比较两个图像是否相似,这个应用范围十分广泛,我刚开始总以为这个技术十分高深(当然也是百分高深),要入门得学很多的相关知识,起码得方方面面都有一定的了解了才能来做这方面的研究。
但是opencv提供了一套API来做这个的比较,使我们很简单的就能对2个图片进行比较,这就是直方图的比较,直方图英文是histogram, 原理就是就是将图片转换成直方图,然后对直方图进行比较,在某些程度,真实地反映了图片的相似度。下面是具体代码:
#include "opencv2/highgui/highgui.hpp" #include "opencv/cv.hpp" //画直方图用 int HistogramBins = 256; float HistogramRange1[2]={0,255}; float *HistogramRange[1]={&HistogramRange1[0]}; /* * imagefile1: * imagefile2: * method: could be CV_COMP_CHISQR, CV_COMP_BHATTACHARYYA, CV_COMP_CORREL, CV_COMP_INTERSECT */ int CompareHist(const char* imagefile1, const char* imagefile2) { IplImage *image1=cvLoadImage(imagefile1, 0); IplImage *image2=cvLoadImage(imagefile2, 0); CvHistogram *Histogram1 = cvCreateHist(1, &HistogramBins, CV_HIST_ARRAY,HistogramRange); CvHistogram *Histogram2 = cvCreateHist(1, &HistogramBins, CV_HIST_ARRAY,HistogramRange); cvCalcHist(&image1, Histogram1); cvCalcHist(&image2, Histogram2); cvNormalizeHist(Histogram1, 1); cvNormalizeHist(Histogram2, 1); // CV_COMP_CHISQR,CV_COMP_BHATTACHARYYA这两种都可以用来做直方图的比较,值越小,说明图形越相似 printf("CV_COMP_CHISQR : %.4f\n", cvCompareHist(Histogram1, Histogram2, CV_COMP_CHISQR)); printf("CV_COMP_BHATTACHARYYA : %.4f\n", cvCompareHist(Histogram1, Histogram2, CV_COMP_BHATTACHARYYA)); // CV_COMP_CORREL, CV_COMP_INTERSECT这两种直方图的比较,值越大,说明图形越相似 printf("CV_COMP_CORREL : %.4f\n", cvCompareHist(Histogram1, Histogram2, CV_COMP_CORREL)); printf("CV_COMP_INTERSECT : %.4f\n", cvCompareHist(Histogram1, Histogram2, CV_COMP_INTERSECT)); cvReleaseImage(&image1); cvReleaseImage(&image2); cvReleaseHist(&Histogram1); cvReleaseHist(&Histogram2); return 0; } int main(int argc, char* argv[]) { CompareHist(argv[1], argv[2]); //CompareHist("d:\\camera.jpg", "d:\\camera1.jpg"); return 0; }
对于这两张图的运行结果是:
CV_COMP_CHISQR : 0.2902
CV_COMP_BHATTACHARYYA : 0.1707
CV_COMP_CORREL : 0.8017
CV_COMP_INTERSECT : 0.8070
如果使用同一张图片来自己比较运行的结果应该是CV_COMP_CHISQR : 0.0000
CV_COMP_BHATTACHARYYA : 0.0000
CV_COMP_CORREL : 1.0000
CV_COMP_INTERSECT : 1.0000