4
votes

I'm trying to calculate the histogram of a matrix composed by only one row. I wrote this code in VS2015 using OpenCV3.1:

//Create matrix stromal pop
cv::Mat stromalHistogram(1, i_stromalIID.size(), CV_32F);
float * ref_ptr = stromalHistogram.ptr<float>(0);
std::copy(i_stromalIID.begin(),
          i_stromalIID.end(),
          stdext::checked_array_iterator<float *>(ref_ptr, stromalHistogram.cols));

#ifdef _DEBUG
std::cout << "Matrix =" << std::endl << stromalHistogram << std::endl;
#endif

// calculate histogram for stromal pop
auto  itRangesRef     = std::minmax_element(i_stromalIID.begin(), i_stromalIID.end());
float stromalRanges[] = {*itRangesRef.first, *itRangesRef.second};
const float *      rangesRef[] = {stromalRanges};
const int          channel     = 0;
const int          histSize    = 256;
std::vector<float> hist_out;
cv::calcHist(
  &stromalHistogram, 1, &channel, cv::Mat(), hist_out, 1, &histSize, rangesRef);

i_stromalIID is a std::vector<double> passed from the extern. The cv::Mat stromalHistogram is filled correctly because when I print it, everything is as I expected (1 row, 1203 columns). But when the program runs the cv::calcHist, I receive the following error:

OpenCV Error: Assertion failed (d == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0)) in cv::_OutputArray::create, file D:\Development\lib\OpenCV3.1\opencv-master\modules\core\src\matrix.cpp, line 2363

I tried to debug the OpenCV code, and the error is in cv::calcHist when it tries to do:

void cv::calcHist( const Mat* images, int nimages, const int* channels,
                   InputArray _mask, OutputArray _hist, int dims, const int* histSize,
                   const float** ranges, bool uniform, bool accumulate )
{
      .....
      .....

      _hist.create(dims, histSize, CV_32F);
}

Then inside matrix.cpp is called:

void _OutputArray::create(int d, const int* sizes, int mtype, int i,
                          bool allowTransposed, int fixedDepthMask) const
{
      .....
      .....

      if( k == STD_VECTOR || k == STD_VECTOR_VECTOR )
      {
        CV_Assert( d == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0) );
        .....
        .....
      }
}

And this assert fails because d in my case is equal to 1.

What am I doing wrong?

2
try cv::Mat hist_out; instead of std::vector<float> hist_out; - sturkmen
It works! Thanks! But I don't understand why it doesn't like if I try to use a std::vector. - BugsFree

2 Answers

0
votes

Change the Mat size to the source image.

0
votes

You are passing dims as 1 and the assert that it is 2 is failing.