学习OpenCV——绘制彩色直方图(HSV2BGR)

#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace std; int main( int argc, char** argv )
{
IplImage * src= cvLoadImage("D:/2.jpg"); IplImage* hsv = cvCreateImage( cvGetSize(src), , );
IplImage* h_plane = cvCreateImage( cvGetSize(src), , );
IplImage* s_plane = cvCreateImage( cvGetSize(src), , );
IplImage* v_plane = cvCreateImage( cvGetSize(src), , );
IplImage* planes[] = { h_plane, s_plane }; /** H 分量划分为16个等级,S分量划分为8个等级 */
int h_bins = , s_bins = ;
int hist_size[] = {h_bins, s_bins}; /** H 分量的变化范围 */
float h_ranges[] = { , }; /** S 分量的变化范围*/
float s_ranges[] = { , };
float* ranges[] = { h_ranges, s_ranges }; /** 输入图像转换到HSV颜色空间 */
cvCvtColor( src, hsv, CV_BGR2HSV );
cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, ); /** 创建直方图,二维, 每个维度上均分 */
CvHistogram * hist = cvCreateHist( , hist_size, CV_HIST_ARRAY, ranges, );
/** 根据H,S两个平面数据统计直方图 */
cvCalcHist( planes, hist, , ); /** 获取直方图统计的最大值,用于动态显示直方图 */
float max_value;
cvGetMinMaxHistValue( hist, , &max_value, , ); /** 设置直方图显示图像 */
int height = ;
int width = (h_bins*s_bins*);
IplImage* hist_img = cvCreateImage( cvSize(width,height), , );
cvZero( hist_img ); /** 用来进行HSV到RGB颜色转换的临时单位图像 */
IplImage * hsv_color = cvCreateImage(cvSize(,),,);
IplImage * rgb_color = cvCreateImage(cvSize(,),,);
int bin_w = width / (h_bins * s_bins);
for(int h = ; h < h_bins; h++)
{
for(int s = ; s < s_bins; s++)
{
int i = h*s_bins + s;
/** 获得直方图中的统计次数,计算显示在图像中的高度 */
float bin_val = cvQueryHistValue_2D( hist, h, s );
int intensity = cvRound(bin_val*height/max_value);//Round, Floor, Ceil 转换浮点数为整数(cvRound 返回和参数最接近的整数值。 cvFloor 返回不大于参数的最大整数值。cvCeil 返回不小于参数的最小整数值。) /** 获得当前直方图代表的颜色,转换成RGB用于绘制 */
cvSet2D(hsv_color,,,cvScalar(h*.f / h_bins,s*.f/s_bins,,));
cvCvtColor(hsv_color,rgb_color,CV_HSV2BGR);
CvScalar color = cvGet2D(rgb_color,,); cvRectangle( hist_img, cvPoint(i*bin_w,height),
cvPoint((i+)*bin_w,height - intensity),
color, -, , );
}
} cvNamedWindow( "Source", );
cvShowImage( "Source", src ); cvNamedWindow( "H-S Histogram", );
cvShowImage( "H-S Histogram", hist_img ); cvWaitKey();
}

from: http://blog.csdn.net/yangtrees/article/details/7433598

上一篇:【图像处理】基于OpenCV实现图像直方图的原理


下一篇:OpenCV(7)-图像直方图