Search code examples
c++opencvhistogram

I get an Assertion Failiure ((elemSize() == sizeof(_Tp)) in C++ OpenCV when trying to access values of a histogram


When I am trying to access the bin values of a generated histogram of a greyscale image, I get this assertion failiure:

Error: Assertion failed (elemSize() == sizeof(_Tp)) in cv::Mat::at ... opencv2\core\mat.inl.hpp, line 943

This is the Code Fragment that throws the failiure:

  for (int i = 0; i < 256; i++) {
        
        hist.at<float>(i) = (hist.at<float>(i) / pixelAmount) * 255;
        
    }

My main problem is that i dont really understand the problem associated with the assertion failiure

I looked up the OpenCV documentation for Histogram Calculation and they are accessing the histogram values the same way.

Thanks in advance for any advice


Solution

  • I'll assume that you got your hist Mat from another API call, so its type can't be affected at creation time.

    The at<T>() method requires you to know the element type of the Mat (say, CV_8U), and to use that same type (uint8_t) in the access.

    There are two ways to solve this situation:

    1. get the scalar value (uint8_t), convert the scalar value so it suits your calculation, write back (uint8_t) a coerced value

    2. convert the entire Mat to CV_32F, which is equivalent to float, and then do your operations

    First option:

    for (int i = 0; i < 256; i++) {
        hist.at<uint8_t>(i) =
            (static_cast<float>(hist.at<uint8_t>(i)) / pixelAmount) * 255;
    }
    

    Second option:

    hist.convertTo(hist, CV_32F);
    // now do your calculations with at<float>()