直方图的比较
1、直方图的比较
- 1.1直方图的比较
a.相关性
b.卡方计算
c.十字计算
d.巴氏距离计算
- 1.2 步骤
api:
2、代码实现
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
string Tostring(double d);
int main(int argc, char** argv)
{
Mat img1 = imread("G:/testpic/img.png");
Mat img2 = imread("G:/testpic/img2.png");
if (!img1.data || !img2.data)
{
printf("cannot load the image");
return -1;
}
namedWindow("input1", WINDOW_AUTOSIZE);
namedWindow("input2", WINDOW_AUTOSIZE);
imshow("input1", img1);
imshow("input2", img2);
//转化为HSV
cvtColor(img1, img1, COLOR_BGR2HSV);
cvtColor(img2, img2, COLOR_BGR2HSV);
//计算直方图
int channels = {0,1};
Mat hist1, hist2;
int h_bin = 40, s_bin = 50;
float histsize[] = {b_bin, s_bin};
int h_range[] = {0,180};
int s_range[] = {0, 256};
const float* histrange[] = {h_range, s_range}
calcHist(&img1, 1, channels, Mat(), hist1, 2, histsize, histrange, true, false);
normalize(hist1, hist1, 0, 1, NORM_MINMAX, -1, Mat());
calcHist(&img2, 1, channels, Mat(), hist2, 2, histsize, histrange, true, false);
normalize(hist2, hist2, 0, 1, NORM_MINMAX, -1, Mat());
//直方图比较
//相关性比较,值越大,相关性越高
double src11 = compareHist(hist1, hist1, HISTCMP_CORREL);
cout << "src11 value:" << src11 << endl;
double src12 = compareHist(hist1, hist2, HISTCMP_CORREL);
cout << "src12 value:" << src12 << endl;
//在图中显示相关性
putText(img1, Tostring(src11), Point(50, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);
putText(img2, Tostring(src12), Point(50, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);
imshow("output1", img1);
imshow("output2", img2);
waitKey(0);
return 0;
}
string Tostring(double d)
{
ostringstream os;
if (os << d)
{
return os.str();
}
return "invalid conversion";
}
img1:
img2:
src12:
src11: