码迷,mamicode.com
首页 > 其他好文 > 详细

openCV构造直方图

时间:2014-08-25 17:04:34      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   color   os   io   for   ar   2014   

学习openCV上的一个例子,根据输入的图像构造色相饱和度的直方图

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


void main()
{
	
	
	//以原始通道数读取图片1
	IplImage* img1 = cvLoadImage("D://vc6.0//MSDev98//MyProjects//MachineVision//TestPic//PeppersRGB.bmp",CV_LOAD_IMAGE_UNCHANGED);
	//创建图片1的一个空副本
	IplImage* img2 = cvCreateImage(cvGetSize(img1), 8, 3);

	//从RGB色彩空间转换到HSV色彩空间
	cvCvtColor(img1, img2, CV_BGR2HSV);

	IplImage* h_plane = cvCreateImage(cvGetSize(img1), 8, 1);
	IplImage* s_plane = cvCreateImage(cvGetSize(img1), 8, 1);
	IplImage* v_plane = cvCreateImage(cvGetSize(img1), 8, 1);
	IplImage* planes[] = {h_plane, s_plane};

	//将HSV图像分成H,S,V三个通道分别操作
	cvCvtPixToPlane(img2, h_plane, s_plane, v_plane, 0);


	//建立直方图
	//确定直方图中方块的数量
	int h_bins = 30;
	int s_bins = 32;

	CvHistogram* hist;
	int		hist_size[] = {h_bins, s_bins};

	//设定h和s直方图横坐标的范围
	float	h_ranges[] = {0, 180};
	float	s_ranges[] = {0, 255};
	float*  ranges[] = {h_ranges, s_ranges};

	//创建一个二维直方图,1代表均匀分割
	hist = cvCreateHist(2, hist_size, CV_HIST_ARRAY, ranges, 1);


	//计算直方图
	cvCalcHist(planes, hist, 0, 0);

	//归一化
	cvNormalizeHist(hist, 1.0);

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

	cvZero(histogram);

	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(histogram, 
				cvPoint(h*scale, s*scale), 
				cvPoint((h+1)*scale - 1, (s+1)*scale - 1),
				CV_RGB(intensity,intensity,intensity),
				CV_FILLED
				);
		}
	}
	//命名窗口
	cvNamedWindow("Source", CV_WINDOW_AUTOSIZE);
	cvShowImage("Source", img1);
	
	cvNamedWindow("Histogram", CV_WINDOW_AUTOSIZE);
	cvShowImage("Histogram", histogram);
	cvWaitKey(0);
	
	cvDestroyAllWindows();
	cvReleaseImage(&img1);
	cvReleaseImage(&histogram);	


}

bubuko.com,布布扣

bubuko.com,布布扣

openCV构造直方图

标签:des   blog   http   color   os   io   for   ar   2014   

原文地址:http://blog.csdn.net/lampqiu/article/details/38822131

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!