读取直方图后的未处理异常(使用calcHist创建)

Pat*_*ryk 5 c++ opencv histogram unhandled-exception

我想在OpenCV中从我的颜色(3通道)图像中获取直方图,但每次我都像这样做calcHist直方图:

//int histSize[3];
//float hranges[2];
//const float* ranges[3];
//int channels[3];

ColorHistogram::ColorHistogram() 
{
    // Prepare arguments for a color histogram
    histSize[0]= histSize[1]= histSize[2]= 256;
    hranges[0]= 0.0; // BRG range
    hranges[1]= 255.0;
    ranges[0]= hranges; // all channels have the same range
    ranges[1]= hranges;
    ranges[2]= hranges;
    channels[0]= 0; // the three channels
    channels[1]= 1;
    channels[2]= 2;
}

cv::MatND ColorHistogram::getHistogram(const cv::Mat &image)
{
    cv::MatND hist;
    // Compute histogram
    cv::calcHist(&image,
        1, // histogram of 1 image only
        channels, // the channel used
        cv::Mat(), // no mask is used
        hist, // the resulting histogram
        3, // it is a 3D histogram
        histSize, // number of bins
        ranges // pixel value range
        );
    return hist;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当我尝试将结果输入到例如时,cv::minMaxLoc我得到一个未处理的异常.

cv::Mat ColorHistogram::getHistogramImage(const cv::Mat &image){
    // Compute histogram first
    cv::MatND hist = getHistogram(image);
    // Get min and max bin values
    double maxVal=0;
    double minVal=0;
    cv::minMaxLoc(hist, &minVal, &maxVal, 0, 0);
//....
}
Run Code Online (Sandbox Code Playgroud)

编辑

我不知道这是否重要,但我在控制台中收到此错误:

OpenCV错误:未知函数中的断言失败(img.dims <= 2),文件C:\ slave\WinInstallerMegaPack\src\opencv\modules\core\src\stat.cpp,第788行

而我imagedims = 2

mev*_*ron 2

不幸的是,您不能minMaxLoc使用 3D 直方图进行调用(即,这hist.dims == 3是真的)。下面是代码minMaxLoc

void cv::minMaxLoc( InputArray _img, double* minVal, double* maxVal,
                Point* minLoc, Point* maxLoc, InputArray mask )
{
    Mat img = _img.getMat();
    CV_Assert(img.dims <= 2); // <-- This is the line that is asserting for you...

    minMaxIdx(_img, minVal, maxVal, (int*)minLoc, (int*)maxLoc, mask);
    if( minLoc )
        std::swap(minLoc->x, minLoc->y);
    if( maxLoc )
        std::swap(maxLoc->x, maxLoc->y);
}
Run Code Online (Sandbox Code Playgroud)

您必须手动搜索 3D 直方图中的最小值和最大值。您也许可以使用NAryMatIterator来帮助简化搜索。文档中有一个如何使用它的示例。另外,您可以在这里找到我的相关答案。