#ifndef HIST_IMG_H_INCLUDED#define HIST_IMG_H_INCLUDED#include <opencv\cv.h>#include <opencv\cxcore.h>#include <iostream>#define LOW_BOUND (0.f)#define HIGH_BOUND (255.f)#define BINS (10)#define BINWIDTH (20)/**- Get a histogram image of the input image. @param pImage an 1 channel image @return Returns a histogram image-**/IplImage* HistImage(IplImage* pImage);#endif // HIST_IMG_H_INCLUDED
2. [文件] hist_img.cpp
#include "hist_img.h"using namespace std;IplImage* HistImage(IplImage* pImage){ if (!pImage) { cerr<<"The input image is NULL."<<endl; return NULL; } if (1 != pImage->nChannels) { cerr<<"The input image's channels is not equal to 1."<<endl; return NULL; } // create a histogram int histSize = BINS; float** range = new float*; range[0] = new float[2]; range[0][0] = LOW_BOUND; range[0][1] = HIGH_BOUND; CvHistogram* pHist = cvCreateHist(1,&histSize,CV_HIST_ARRAY,range); cvCalcHist(&pImage,pHist); float fMaxValue = 0.f; cvGetMinMaxHistValue(pHist,0,&fMaxValue,0,0); // generate the histogram image int height = 240; int interval = cvRound(BINWIDTH * 2 / 5); int width = histSize * BINWIDTH + (histSize - 1)*interval; IplImage* pHistImg = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,3); cvZero(pHistImg); for (int i = 0;i < histSize;i++) { float fBinValue = cvQueryHistValue_1D(pHist,i); int BinHeight = cvRound(fBinValue / fMaxValue * height); CvScalar color = cvScalar(i*255/histSize,255,255,0); CvPoint point1 = cvPoint(i*(BINWIDTH + interval),height); CvPoint point2 = cvPoint(point1.x + BINWIDTH,height - BinHeight); cvRectangle(pHistImg,point1,point2,color,-1,8,0); } cvReleaseHist(&pHist); delete[] range[0]; delete range; return pHistImg;}