opencv学习笔记(六)直方图比较图片相似度

opencv学习笔记(六)直方图比较图片相似度

  opencv提供了API来比较图片的相似程度,使我们很简单的就能对2个图片进行比较,这就是直方图的比较,直方图英文是histogram, 原理就是就是将图片转换成直方图,然后对直方图进行比较,在某些程度,真实地反映了图片的相似度。

代码如下:

 1 #include 
 2 #include 
 3 #include 
 4 using namespace std;
 5 using namespace cv;
 6 
 7 int main(void)
 8 {
 9     Mat pic1 = imread("pic1.jpg");
10     Mat pic2 = imread("pic2.jpg");
11     //计算相似度
12     if (pic2.channels() == 1) {//单通道时,
13     int histSize = 256;
14     float range[] = { 0, 256 };
15     const float* histRange = { range };
16     bool uniform = true;
17     bool accumulate = false;
18             
19     cv::Mat hist1, hist2;
20             
21     cv::calcHist(&pic2, 1, 0, cv::Mat(), hist1, 1, &histSize, &histRange, uniform, accumulate);
22     cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
23             
24     cv::calcHist(&pic1, 1, 0, cv::Mat(), hist2, 1, &histSize, &histRange, uniform, accumulate);
25     cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
26             
27     double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL);//,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA    CV_COMP_CORREL
28             
29     cout << "similarity = " << dSimilarity << endl;
30     }
31     else {//三通道时
32         cv::cvtColor(pic2, pic2, cv::COLOR_BGR2HSV);
33         cv::cvtColor(pic1, pic1, cv::COLOR_BGR2HSV);
34             
35     int h_bins = 50, s_bins = 60;
36     int histSize[] = { h_bins, s_bins };
37     float h_ranges[] = { 0, 180 };
38     float s_ranges[] = { 0, 256 };
39     const float* ranges[] = { h_ranges, s_ranges };
40     int channels[] = { 0, 1 };
41             
42     cv::MatND hist1, hist2;
43             
44     cv::calcHist(&pic2, 1, channels, cv::Mat(), hist1, 2, histSize, ranges, true, false);
45     cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
46             
47     cv::calcHist(&pic1, 1, channels, cv::Mat(), hist2, 2, histSize, ranges, true, false);
48     cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
49             
50     double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL); //,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA  CV_COMP_CORREL
51             
52     cout << "similarity = " << dSimilarity << endl;
53     }
54     waitKey(0);
55     return 1;    
56 
57 }

  pic1:

  opencv学习笔记(六)直方图比较图片相似度_第1张图片

 

  pic2:

  opencv学习笔记(六)直方图比较图片相似度_第2张图片

 

  使用相关系数法(CV_COMP_CORREL)进行图片相似度比较时,取值范围为[-1,1];越接近1说明两幅图片越相似;

  比较pic1与pic2得到的结果为:

  similarity =0.926247

  pic与本身进行比较时,

  similarity =1

转载于:https://www.cnblogs.com/codingmengmeng/p/5609036.html

你可能感兴趣的:(视觉,OpenCv)