我正在尝试比较存储为数组的两个直方图。我是C++接口(interface)(cv::Mat)的新手,它在OpenCV中计算直方图。

我的代码:

int testArr1[4] = {12, 10, 11, 11};
int testArr2[4] = {12, 0, 11, 0};
cv::Mat M1 = cv::Mat(1,4,CV_8UC1, testArr1);
cv::Mat M2 = cv::Mat(1,4,CV_8UC1, testArr2);

int histSize = 4;
float range[] = {0, 20};
const float* histRange = {range};
bool uniform = true;
bool accumulate = false;
cv::Mat a1_hist, a2_hist;

cv::calcHist(&M1, 1, 0, cv::Mat(), a1_hist, 1, &histSize, &histRange, uniform, accumulate );
cv::calcHist(&M2, 1, 0, cv::Mat(), a2_hist, 1, &histSize, &histRange, uniform, accumulate );

double compar_c = cv::compareHist(a1_hist, a2_hist, CV_COMP_CORREL);
double compar_chi = cv::compareHist(a1_hist, a2_hist, CV_COMP_CHISQR);
double compar_bh = cv::compareHist(a1_hist, a2_hist, CV_COMP_BHATTACHARYYA);
double compar_i = cv::compareHist(a1_hist, a2_hist, CV_COMP_INTERSECT);
cout << "compare(CV_COMP_CORREL): " << compar_c << "\n";
cout << "compare(CV_COMP_CHISQR): " << compar_chi << "\n";
cout << "compare(CV_COMP_BHATTACHARYYA): " << compar_bh << "\n";
cout << "compare(CV_COMP_INTERSECT): " << compar_i << "\n";

结果有点出乎意料:
compare(CV_COMP_CORREL): 1
compare(CV_COMP_CHISQR): 0
compare(CV_COMP_BHATTACHARYYA): 0
compare(CV_COMP_INTERSECT): 4

例如,对于交集,我期望大约为0.5。我究竟做错了什么?我不能在cv::mat中放入数组吗?还是我选择了错误的直方图“设置”?

最佳答案

问题是您的前4行将整数的c数组转换为chars矩阵。构造函数假设使用char数组,因此无法正确读取值。您的矩阵M1和M2没有包含正确的值。

但是,如果更改以下几行,以使数组的类型与矩阵的类型匹配:

char testArr1[4] = {12, 10, 11, 11};
char testArr2[4] = {12, 0, 11, 0};

我从您的程序中获得以下输出:
compare(CV_COMP_CORREL): 0.57735
compare(CV_COMP_CHISQR): 2.66667
compare(CV_COMP_BHATTACHARYYA): 0.541196
compare(CV_COMP_INTERSECT): 2

关于c++ - 在openCV中的结果compareHist,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9687309/

10-16 22:50