运行时错误使用calcHist在OpenCV (c++)

Runtime error using calcHist in OpenCV (C++)

本文关键字:c++ OpenCV calcHist 运行时错误      更新时间:2023-10-16

这里有许多关于OpenCV中的calcHist的问题,但我找不到我的问题的答案,并且已经多次阅读文档,所以这里希望有人可以发现我的问题与以下代码:

//the setup is that I've got a 1x993 cv::Mat called bestLabels that contains cluster 
//labels for 993 features each belonging to 1 of 40 different clusters. I'm just trying 
//to histogram these into hist. 
cv::Mat hist;
int nbins = 40; 
int hsize[] = { nbins }; 
float range[] = { 0, 39 };
const float *ranges[] = { range };
int chnls[] = { 0 };   
cv::calcHist(&bestLabels, 1, chnls, cv::Mat(), hist, 1, hsize, ranges);

这可以编译,但是当我运行它时,我得到一个错误:

OpenCV Error: Unsupported format or combination of formats () in cv::calcHist

一开始很难让它编译,但现在我真的不确定我错过了什么。请帮助!

或者,我尝试遍历bestLabels的元素,并在存储我的直方图的数组中增加值,但是使用bestLabels.at(0, I)也不起作用。必须有一种更简单的方法来从cv::Mat对象中提取单个元素。

谢谢你的帮助

bestLabels的类型是什么?

我可以用CV_32S重现您的错误,但它与CV_8U或CV_32F一起工作很好。

也许最简单的方法是将其转换为uchar:
bestLabels.convertTo( bestLabels, CV_8U ); // CV_32F for float, might be overkill here

此外,"手动"直方图计算并不那么困难:

Mat bestLabels(1,933,CV_32S); // assuming 'int' here again
Mat hist(1,40,CV_8U,Scalar(0));
for ( int i=0; i<bestLabels.cols; i++ ) 
    hist[ bestLabels.at<int>(0,i) ] ++;