1.目的
(1)如何使用OpenCV函数 compareHist 产生一个表达两个直方图的相似度的数值。
(2)如何使用不同的对比标准来对直方图进行比较。
2.原理
[1]直方图衡量标准
a.Correlation ( CV_COMP_CORREL )
b.Chi-Square(CV_COMP_CHISQR)
c.Intersection(CV_COMP_INTERSECT)
d.Bhattacharyya距离(CV_COMP_BHATTACHARYYA)
3.部分代码解释
/*
compareHist参数解释
test_hist:输入直方图1
test1_hist:输入直方图2
compareMethod:比较方法
*/
double test_test1 = compareHist(test_hist, test1_hist, compareMethod);
double test_test2 = compareHist(test_hist, test2_hist, compareMethod);
double test1_test2 = compareHist(test1_hist, test2_hist, compareMethod);
4.完整代码
(1)CommonInclude.h
#ifndef COMMON_INCLUDE
#define COMMON_INCLUDE
#include<iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
#endif
(2)CompareHist.cpp
#include"CommonInclude.h"
int main(int argc, char** argv){
if(argc<4){
cout << "more parameters are required!!!" << endl;
return(-1);
}
Mat test;
Mat test1;
Mat test2;
test = imread(argv[1]);
test1 = imread(argv[2]);
test2 = imread(argv[3]);
if(!test.data || !test1.data || !test2.data){
cout << "error to read images!!!" << endl;
return(-1);
}
cvtColor(test, test, CV_BGR2HSV);
cvtColor(test1, test1, CV_BGR2HSV);
cvtColor(test2, test2, CV_BGR2HSV);
MatND test_hist;
MatND test1_hist;
MatND test2_hist;
int channels[] = {0,1};
int h_bins = 50;
int s_bins = 32;
int histSize[] = {h_bins, s_bins};
float h_range[] = {0,256};
float s_range[] = {0,180};
const float* histRange[] = {h_range, s_range};
calcHist(&test, 1, channels, Mat(), test_hist, 2, histSize, histRange, true, false);
normalize(test_hist, test_hist, 0, 1, NORM_MINMAX, -1, Mat());
calcHist(&test1, 1, channels, Mat(), test1_hist, 2, histSize, histRange, true, false);
normalize(test1_hist, test1_hist, 0, 1, NORM_MINMAX, -1, Mat());
calcHist(&test2, 1, channels, Mat(), test2_hist, 2, histSize, histRange, true, false);
normalize(test2_hist, test2_hist, 0, 1, NORM_MINMAX, -1, Mat());
for(int i=0; i<4; i++){
int compareMethod = i;
/*
compareHist参数解释
test_hist:输入直方图1
test1_hist:输入直方图2
compareMethod:比较方法
*/
double test_test1 = compareHist(test_hist, test1_hist, compareMethod);
double test_test2 = compareHist(test_hist, test2_hist, compareMethod);
double test1_test2 = compareHist(test1_hist, test2_hist, compareMethod);
cout << "method " << i << ":" << test_test1 << " " << test_test2 << " " << test1_test2 << endl;
}
return(0);
}