RGB三个通道分别计算直方图

利用OpenCV 对图像像素进行操作,将图像分成三个通道,并分别计算归一化直方图,并在窗口中以图形的方式显示出来。


// Test.cpp : 三通道灰度直方图
//RGB三个通道分别计算直方图

#include "stdafx.h"
#include 
#include 

int _tmain_4(int argc, _TCHAR* argv[])
{
	IplImage * src = cvLoadImage("1.jpg");
	IplImage* gray_plane = cvCreateImage(cvGetSize(src),8,1);
	IplImage* red_plane = cvCreateImage(cvGetSize(src),8,1);
	IplImage* green_plane = cvCreateImage(cvGetSize(src),8,1);
	IplImage* blue_plane = cvCreateImage(cvGetSize(src),8,1);

	//分割多通道数组成几个单通道数组或者从数组中提取一个通道
	cvCvtPixToPlane(src,blue_plane,green_plane,red_plane,0);
	cvCvtColor(src,gray_plane,CV_BGR2GRAY);

	int hist_size = 256;    //直方图尺寸
	int hist_height = 256;
	float range[] = {0,255};	//灰度级的范围
	float* ranges[] = {range};

	//创建一维直方图,统计图像在[0,255]像素的均匀分布
	CvHistogram* gray_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
	CvHistogram* red_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
	CvHistogram* green_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
	CvHistogram* blue_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);

	//计算灰度图像的一维直方图
	cvCalcHist(&gray_plane,gray_hist,0,0);
	cvCalcHist(&red_plane,red_hist,0,0);
	cvCalcHist(&green_plane,green_hist,0,0);
	cvCalcHist(&blue_plane,blue_hist,0,0);

	//归一化直方图
	cvNormalizeHist(gray_hist,1.0);
	cvNormalizeHist(red_hist,1.0);
	cvNormalizeHist(green_hist,1.0);
	cvNormalizeHist(blue_hist,1.0);


	int scale = 1;
	//创建一张一维直方图的“图像”,横坐标为灰度级,纵坐标为像素个数(*scale)
	//图像位深度为8位整形,每个元素通道号为3
	IplImage* hist_image = cvCreateImage(cvSize(hist_size*2*scale,hist_height*2),8,3);
	//初始化,图像清零
	cvZero(hist_image);
	//统计直方图中的最大直方块
	//float max_value = 0;
	//cvGetMinMaxHistValue(gray_hist,0,&max_value,0,0);
	float max_value_r = 0;
	float max_value_g = 0;
	float max_value_b = 0;
	float max_value_gray = 0;
	cvGetMinMaxHistValue(red_hist,0,&max_value_r,0,0);
	cvGetMinMaxHistValue(green_hist,0,&max_value_g,0,0);
	cvGetMinMaxHistValue(blue_hist,0,&max_value_b,0,0);
	cvGetMinMaxHistValue(gray_hist,0,&max_value_gray,0,0);
	
	//分别将每个直方块的值绘制到图中
	for(int i=0;i


你可能感兴趣的:(C++)