#include "highgui.h" #include "cv.h" #include <iostream> #include <iomanip> using namespace std; int main() { IplImage* src = cvLoadImage("lena.jpg",0); IplImage* histimg = 0;//存放绘制的直方图 CvHistogram *hist = 0; int hdims = 256; //划分直方块的个数,越高越精确 float hranges_arr[] = {0,255}; float* hranges = hranges_arr; int bin_w; float max_val; int i; cvNamedWindow("src",1); cvNamedWindow("Histogram",1); hist = cvCreateHist(1,&hdims,CV_HIST_ARRAY,&hranges,1);//创建直方图 histimg = cvCreateImage(cvSize(320,320),8,3); cvZero(histimg); cvCalcHist(&src,hist,0,0);//计算直方图 cvGetMinMaxHistValue(hist,0,&max_val,0,0);//找出直方图的最大值 cvConvertScale(hist->bins,hist->bins,max_val ? 255/max_val : 0, 0);//对计算出来的直方图高度缩放到【0-255】 bin_w = histimg->width / hdims;//计算每一块直方图占的宽度 //画直方图 for (i=0;i<hdims;i++) { double val = (cvGetReal1D(hist->bins,i)*histimg->height)/255; CvScalar color = CV_RGB(255,255,0); cvRectangle(histimg,cvPoint((i+1)*bin_w,(int)(histimg->height-val)),cvPoint(i*bin_w,histimg->height),color,1,8,0); } cvShowImage("src",src); cvShowImage("Histogram",histimg); cvWaitKey(0); }