foreword
The image histogram is explained in detail in , and image histogram comparison is a means of measuring the similarity of two images. To compare two histograms (H1 and H2), first we have to choose a metric (d(H1,H2)) to represent how well the two histograms match. OpenCV provides 4 different metrics to calculate matches:
Correlation (HISTCMP_CORREL):
N is N is the total number of histogram bins.
Chi-Square ( HISTCMP_CHISQR)
Intersection ( method=HISTCMP_INTERSECT)
Bhattacharyya distance ( HISTCMP_BHATTACHARYYA)
opencv function support
Function prototype:
CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
Parameter description:
H1: The first to compare the histogram.
H2: The second wants a histogram, the same size as H1.
method : The method of comparison, see #HistCompMethods, for Correlation and Intersection methods, the higher the metric, the more accurate the match. Square and Bhattacharyya distance are the opposite.
Code example:
cv::Mat image = cv::imread("D:\\QtProject\\Opencv_Example\\Hist\\Hist.png", cv::IMREAD_GRAYSCALE);
if (image.empty()) {
cout << "Cannot load image" << endl;
return;
}
imshow("image",image);
const int bins[1] = {
256 };
float hranges[2] = {
0,255 };
const float* ranges[1] = {
hranges };
Mat hist;
// 计算直方图
calcHist(&image, 1, 0, Mat(), hist, 1, bins, ranges);
normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat()); //将数据规皈依到0和1之间
cv::Mat imageCvert;
image.convertTo(imageCvert, -1, 1, 50);
imshow( "imageCvert", imageCvert);
Mat histCompare;
calcHist(&imageCvert, 1, 0, Mat(), histCompare, 1, bins, ranges);
normalize(histCompare, histCompare, 0, 1, NORM_MINMAX, -1, Mat()); //将数据规皈依到0和1之间
double CORREL = compareHist( hist, histCompare, HISTCMP_CORREL );
double CHISQR = compareHist( hist, histCompare, HISTCMP_CHISQR );
double INTERSECT = compareHist( hist, histCompare, HISTCMP_INTERSECT );
double BHATTACHARYYA = compareHist( hist, histCompare, HISTCMP_BHATTACHARYYA );
cout << "HISTCMP_CORREL:" << CORREL<<endl
<< "HISTCMP_CHISQR:" << CHISQR << endl
<< "HISTCMP_INTERSECT:" << INTERSECT << endl
<< "HISTCMP_BHATTACHARYYA:" << BHATTACHARYYA << endl;
Two images compared:
run results: