灰度直方圖是灰度級的函數,它表示圖像中具有某種灰度級的像素的個數,反映了圖像中某種灰度出現的頻率。
如果將圖像總像素亮度(灰度級別)看成是一個隨機變量,則其分布情況就反映了圖像的統計特性,這可用probability density function (PDF)來刻畫和描述,表現為灰度直方圖。
灰度直方圖的分布函數為:
h(k)=nk
其中,k是值第k個灰度級,nk是灰度級為rk的像素總和。如果是8位灰度圖像,k=0,1,2,...,255
下面代碼如下:
1 #include<cv.h> 2 #include<highgui.h> 3 4 using namespace cv; 5 using namespace std; 6 7 int main() 8 { 9 IplImage *src = cvLoadImage("D:\\Opencv\\Images\\GrayLena.bmp"); 10 int pix[256]; 11 for (int i = 0; i < 256; i++) 12 pix[i] = 0; 13 int grayValue; 14 for (int i = 0; i < src->height;i++) 15 for (int j = 0; j < src->width; j++) 16 { 17 grayValue = ((char*)(src->imageData + j*src->widthStep))[i]; 18 pix[grayValue]++; 19 } 20 21 int max = 0; 22 for (int i = 0; i<256; i++) 23 { 24 if (pix[i]>max) 25 { 26 max = pix[i]; 27 } 28 } 29 IplImage* dst = cvCreateImage(cvSize(400, 300), 8, 3); 30 cvSet(dst, cvScalarAll(255), 0); 31 double bin_width = (double)dst->width / 256; 32 double bin_unith = (double)dst->height / max; 33 for (int i = 0; i<256; i++) 34 { 35 CvPoint p0 = cvPoint(i*bin_width, dst->height); 36 CvPoint p1 = cvPoint((i + 1)*bin_width, dst->height - pix[i] * bin_unith); 37 cvRectangle(dst, p0, p1, cvScalar(0, 255), -1, 8, 0); 38 } 39 40 cvNamedWindow("destImage"); 41 cvShowImage("destImage",dst); 42 cvWaitKey(); 43 cvReleaseImage(&dst); 44 cvDestroyWindow("destImage"); 45 return 0; 46 }