#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include
#include
using namespace std;
using namespace cv;
int main( int, char** argv )
{
Mat src, dst;
src = imread( argv[1], 1 );
if( src.empty() )
{ return -1; }
vector bgr_planes;
split( src, bgr_planes );
int histSize = 256;
float range[] = { 0, 256 } ;
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
Mat b_hist, g_hist, r_hist;
calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );
// Draw the histograms for B, G and R
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound( (double) hist_w/histSize );
Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );
normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
for( int i = 1; i < histSize; i++ )
{
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(b_hist.at(i)) ),
Scalar( 255, 0, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(g_hist.at(i)) ),
Scalar( 0, 255, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(r_hist.at(i)) ),
Scalar( 0, 0, 255), 2, 8, 0 );
}
namedWindow("calcHist Demo", WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );
waitKey(0);
return 0;
}
(1)**&bgr_planes [0]:**源数组
(2)1:源数组的数量(在这种情况下我们使用1.我们也可以在这里输入一个数组列表)
(3)0:要测量的通道(暗淡)。 在这种情况下,它只是强度(每个数组是单通道)所以我们只写0。
(4)Mat():要在源数组上使用的掩码(指示要忽略的像素的零)。 如果没有定义,则不使用它
(5)b_hist:将存储直方图的Mat对象
(6)1:直方图维度。
(7)histSize:每个使用维度的bin数
(8)histRange:每个维度要测量的值范围
(9)均匀和累积:箱尺寸相同,直方图在开始时被清除。
使用如下所示的图像作为输入参数:
生成以下直方图: