计算机视觉
图像处理

opencv绘制灰度直方图

代码之一

#include 
#include 
#pragma comment( lib, "cv.lib" )
#pragma comment( lib, "cxcore.lib" )
#pragma comment( lib, "highgui.lib" )
int main()
{
         IplImage* src=cvLoadImage("lena.jpg",0);
         int width=src->width;
         int height=src->height;
         int step=src->widthStep;
         uchar* data=(uchar *)src->imageData;
         int hist[256]={0};
         for(int i=0;i<height;i++)
         {
                   for(int j=0;j<width;j++)
                   {
                            hist[data[i*step+j]]++;
                   }
         }
         int max=0;
         for(i=0;i<256;i++) { if(hist[i]>max)
                   {
                            max=hist[i];
                   }
         }
         IplImage* dst=cvCreateImage(cvSize(400,300),8,3);
         cvSet(dst,cvScalarAll(255),0);
         double bin_width=(double)dst->width/256;
         double bin_unith=(double)dst->height/max;
         for(i=0;i<256;i++) { CvPoint p0=cvPoint(i*bin_width,dst->height);
                   CvPoint p1=cvPoint((i+1)*bin_width,dst->height-hist[i]*bin_unith);
                   cvRectangle(dst,p0,p1,cvScalar(0,255),-1,8,0);
         }
         cvNamedWindow("src",1);
         cvShowImage("src",src);
         cvNamedWindow("dst",1);
         cvShowImage("dst",dst);
         cvWaitKey(0);
         cvDestroyAllWindows();
         cvReleaseImage(&src);
         cvReleaseImage(&dst);
         return 0;
}

代码之二

#include 
#include 
#pragma comment( lib, "cv.lib" )
#pragma comment( lib, "cxcore.lib" )
#pragma comment( lib, "highgui.lib" )
int main()
{
         IplImage* src=cvLoadImage("lena.jpg",0);
         int size=256;
         float range[]={0,255};
         float* ranges[]={range};
         CvHistogram* hist=cvCreateHist(1,&size,CV_HIST_ARRAY,ranges,1);
         cvCalcHist(&src,hist,0,NULL);
         float max=0;
         cvGetMinMaxHistValue(hist,NULL,&max,NULL,NULL);
         IplImage* dst=cvCreateImage(cvSize(400,300),8,3);
         cvSet(dst,cvScalarAll(255),0);
         double bin_width=(double)dst->width/size;
         double bin_unith=(double)dst->height/max;
         for(int i=0;i<size;i++) { CvPoint p0=cvPoint(i*bin_width,dst->height);
                   CvPoint p1=cvPoint((i+1)*bin_width,dst->height-cvGetReal1D(hist->bins,i)*bin_unith);
                   cvRectangle(dst,p0,p1,cvScalar(0,255),-1,8,0);
         }
         cvNamedWindow("src",1);
         cvShowImage("src",src);
         cvNamedWindow("dst",1);
         cvShowImage("dst",dst);
         cvWaitKey(0);
         cvDestroyAllWindows();
         cvReleaseImage(&src);
         cvReleaseImage(&dst);
         return 0;
}

转载注明来源:CV视觉网 » opencv绘制灰度直方图

分享到:更多 ()
扫描二维码,给作者 打赏
pay_weixinpay_weixin

请选择你看完该文章的感受:

0不错 0超赞 0无聊 0扯淡 0不解 0路过

评论 3

评论前必须登录!