输入图像:
输出直方图分布图像:
输入图像:
输出直方图分布图像:
[c] view plain copy
- <pre name="code" class="cpp">#include <cv.h>
- #include <highgui.h>
- #include <iostream>
- using namespace std;
-
-
-
- int main( int argc, char** argv )
- {
- IplImage * src= cvLoadImage("F:\\test3.jpg");
-
- IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 );
- 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 };
-
-
- int h_bins = 16, s_bins = 8;
- int hist_size[] = {h_bins, s_bins};
-
-
- float h_ranges[] = { 0, 180 };
-
-
- float s_ranges[] = { 0, 255 };
- float* ranges[] = { h_ranges, s_ranges };
-
-
- cvCvtColor( src, hsv, CV_BGR2HSV );
- cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );
-
-
- CvHistogram * hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY, ranges, 1 );
-
- cvCalcHist( planes, hist, 0, 0 );
-
-
- float max_value;
- cvGetMinMaxHistValue( hist, 0, &max_value, 0, 0 );
-
-
-
- int height = 240;
- int width = (h_bins*s_bins*6);
- IplImage* hist_img = cvCreateImage( cvSize(width,height), 8, 3 );
- cvZero( hist_img );
-
-
- IplImage * hsv_color = cvCreateImage(cvSize(1,1),8,3);
- IplImage * rgb_color = cvCreateImage(cvSize(1,1),8,3);
- int bin_w = width / (h_bins * s_bins);
- for(int h = 0; h < h_bins; h++)
- {
- for(int s = 0; 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);
-
-
- cvSet2D(hsv_color,0,0,cvScalar(h*180.f / h_bins,s*255.f/s_bins,255,0));
- cvCvtColor(hsv_color,rgb_color,CV_HSV2BGR);
- CvScalar color = cvGet2D(rgb_color,0,0);
-
- cvRectangle( hist_img, cvPoint(i*bin_w,height),
- cvPoint((i+1)*bin_w,height - intensity),
- color, -1, 8, 0 );
- }
- }
-
- cvNamedWindow( "Source", 1 );
- cvShowImage( "Source", src );
-
- cvNamedWindow( "H-S Histogram", 1 );
- cvShowImage( "H-S Histogram", hist_img );
-
- cvWaitKey(0);
- }</pre><br><br><span style="color:#009900"></span>
对于颜色直方图的统计,应该还可以用更多的该进,诸如当S分量小于给定值时,不同H,人眼看上去都是白色,可以将这些颜色的统计归并到白色中去。
[编辑]作者
出处:http://wiki.OpenCV.org.cn/index.PHP/%E5%9B%BE%E5%83%8F%E9%A2%9C%E8%89%B2%E5%88%86%E5%B8%83%E7%9B%B4%E6%96%B9%E5%9B%BE
public static IntPtr cvCreateHist(
int dims,
int[] sizes,
HIST_TYPE type,
IntPtr[] ranges,
int uniform
)
各个成员的意思结合下图来理解:
dim是表示几维空间,即一般彩色图像是3通道的,dim=3;而灰度图是1通道的,dim=1
sizes如上图有10个方块,即sizes=10
type我用的时候是CV_HIST_ARRAY,具体请参照这里。
ranges如上图最右边的数字100。这里猫仔有话说,即图像若为IPL_DEPTH_8U,即深度为8,则设成255比较合适,若深度为8位的图像ranges设为2550,则图像上的像素点都会统计在0~255中(即第一个直方图方块中)。
uniform我用的时候设为1,具体请参照这里。