实践:二维直方图
我们也可以结合OpenCV的例子生成二维直方图:
IplImage* r_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* g_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* b_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* planes[] = { r_plane, g_plane };
//将HSV图像分离到不同的通道中
cvCvtPixToPlane( src, b_plane, g_plane, r_plane, 0 );
// 生成二维直方图数据结构
int r_bins =256, b_bins = 256;
CvHistogram* hist;
{
int hist_size[] = { r_bins, b_bins };
float r_ranges[] = { 0, 255 }; // hue is [0,180]
float b_ranges[] = { 0, 255 };
float* ranges[] = { r_ranges,b_ranges };
hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY, ranges, 1);
}
//计算一张或多张单通道图像image(s) 的直方图
cvCalcHist( planes, hist, 0, 0 );
刚才的图我们是对应每个横坐标绘制纵坐标的直方块,二维的图需要绘制每个点:
for( int h = 0; h < r_bins; h++ ) {
for( int s = 0; s < b_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);
}
}
最终生成二维直方图:
直方图的应用以后再讨论。