#include "stdafx.h"
#include
#include
#include
using namespace cv;
// 计算图像直方图
void CompImageHist(Mat &src, MatND &b_hist, MatND &g_hist, MatND &r_hist)
{
// 分割成3个单通道图像(bgr)
vector rgb_planes;
split(src, rgb_planes);
// 设定bin数目及取值范围
int histSize = 255;
float range[] = { 0, 255 };
const float* histRange = { range };
// 计算直方图
bool uniform = true;
bool accumulate = false;
calcHist(&rgb_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate);
calcHist(&rgb_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate);
calcHist(&rgb_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate);
// 直方图归一化>>范围为[0, 1]
normalize(r_hist, r_hist, 0, 1, NORM_MINMAX, -1/*, Mat()*/);
normalize(g_hist, g_hist, 0, 1, NORM_MINMAX, -1/*, Mat()*/);
normalize(b_hist, b_hist, 0, 1, NORM_MINMAX, -1/*, Mat()*/);
}
int main(int argc, _TCHAR* argv[])
{
Mat img0 = imread("image\\lena0.jpg");
imshow("img0", img0);
Mat img1 = imread("image\\lena1.jpg");
imshow("img1", img1);
MatND hist0[3], hist1[3];
// 计算图像直方图
CompImageHist(img0, hist0[0], hist0[1], hist0[2]);
CompImageHist(img1, hist1[0], hist1[1], hist1[2]);
double sum[4] = { 0.0 };
double results[4] = { 0.0 };
char channelName[][8] = { { "蓝色" }, { "绿色" }, { "红色" } };
// 比较直方图
printf("各通道比较结果... \n\n");
for (int i = 0; i < 3; i++)
{
// 相关: CV_COMP_CORREL,卡方: CV_COMP_CHISQR,相交: CV_COMP_INTERSECT,巴氏: CV_COMP_BHATTACHARYYA
results[0] = compareHist(hist0[i], hist1[i], CV_COMP_CORREL);
results[1] = compareHist(hist0[i], hist1[i], CV_COMP_CHISQR);
results[2] = compareHist(hist0[i], hist1[i], CV_COMP_INTERSECT);
results[3] = compareHist(hist0[i], hist1[i], CV_COMP_BHATTACHARYYA);
sum[0] += results[0];
sum[1] += results[1];
sum[2] += results[2];
sum[3] += results[3];
printf("%s-->相关: %f, 卡方: %f, 相交: %f, 巴氏: %f \n", channelName[i], results[0], results[1], results[2], results[3]);
}
printf("\n均值-->相关: %f, 卡方: %f, 相交: %f, 巴氏: %f \n", sum[0]/3, sum[1]/3, sum[2]/3, sum[3]/3);
waitKey();
return 0;
}
运行结果: