灰度直方图
cv:: Mat opencvTool:: calculateHistogram ( const cv:: Mat& image)
{
cv:: Mat grayscale_image;
if ( image. channels ( ) > 1 )
{
cv:: cvtColor ( image, grayscale_image, cv:: COLOR_BGR2GRAY) ;
}
else
{
grayscale_image = image. clone ( ) ;
}
cv:: Mat hist;
int histSize = 256 ;
float range[ ] = { 0 , 256 } ;
const float * histRange = { range } ;
bool uniform = true , accumulate = false ;
cv:: calcHist ( & grayscale_image, 1 , nullptr , cv:: Mat ( ) , hist, 1 , & histSize, & histRange, uniform, accumulate) ;
int hist_w = 512 , hist_h = 400 ;
int bin_w = cvRound ( ( double ) hist_w / histSize) ;
cv:: Mat histImage ( hist_h, hist_w, CV_8UC3, cv:: Scalar ( 255 , 255 , 255 ) ) ;
cv:: normalize ( hist, hist, 0 , histImage. rows, cv:: NORM_MINMAX, - 1 , cv:: Mat ( ) ) ;
for ( int i = 1 ; i < histSize; i++ )
{
cv:: line ( histImage, cv:: Point ( bin_w * ( i - 1 ) , hist_h - cvRound ( hist. at < float > ( i - 1 ) ) ) ,
cv:: Point ( bin_w * ( i) , hist_h - cvRound ( hist. at < float > ( i) ) ) ,
cv:: Scalar ( 0 , 0 , 0 ) , 2 , 8 , 0 ) ;
}
return histImage;
}