opencv学习笔记(六)直方图比较图片相似度
opencv提供了API来比较图片的相似程度,使我们很简单的就能对2个图片进行比较,这就是直方图的比较,直方图英文是histogram, 原理就是就是将图片转换成直方图,然后对直方图进行比较,在某些程度,真实地反映了图片的相似度。
代码如下:
#include <iostream>
#include <cv.h>
#include <highgui.h>
using namespace std;
using namespace cv; int main(void)
{
Mat pic1 = imread("pic1.jpg");
Mat pic2 = imread("pic2.jpg");
//计算相似度
if (pic2.channels() == ) {//单通道时,
int histSize = ;
float range[] = { , };
const float* histRange = { range };
bool uniform = true;
bool accumulate = false; cv::Mat hist1, hist2; cv::calcHist(&pic2, , , cv::Mat(), hist1, , &histSize, &histRange, uniform, accumulate);
cv::normalize(hist1, hist1, , , cv::NORM_MINMAX, -, cv::Mat()); cv::calcHist(&pic1, , , cv::Mat(), hist2, , &histSize, &histRange, uniform, accumulate);
cv::normalize(hist2, hist2, , , cv::NORM_MINMAX, -, cv::Mat()); double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL);//,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA CV_COMP_CORREL cout << "similarity = " << dSimilarity << endl;
}
else {//三通道时
cv::cvtColor(pic2, pic2, cv::COLOR_BGR2HSV);
cv::cvtColor(pic1, pic1, cv::COLOR_BGR2HSV); int h_bins = , s_bins = ;
int histSize[] = { h_bins, s_bins };
float h_ranges[] = { , };
float s_ranges[] = { , };
const float* ranges[] = { h_ranges, s_ranges };
int channels[] = { , }; cv::MatND hist1, hist2; cv::calcHist(&pic2, , channels, cv::Mat(), hist1, , histSize, ranges, true, false);
cv::normalize(hist1, hist1, , , cv::NORM_MINMAX, -, cv::Mat()); cv::calcHist(&pic1, , channels, cv::Mat(), hist2, , histSize, ranges, true, false);
cv::normalize(hist2, hist2, , , cv::NORM_MINMAX, -, cv::Mat()); double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL); //,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA CV_COMP_CORREL cout << "similarity = " << dSimilarity << endl;
}
waitKey();
return ; }
pic1:
pic2:
使用相关系数法(CV_COMP_CORREL)进行图片相似度比较时,取值范围为[-1,1];越接近1说明两幅图片越相似;
比较pic1与pic2得到的结果为:
similarity =0.926247
pic与本身进行比较时,
similarity =1