CvHistogram结构体
typedef struct CvHistogram
{
int type;
CvArr* bins; //存放每个灰度级数目的数组指针
float thresh[CV_MAX_DIM][2]; //均匀直方图
float** thresh2; //非均匀直方图
CvMatND mat; //直方图数组的内部数据结构
}
CvHistogram;
创建直方图cvCreateHist(),函数原型:
CVAPI(CvHistogram*) cvCreateHist( int dims, int* sizes, int type,
float** ranges CV_DEFAULT(NULL),
int uniform CV_DEFAULT(1));
dims,维数
sizes,直方图大小(横轴长度)
type,密集矩阵(CV_HIST_ARRAY)或者是稀疏矩阵(CV_HIST_SPARSE)
ranges,灰度范围
uniform,归一化标志
cvSetHistBinRanges(),用于设置灰度范围range,函数原型:
CVAPI(void) cvSetHistBinRanges( CvHistogram* hist, float** ranges,
int uniform CV_DEFAULT(1));
根据给出数据建立直方图用cvMakeHistHeaderForArray(),,函数原型:
CVAPI(CvHistogram*) cvMakeHistHeaderForArray(
int dims, int* sizes, CvHistogram* hist,
float* data, float** ranges CV_DEFAULT(NULL),
int uniform CV_DEFAULT(1));
参数定义同上
计算直方图cvCalcHist(),函数原型:
CV_INLINE void cvCalcHist( IplImage** image, CvHistogram* hist,
int accumulate CV_DEFAULT(0),
const CvArr* mask CV_DEFAULT(NULL) )
image,源图像
hist,输出直方图
accumulate,直方图标志位
mask,直方图计算标志位
直方图归一化,CVAPI(void) cvNormalizeHist( CvHistogram* hist, double factor );
直方图中获取最大最小值cvGetMinMaxHistValue(),函数原型:
CVAPI(void) cvGetMinMaxHistValue( const CvHistogram* hist,
float* min_value, float* max_value,
int* min_idx CV_DEFAULT(NULL),
int* max_idx CV_DEFAULT(NULL));
测试用图:
和
程序代码:
#include <highgui.h>
#include<cv.h>
#include <opencv2/legacy/legacy.hpp>
using namespace std;
int main()
{
IplImage *img_in = cvLoadImage("test.jpg");
IplImage *img_gray = cvCreateImage(cvGetSize(img_in),IPL_DEPTH_8U,1);
IplImage *img_canny = cvCreateImage(cvGetSize(img_in),IPL_DEPTH_8U,1);
IplImage *img_out = cvCreateImage(cvGetSize(img_in),IPL_DEPTH_8U,3);
cvNamedWindow("img_in",CV_WINDOW_AUTOSIZE);
cvShowImage("img_in",img_in);
cvCvtColor(img_in,img_gray,CV_BGR2GRAY);
cvNamedWindow("img_gray",CV_WINDOW_AUTOSIZE);
cvShowImage("img_gray",img_gray);
int hist_size=256;//直方图的横轴长度
int hist_height=256;//直方图的纵轴高度
float range[]={0,255}; //灰度级的范围
float* ranges[]={range};
CvHistogram *gray_hist=cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);//创建直方图
cvCalcHist(&img_gray,gray_hist,0,0);//计算直方图
cvNormalizeHist(gray_hist,1.0);//归一化直方图
int scale=3;//横轴和纵轴的比例
IplImage *image_hist=cvCreateImage(cvSize(hist_size*scale,hist_height),IPL_DEPTH_8U,3);//创建直方图的区域
cvZero(image_hist);//整张图赋值为0,即黑色
float max_value=0;
cvGetMinMaxHistValue(gray_hist,0,&max_value,0,0);//在输出直方图中找到最小值和最大值
for(int i=0;i<hist_size;i++)
{
float bin_val=cvQueryHistValue_1D(gray_hist,i);//获取直方图中像素i的值
int intensity=cvRound(bin_val*hist_height/max_value);//要绘制的高度
cvRectangle(image_hist,cvPoint(i*scale,hist_height-1),cvPoint((i+1)*scale-1,hist_height-intensity),CV_RGB(255,255,255));
}
cvNamedWindow("H-S Histogram",CV_WINDOW_AUTOSIZE);
cvShowImage("H-S Histogram",image_hist);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&img_in);
cvReleaseImage(&img_gray);
cvReleaseImage(&image_hist);
cvReleaseHist(&gray_hist);//释放直方图
return 0;
}
运行结果: