比较两个直方图的相似程度
函数原型和使用方法都很简单
/* Compares two histogram */
CVAPI(double) cvCompareHist( const CvHistogram* hist1,
const CvHistogram* hist2,
int method);
method是指4种不同的匹配方法
测试用图(两组,一组是找茬图,一组是镜像图):
程序代码:
#include <highgui.h>
#include<cv.h>
#include <opencv2/legacy/legacy.hpp>
using namespace std;
int main()
{
IplImage *img1 = cvLoadImage("test3.jpg");
IplImage *img2 = cvLoadImage("test4.jpg");
IplImage *img_gray1 = cvCreateImage(cvGetSize(img1),IPL_DEPTH_8U,1);
IplImage *img_gray2 = cvCreateImage(cvGetSize(img2),IPL_DEPTH_8U,1);
cvNamedWindow("img1",CV_WINDOW_AUTOSIZE);
cvShowImage("img1",img1);
cvNamedWindow("img2",CV_WINDOW_AUTOSIZE);
cvShowImage("img2",img2);
cvCvtColor(img1,img_gray1,CV_BGR2GRAY);
cvNamedWindow("img_gray1",CV_WINDOW_AUTOSIZE);
cvShowImage("img_gray1",img_gray1);
cvCvtColor(img2,img_gray2,CV_BGR2GRAY);
cvNamedWindow("img_gray2",CV_WINDOW_AUTOSIZE);
cvShowImage("img_gray2",img_gray2);
int hist_size=256;//直方图的横轴长度
int hist_height=256;//直方图的纵轴高度
float range[]={0,255}; //灰度级的范围
float* ranges[]={range};
CvHistogram *Histogram1 = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
CvHistogram *Histogram2 = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1);
cvCalcHist(&img_gray1,Histogram1,0,0);//计算直方图
cvNormalizeHist(Histogram1,1.0);//归一化直方图
cvCalcHist(&img_gray2,Histogram2,0,0);//计算直方图
cvNormalizeHist(Histogram2,1.0);//归一化直方图
printf("CV_COMP_CORREL : %.4f\n",cvCompareHist(Histogram1,Histogram2,CV_COMP_CORREL));
printf("CV_COMP_CHISQR : %.4f\n",cvCompareHist(Histogram1,Histogram2,CV_COMP_CHISQR));
printf("CV_COMP_INTERSECT : %.4f\n",cvCompareHist(Histogram1,Histogram2,CV_COMP_INTERSECT));
printf("CV_COMP_BHATTACHARYYA : %.4f\n",cvCompareHist(Histogram1,Histogram2,CV_COMP_BHATTACHARYYA));
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&img1);
cvReleaseImage(&img2);
return 0;
}
运行结果: