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 {9Mat pic1 = imread("pic1.jpg");10Mat pic2 = imread("pic2.jpg");11//计算相似度12if (pic2.channels() == 1) {//单通道时,13int histSize = 256;14float range[] = { 0, 256 };15const float* histRange = { range };16bool uniform = true;17bool accumulate = false;18 19cv::Mat hist1, hist2;20 21cv::calcHist(&pic2, 1, 0, cv::Mat(), hist1, 1, &histSize, &histRange, uniform, accumulate);22cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());23 24cv::calcHist(&pic1, 1, 0, cv::Mat(), hist2, 1, &histSize, &histRange, uniform, accumulate);25cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());26 27double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL);//,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA CV_COMP_CORREL28 29cout << "similarity = " << dSimilarity << endl;30}31else {//三通道时32 cv::cvtColor(pic2, pic2, cv::COLOR_BGR2HSV);33 cv::cvtColor(pic1, pic1, cv::COLOR_BGR2HSV);34 35int h_bins = 50, s_bins = 60;36int histSize[] = { h_bins, s_bins };37float h_ranges[] = { 0, 180 };38float s_ranges[] = { 0, 256 };39const float* ranges[] = { h_ranges, s_ranges };40int channels[] = { 0, 1 };41 42cv::MatND hist1, hist2;43 44cv::calcHist(&pic2, 1, channels, cv::Mat(), hist1, 2, histSize, ranges, true, false);45cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());46 47cv::calcHist(&pic1, 1, channels, cv::Mat(), hist2, 2, histSize, ranges, true, false);48cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());49 50double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL); //,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA CV_COMP_CORREL51 52cout << "similarity = " << dSimilarity << endl;53}54waitKey(0);55return 1; 56 57 }
pic1:
pic2:
使用相关系数法(CV_COMP_CORREL)进行图片相似度比较时,取值范围为[-1,1];越接近1说明两幅图片越相似;
比较pic1与pic2得到的结果为:
similarity =0.926247
pic与本身进行比较时,
similarity =1
如果觉得《opencv学习笔记(六)直方图比较图片相似度》对你有帮助,请点赞、收藏,并留下你的观点哦!