直方图数据结构:
typedef struct CvHistogram
{int type;
CvArr* bins;
float thresh[CV_MAX_DIM][2]; /* For uniform histograms. */
float** thresh2; /* For non-uniform histograms. */
CvMatND mat; /* Embedded matrix header for array histograms. */
}
CvHistogram;
直方图内部很多内部数据存储在mat中
创建新的直方图:
CVAPI(CvHistogram*) cvCreateHist( int dims, int* sizes, int type, float** ranges CV_DEFAULT(NULL), int uniform CV_DEFAULT(1));
dims直方图的维数,sizes维数的bins的总数,数组的维数和dims相同,ranges每一个bins的分割,uniform = 1表示均匀分布
计算直方图:
CV_INLINE void cvCalcHist( IplImage** image, CvHistogram* hist,int accumulate CV_DEFAULT(0),const CvArr* mask CV_DEFAULT(NULL) )
image为原图像的指针数组,多通道图像要分解为单通道图像,在组合成数组,就可以生成多通道直方图;
获取hist中的数据
cvQueryHistValue_1D 为宏定义
#include
#include
#include
#include
using namespace cv;
int main()
{
IplImage *img = cvLoadImage("lena.jpg");
IplImage *dst = cvCreateImage(cvSize(img->width,img->height),img->depth,img->nChannels);
IplImage *b_plane = cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,1);
IplImage *g_plane = cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,1);
IplImage *r_plane = cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,1);
cvSplit(img,b_plane,g_plane,r_plane,NULL);
int size[] = {100};
float range[] = {0,255};
float *ranges[] = {range};
CvHistogram *hist = cvCreateHist(1,size,CV_HIST_ARRAY,ranges,1);
cvCalcHist(&b_plane,hist);
float max_value = 0;
float min_value = 0;
cvGetMinMaxHistValue(hist,&min_value,&max_value);
IplImage *hist_img = cvCreateImage(cvSize(100*10,500),IPL_DEPTH_8U,1);
hist_img->origin = 1; //原点设为右下
cvZero(hist_img);
for (int i = 0; i<100;i++)
{
float bin_val = cvQueryHistValue_1D(hist,i);
//float bin_val = *(hist->mat.data.fl + i);
cvRectangle(hist_img,cvPoint(i*10,cvRound(bin_val*500/max_value)),cvPoint((i+1)*10,0),cvScalar(255),CV_FILLED);
}
cvNamedWindow("lena");
cvShowImage("lena",hist_img);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&dst);
cvDestroyWindow("lena");
}