calcHist()不按预期返回绿色直方图

时间:2014-05-30 08:49:43

标签: opencv image-processing histogram

我在Ubuntu 12.04上使用OpenCV。没有花哨的IDE。只需从命令行编译和运行。这是我用于计算彩色图像直方图的代码。 “lion.jpg”是彩色图像。这段代码大量借鉴了官方OpenCV教程中的直方图计算。  我得到红色和蓝色直方图就好了。但是绿色直方图都是乱七八糟的。 The image of the histogram.

我的代码是:

#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include<iostream>
#include<stdio.h>
using namespace cv;
using namespace std;
int main(int argc,char *argv[])
{
Mat img,b_hist,g_hist,r_hist;
vector<Mat> channels;
namedWindow("Histogram",CV_WINDOW_NORMAL);
int bins=256;
float range[]={0,255};
const float* histrange={range};
img=imread("lion.jpg",CV_LOAD_IMAGE_COLOR);
split(img,channels);
calcHist(&channels[0],1,0,Mat(),b_hist,1,&bins,&histrange,true,false);
calcHist(&channels[1],1,0,Mat(),g_hist,1,&bins,&histrange,true,false);
calcHist(&channels[2],1,0,Mat(),r_hist,1,&bins,&histrange,true,false);
Mat histimage(600,600,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=0;i<bins;i++)
{
line(histimage,Point(2*i,histimage.rows-b_hist.at<float>(i)),Point(2*   (i+1),histimage.rows-b_hist.at<float>(i+1)),Scalar(255,0,0));
line(histimage,Point(2*1,histimage.rows-g_hist.at<float>(i)),Point(2*(i+1),histimage.rows-g_hist.at<float>(i+1)),Scalar(0,255,0));
line(histimage,Point(2*i,histimage.rows-r_hist.at<float>(i)),Point(2*(i+1),histimage.rows-r_hist.at<float>(i+1)),Scalar(0,0,255));
}
imshow("Histogram",histimage);
waitKey(0);
destroyWindow("Histogram");
return 1;
}

1 个答案:

答案 0 :(得分:1)

你有拼写错误

line(histimage,Point(2*1,histimage.rows-g_hist.at<float>(i)),Point(2*(i+1),histimage.rows-g_hist.at<float>(i+1)),Scalar(0,255,0));

而不是正确的

line(histimage,Point(2*i,histimage.rows-g_hist.at<float>(i)),Point(2*(i+1),histimage.rows-g_hist.at<float>(i+1)),Scalar(0,255,0));