calcHist的使用不当

时间:2017-07-23 14:36:08

标签: c++ opencv image-processing histogram

我的目标是为灰度图像生成直方图。我使用的代码是:

Mat img = imread("leeds-castle.jpg",IMREAD_GRAYSCALE);
Mat hst;
int hstsize = 256;
float ranges[] = { 0,256 };
float *hstrange = { ranges };
calcHist( img, 1,0, Mat(), hst, 1, &hstsize,&hstrange,true,false);
int hst_w = 512, hst_h = 400;
int bin_w = cvRound((double)hst_w / 256);
Mat histimg(hst_w, hst_h, CV_8U);
normalize(hst, hst, 0, histimg.rows, NORM_MINMAX, -1, Mat());
for (int i = 1; i < 256; i++)
{
    line(histimg, Point(bin_w*(i - 1), hst_h - cvRound(hst.at<float>(i - 1))), Point(bin_w*i, hst_h - cvRound(hst.at<float>(i))), 2, 8, 0);
}
imshow("Histogram", histimg);

唯一的错误是使用calcHist()函数。它有什么问题吗?

1 个答案:

答案 0 :(得分:0)

请参阅calcHist上方的评论以确定正确的用法:

// original image
Mat img = imread("leeds-castle.jpg",IMREAD_GRAYSCALE);
// NOTE: check if img.channels is equal to 1

// histogram
Mat hst;

// number of bins
int hstsize = 256;
float ranges[] = { 0,256 };
float *hstrange = { ranges };

// parameters for histogram calculation
bool uniform = true; 
bool accumulate = false;

// calculate histogram
// the '&' was missing here
calcHist( &img, 1,0, Mat(), hst, 1, &hstsize,&hstrange,true,false);