对输入的两张图像计算得到直方图H1与H2,归一化到相同的尺度空间,然后可以通过计算H1与H2的之间的距离得到两个直方图的相似程度进,而比较图像本身的相似程度。Opencv提供的比较方法有四种:
(1)Correlation 相关性比较(CV_COMP_CORREL)
N为bin的个数。两幅图像越相似则计算出的值接近1。
(2)Chi-Square 卡方比较(CV_COMP_CHISQR)
(3)Intersection 十字交叉性(CV_COMP_INTERSECT)
(4)Bhattacharyya distance 巴氏距离(CV_COMP_BHATTACHARYYA)
(1)步骤
首先把图像从RGB色彩空间转换到HSV色彩空间cvtColor
计算图像的直方图,然后归一化到[0~1]之间calcHist和normalize;
使用上述四种比较方法之一进行比较compareHist
(2)compareHist(InputArray h1, InputArray H2,int method)
h1:第一幅图直方图数据
h2:第二幅图直方图数据
method:上述方法中的1个
#include "stdafx.h"
#include
#include
#include
using namespace std;
using namespace cv;
char inputName[] = "src1";
char outputName[] = "src2";
int main()
{
Mat src1, src2;
src1 = imread("D:/VS project/Image/people.jpg");
src2 = imread("D:/VS project/Image/people1.png");
if (src1.empty() || src2.empty())
{
cout << "找不到图像" << endl;
return -1;
}
namedWindow(inputName, CV_WINDOW_AUTOSIZE);
namedWindow(outputName, CV_WINDOW_AUTOSIZE);
imshow(inputName, src1);
imshow(outputName, src2);
//转到HSV色彩空间
cvtColor(src1, src1, CV_BGR2HSV);
cvtColor(src2, src2, CV_BGR2HSV);
//计算直方图
int h_bins = 50, s_bins = 60;//定义HS2个通道的级数
int histsize[] = { h_bins, s_bins };//直方图级数
const float h_range[] = { 0,180 };//H值域范围
const float s_range[] = { 0,255 };//S值域范围
const float* range[] = { h_range,s_range };
int channels[] = { 0,1 };
MatND src1Hist, src2Hist;//定义多维数组存放直方图结果
calcHist(&src1, 1, channels, Mat(), src1Hist, 2, histsize, range, true, false);
normalize(src1Hist, src1Hist, 0, 1, NORM_MINMAX, -1,Mat());
calcHist(&src2, 1, channels, Mat(), src2Hist, 2, histsize, range, true, false);
normalize(src2Hist, src2Hist, 0, 1, NORM_MINMAX, -1,Mat());
//比较直方图
double src1src1 = compareHist(src1Hist, src1Hist, CV_COMP_BHATTACHARYYA);//巴士距离
double src1src2 = compareHist(src1Hist, src2Hist, CV_COMP_CORREL);//相关性比较
cout << src1src1 << endl << src1src2;
waitKey(0);
return 0;
}