直方图用法示例

这个程序根据输入的图像计算出一个色相饱和度直方图,然后利用网格的方式将直方图以网格形式显示。

Code:

#include<cv.h>
#include<highgui.h>
#include<stdio.h>

int main()
{
	IplImage* src = NULL;
	src = cvLoadImage ("lena.jpg", 1);
	
	IplImage* hsv = cvCreateImage (cvGetSize(src), 8, 3);
	cvCvtColor (src, hsv, CV_BGR2HSV);
	
	IplImage* h_plane = cvCreateImage (cvGetSize(src), 8, 1);
	IplImage* s_plane = cvCreateImage (cvGetSize(src), 8, 1);
	IplImage* v_plane = cvCreateImage (cvGetSize(src), 8, 1);
	IplImage* planes[] = {h_plane, s_plane};
	cvCvtPixToPlane (hsv, h_plane, s_plane, v_plane, 0); 

	/*创建和计算直方图*/

	int h_bins = 30;
	int s_bins = 32;
	CvHistogram* hist = NULL;
	int hist_size[] = {h_bins, s_bins};
	float h_ranges[] = {0, 180};
	float s_ranges[] = {0, 255};
	float* ranges[] = {h_ranges, s_ranges};
	hist = cvCreateHist (2, hist_size, CV_HIST_ARRAY, ranges, 1);
	cvCalcHist (planes, hist, 0, 0); //计算直方图
	cvNormalizeHist (hist, 1.0);   //归一化

	/*测试匹配度并输出*/
	
	/*double like = cvCompareHist (hist, hist, CV_COMP_INTERSECT);
	printf("%lf\n", like);*/

	/*创建一个图像来可视化我们的直方图*/

	int scale = 10;
	IplImage* hist_img = cvCreateImage (cvSize(h_bins * scale, s_bins * scale), 8, 3);
	cvZero (hist_img);

	/*用小的灰度方格填充hist_img*/

	float max_value = 0;
	cvGetMinMaxHistValue (hist, 0, &max_value, 0, 0);
	for (int h = 0; h < h_bins; h++)
	{
		for (int s = 0; s < s_bins; s++)
		{
			float bin_val = cvQueryHistValue_2D (hist, h, s);
			int intensity = cvRound (bin_val * 255 / max_value);
			cvRectangle (hist_img, cvPoint(h*scale, s*scale), cvPoint((h+1)*scale-1, (s+1)*scale-1), 
				CV_RGB(intensity, intensity, intensity),CV_FILLED);
		}
	}
	cvNamedWindow ("src", 1);
	cvShowImage ("src", src);
	cvNamedWindow ("H-S histogram", 1);
	cvShowImage ("H-S histogram", hist_img);

	cvWaitKey (0);

	cvReleaseImage (&src);
	cvReleaseImage (&hsv);
	cvReleaseImage (&hist_img);
	cvReleaseHist (&hist);

	return 0;
}


你可能感兴趣的:(直方图用法示例)