直方圖統計使用的函數是
void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false );1.images是輸入圖片,2.nimages是輸入圖片數目
3.channels:統計的通道,例如{0}或者{0,1,2}
3.mask:掩碼
4.hist:統計輸出結果
5.dims:維數
6.histSize:每一維的直方圖的尺寸大小
7.ranges:直方圖每一維的數據大小范圍。例如:{{0,2555}}(統計1個通道),{{0,2555},{0,2555},{0,2555}}(統計3個通道)
8.最后的參數默認為true,false。我的源代碼:#include <cv.h>#include <opencv2/core/core.hpp> #include <opencv2/imgPRoc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std;using namespace cv;void mycalhist(Mat image){ MatND hist; int bins = 256; int hist_size[] = {bins}; float range[] = { 0, 256 }; const float* ranges[] = { range}; int channels[] = {0}; calcHist(&image, 1, channels, Mat(), // do not use mask hist, 1, hist_size, ranges, true, // the histogram is uniform false); //計算出出現的頻率 int sum=image.cols*image.rows; float p[256]; for(int i=0;i<256;i++){ p[i]=hist.at<float>(i)/(1.0*sum); //cout<<p[i]<<" "; } double max_val; //直方圖的最大值 minMaxLoc(hist, 0, &max_val, 0, 0); //計算直方圖最大值 //畫出直方圖 int maxheight=256; Mat image2=Mat::zeros(256,2*256, CV_8UC3); for(int i=0;i<256;i++){ // 計算高度 double height=(maxheight*hist.at<float>(i))/(1.0*max_val); //畫出對應的高度圖 //坐標體系中的零點坐標定義為圖片的左上角,X軸為圖像矩形的上面那條水平線,從左往右;Y軸為圖像矩形左邊的那條垂直線,從上往下。在Point(x,y)和Rect(x,y)中,第一個參數x代表的是元素所在圖像的列數,第二個參數y代表的是元素所在圖像的行數,而在at(x,y)中是相反的。 rectangle(image2,Point(i*2,255), Point((i+1)*2 - 1, 255-height), CV_RGB(255,255,255)); } imshow("hist",image2); //cout<<endl;}int main( int argc, char** argv ){ Mat image=imread("./1.jpg",CV_LOAD_IMAGE_GRAYSCALE); mycalhist(image); waitKey(0); return 0;}原圖像:
統計結果:
新聞熱點
疑難解答