1 直方图均衡化
void cvEqualizeHist( const CvArr* src, CvArr* dst );//输入 输出,8位单通道图像
opencv直方图采用的方法:
- 计算输入图像的直方图 H
- 直方图归一化,因此直方块和为255
- 计算直方图积分
- 采用H'作为查询表:dst(x,y)=H'(src(x,y))进行图像变换。
测试1 直方图均衡化
直方图均衡化
int i;
IplImage *pImageChannel[4] = { 0, 0, 0, 0 };
IplImage *pSrcImage = cvLoadImage( "24.jpg", 1 ) ;
IplImage *pImage = cvCreateImage(cvGetSize(pSrcImage), pSrcImage->depth, pSrcImage->nChannels);
if( pSrcImage )
{
for( i = 0; i < pSrcImage->nChannels; i++ )
{
pImageChannel[i] = cvCreateImage( cvGetSize(pSrcImage), pSrcImage->depth, 1 );
}
// 信道分离
cvSplit( pSrcImage, pImageChannel[0], pImageChannel[1],pImageChannel[2], pImageChannel[3] );
for( i = 0; i < pImage->nChannels; i++ )
{
cvEqualizeHist( pImageChannel[i], pImageChannel[i] ); // 直方图均衡化
}
// 信道组合
cvMerge( pImageChannel[0], pImageChannel[1], pImageChannel[2],pImageChannel[3], pImage );
cvNamedWindow( "Source");
cvShowImage("Source",pSrcImage);
cvNamedWindow( "cvEqualizeHist");
cvShowImage( "cvEqualizeHist", pImage );
cvWaitKey(0);
测试图像:
2 .直方图对比
double cvCompareHist( const CvHistogram* hist1, const CvHistogram* hist2, int method );
对比的的方法用method表示,主要由以下几种办法:
CV_COMP_CORREL 相关方法:完全匹配为1,完全不匹配为-1,0是无关联
CV_COMP_CHISQR 卡尔:完全匹配是0 ,完全不匹配为无限值
CV_COMP_INTERSECT 直方图相交:完全匹配为1,完全不匹配为-1,0是无关联
CV_COMP_BHATTACHARYYA Bhattacharyya距离,Bhattacharyya 距离只能应用到规一化后的直方图,完全匹配是0 ,完全不匹配为1
在直方图对比前,都应该进行归一化操作,直方图相交的方法效果最好,卡尔和Bhattacharyya距离速度最慢也较精确。
测试代码:
直方图对比
IplImage * image= cvLoadImage("myhand1.jpg");
IplImage * image2= cvLoadImage("myhand2.jpg");
int hist_size=256;
float range[] = {0,255};
float* ranges[]={range};
IplImage* gray_plane = cvCreateImage(cvGetSize(image),8,1);
cvCvtColor(image,gray_plane,CV_BGR2GRAY);
CvHistogram* gray_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
cvCalcHist(&gray_plane,gray_hist,0,0);
cvNormalizeHist(gray_hist,1.0);
IplImage* gray_plane2 = cvCreateImage(cvGetSize(image2),8,1);
cvCvtColor(image2,gray_plane2,CV_BGR2GRAY);
CvHistogram* gray_hist2 = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
cvCalcHist(&gray_plane2,gray_hist2,0,0);
cvNormalizeHist(gray_hist2,1.0);
double com=cvCompareHist(gray_hist,gray_hist2,CV_COMP_CHISQR);
printf("%f\n",com);
cvNamedWindow( "myhand1");
cvShowImage("myhand1",image);
cvNamedWindow( "myhand2");
cvShowImage( "myhand2", image2 );
cvWaitKey();
输出结果:
也就是这两张图像 并没什么相关,如果和源图像对比,输出结果如下: