本系列代码托管于:https://github.com/chintsan-code/opencv4-tutorials

本篇使用的项目为:compareHist

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, const char** argv) {
	Mat src1 = imread("../sample/m1.png");
	Mat src2 = imread("../sample/m2.png");
	imshow("input1", src1);
	imshow("input2", src2);
	int histSize[] = { 256, 256, 256 };
	int channels[] = { 0, 1, 2 };
	Mat hist1, hist2;
	float c1[] = { 0, 255 };
	float c2[] = { 0, 255 };
	float c3[] = { 0, 255 };
	const float* histRanges[] = { c1, c2, c3 };
	// 计算所有通道的直方图,bin数量为256
	calcHist(&src1, 1, channels, Mat(), hist1, 3, histSize, histRanges, true, false);
	calcHist(&src2, 1, channels, Mat(), hist2, 3, histSize, histRanges, true, false);

	// 归一化
	normalize(hist1, hist1, 0, 1.0, NORM_MINMAX, -1, Mat());
	normalize(hist2, hist2, 0, 1.0, NORM_MINMAX, -1, Mat());

	// 比较巴氏距离
	double h12 = compareHist(hist1, hist2, HISTCMP_BHATTACHARYYA);
	double h11 = compareHist(hist1, hist1, HISTCMP_BHATTACHARYYA);
	printf("h12 : %.2f, h11 : %.2f\n", h12, h11);

	// 相关性比较
	double c12 = compareHist(hist1, hist2, HISTCMP_CORREL);
	double c11 = compareHist(hist1, hist1, HISTCMP_CORREL);
	printf("c12 : %.2f, c11 : %.2f\n", c12, c11);
	waitKey(0);
	destroyAllWindows();
	return 0;
}

compareHist:比较两个直方图

double compareHist( InputArray H1, InputArray H2, int method );
  • H1:直方图1
  • H2:直方图2,与H1具有相同的尺寸
  • method:比较方法
    • HISTCMP_CORREL:相关性。最小值0,最大值1;值越大,越相似
    • HISTCMP_CHISQR:卡方
    • HISTCMP_INTERSECT:十字交叉性
    • HISTCMP_BHATTACHARYYA:巴氏距离。最小值0,最大值1;值越小,越相似
  • @return:返回d(H1, H2)
opencv4入门笔记(13):图像直方图相似比较-萤火