Histogram equalization not working on color image - OpenCV

user349026 picture user349026 · Feb 21, 2013 · Viewed 37.2k times · Source

I am trying to perform a histogram equalization using OpenCV using the following function

Mat Histogram::Equalization(const Mat& inputImage)
{
    if(inputImage.channels() >= 3)
    {
        vector<Mat> channels;
        split(inputImage,channels);
        Mat B,G,R;

        equalizeHist( channels[0], B );
        equalizeHist( channels[1], G );
        equalizeHist( channels[2], R );
        vector<Mat> combined;
        combined.push_back(B);
        combined.push_back(G);
        combined.push_back(R);
        Mat result;
        merge(combined,result);
        return result;
    }
    return Mat();
}

But when I get the result, there seems to be no difference in input and output image, what am I doing wrong?

Sorry for the bad image quality, "Preprocessed" (left) is histogram equalized, you can see its same as the input (right).

enter image description here

What did miss?

Answer

sgarizvi picture sgarizvi · Feb 21, 2013

Histogram equalization is a non-linear process. Channel splitting and equalizing each channel separately is not the proper way for equalization of contrast. Equalization involves Intensity values of the image not the color components. So for a simple RGB color image, HE should not be applied individually on each channel. Rather, it should be applied such that intensity values are equalized without disturbing the color balance of the image. So, the first step is to convert the color space of the image from RGB into one of the color spaces which separate intensity values from color components. Some of these are:

Convert the image from RGB to one of the above mentioned color spaces. YCbCr is preferred as it is designed for digital images. Perform HE of the intensity plane Y. Convert the image back to RGB.

In your current situation, you are not observing any significant change, because there are only 2 prominent colors in the image. When there are lots of colors in the image, the splitting method will cause color imbalance.

As an example, consider the following images:

Input Image

Input Image

Intensity Image Equalization

Intensity Equalized

Individual Channel Equalization

(Notice the false colors)

Split Equalized

Here is the OpenCV code for histogram equalization of color image using YCbCr color space.

Mat equalizeIntensity(const Mat& inputImage)
{
    if(inputImage.channels() >= 3)
    {
        Mat ycrcb;

        cvtColor(inputImage,ycrcb,CV_BGR2YCrCb);

        vector<Mat> channels;
        split(ycrcb,channels);

        equalizeHist(channels[0], channels[0]);

        Mat result;
        merge(channels,ycrcb);

        cvtColor(ycrcb,result,CV_YCrCb2BGR);

        return result;
    }
    return Mat();
}