我正在尝试访问RGB图像的3D直方图。但直方图矩阵返回的行数和列数等于-1。 我想迭代直方图并检查3D矩阵中的各个值。但是,当我检查矩阵中的行数和列数时,我得到-1,如下所示。
CODE
int main( int argc, const char** argv ) {
Mat image = imread("fl.png");
int histSize[3] = {8, 8, 8};
float range[2] = {0, 256};
const float * ranges[3] = {range, range, range};
int channels[3] = {0, 1, 2};
Mat hist;
calcHist(&image, 1, channels, Mat(), hist, 3, histSize, ranges);
cout << "Hist.rows = "<< hist.rows << endl;
cout << "Hist.cols = "<< hist.cols << endl;
return 0;
}
输出
Hist.rows = -1
Hist.cols = -1
我犯了什么错误?如何访问各个矩阵值。
答案 0 :(得分:9)
来自Mat的文档:
//! the number of rows and columns or (-1, -1) when the array has more than 2 dimensions
但你有3个维度。
您可以使用hist.at<T>(i,j,k)
访问直方图的各个值。
或者您可以使用文档here中描述的迭代器。
// Build with gcc main.cpp -lopencv_highgui -lopencv_core -lopencv_imgproc
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using std::cout;
using std::endl;
using namespace cv; # Please, don't include whole namespaces!
int main( int argc, const char** argv ) {
Mat image = imread("good.jpg");
int histSize[3] = {8, 8, 8};
float range[2] = {0, 256};
const float * ranges[3] = {range, range, range};
int channels[3] = {0, 1, 2};
Mat hist;
calcHist(&image, 1, channels, Mat(), hist, 3, histSize, ranges);
cout << "Hist.dims = " << hist.dims << endl;
cout << "Value: " << hist.at<double>(0,0, 0) << endl;
cout << "Hist.rows = "<< hist.rows << endl;
cout << "Hist.cols = "<< hist.cols << endl;
return 0;
}
for (MatConstIterator_<double> it = hist.begin<double>(); it != hist.end<double>(); it++) {
cout << "Value: " << *it << "\n";
}
cout << std::flush;
for (int i=0; i<histSize[0]; i++) {
for (int j=0; j<histSize[1]; j++) {
for (int k=0; k<histSize[2]; k++) {
cout << "Value(" << i << ", " << j << ", " << k <<"): " << hist.at<double>(i, j, k) << "\n";
}
}
}
cout << std::flush;