我正在第04章“OpenCV 2计算机视觉应用程序编程手册”一书中运行示例。calcHist返回的只有2个直方图是黑色的,并且紧跟着源。运行结果如下所示。

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;
}

...

// Computes the 2D ab histogram.
// BGR source image is converted to Lab
cv::MatND getabHistogram(const cv::Mat &image) {

    cv::MatND hist;

    // Convert to Lab color space
    cv::Mat lab;
    cv::cvtColor(image,lab,CV_BGR2Lab);

    // Prepare arguments for a 2D color histogram
    hranges[0]= -128.0;
    hranges[1]= 127.0;
    channels[0]= 1; // the two channels used are ab
    channels[1]= 2;

    // Compute histogram
    cv::calcHist(&lab,
        1,          // histogram of 1 image only
        channels,   // the channel used
        cv::Mat(),  // no mask is used
        hist,       // the resulting histogram
        2,          // it is a 2D histogram
        histSize,   // number of bins
        ranges      // pixel value range
    );

    return hist;
}

错误在哪里?我想不明白。将图像转换为Lab格式时,cvtColor(...)函数是否运行错误?

c++ - 使用cvtColor后,opencv calcHist返回黑色直方图-LMLPHP

最佳答案

该代码有错误。您正在为通道分配随机值。
将范围更改为calchist()中的hranges。
试试这个:

cv::MatND getabHistogram(const cv::Mat &image) {

cv::MatND hist;

// Convert to Lab color space
cv::Mat lab;
cv::cvtColor(image,lab,CV_BGR2Lab);

// Prepare arguments for a 2D color histogram
hranges[0]= -128.0;
hranges[1]= 127.0;
channels[0]= 1; // the two channels used are ab
channels[1]= 2;

// Compute histogram
cv::calcHist(&lab,
    1,          // histogram of 1 image only
    channels,   // the channel used
    cv::Mat(),  // no mask is used
    hist,       // the resulting histogram
    2,          // it is a 2D histogram
    histSize,   // number of bins
    hranges      // pixel value range
);

return hist;

}

关于c++ - 使用cvtColor后,opencv calcHist返回黑色直方图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48576829/

10-10 18:32