Ayoung
Ayoung

Reputation: 351

opencv calcHist returns a black histogram after using cvtColor

I'm running an example in book "OpenCV 2 Computer Vision Application Programming Cookbook", chapter 04. Only 2 histograms return by calcHist are black and the source is followed. And also the running result is shown below.

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

Where is the bug? I cannot figure it out. Is the cvtColor(...) function running into error when converting an image into Lab format?

enter image description here

Upvotes: 1

Views: 845

Answers (1)

janu777
janu777

Reputation: 1978

The code has errors. You are assigning random values to channels. change ranges to hranges in calchist(). Try this:

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;

}

Upvotes: 2

Related Questions