計算圖像image(s) 的 直方圖
void cvCalcHist( IplImage** image, CvHistogram* hist, int accumulate=0, const CvArr* mask=NULL );
image
輸入圖像s (雖然也可以使用 cvMat** ).
hist
直方圖指針
accumulate
累計標識。如果設定,則直方圖在開始時不被清零。這個特徵保證可以為多個圖像計算一個單獨的直方圖,或者線上更新直方圖。
mask
操作 mask, 確定輸入圖像的哪個象素被計數
函式 cvCalcHist 計算一張或多張單通道圖像的直方圖(譯者註:若要計算多通道,可像以下例子那樣用多個單通道圖來表示)。 用來增加直方塊的數組元素可從相應輸入圖像的同樣位置提取。 Sample. 計算和顯示彩色圖像的 2D 色調-飽和度圖像
#include
#include
int main( int argc, char** argv )
{
IplImage* src;
if( argc == 2 && (src= cvLoadImage(argv[1], 1))!= 0)
{
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 };
IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 );
int h_bins = 30, s_bins = 32; int hist_size[] = {h_bins, s_bins};
/*hue varies from 0 (~0°red) to 180 (~360°red again) */
float h_ranges[] = { 0, 180 };
/* saturation varies from 0 (black-gray-white) to 255 (pure spectrum color) */
float s_ranges[] = { 0, 255 }; float* ranges[] = { h_ranges, s_ranges }; int scale = 10;
IplImage* hist_img = cvCreateImage(CvSize(h_bins*scale,s_bins*scale), 8, 3 );
CvHistogram* hist;
float max_value = 0;
int h, s;
cvCvtColor( src, hsv, CV_BGR2HSV );
cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );
hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY, ranges, 1 );
cvCalcHist( planes, hist, 0, 0 );
cvGetMinMaxHistValue( hist, 0, &max_value, 0, 0 );
cvZero( hist_img );
for( h = 0; h < h_bins; h++ )
{
for( s = 0; s < s_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),
/* graw a grayscale histogram. if you have idea how to do it nicer let us know */
CV_FILLED );
}
}
cvNamedWindow( "Source", 1 );
cvShowImage( "Source", src );
cvNamedWindow( "H-S Histogram", 1 );
cvShowImage( "H-S Histogram", hist_img ); cvWaitKey(0);
}
}