opencv學習筆記(六)直方圖比較圖片相似度
opencv提供了API來比較圖片的相似程度,使我們很簡單的就能對2個圖片進行比較,這就是直方圖的比較,直方圖英文是histogram, 原理就是就是將圖片轉換成直方圖,然后對直方圖進行比較,在某些程度,真實地反映了圖片的相似度。
代碼如下:
1 #include <iostream> 2 #include <cv.h> 3 #include <highgui.h> 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:
pic2:
使用相關系數法(CV_COMP_CORREL)進行圖片相似度比較時,取值范圍為[-1,1];越接近1說明兩幅圖片越相似;
比較pic1與pic2得到的結果為:
similarity =0.926247
pic與本身進行比較時,
similarity =1