In this tutorial you will learn:
Equalization implies mapping one distribution (the given histogram) to another distribution (a wider and more uniform distribution of intensity values) so the intensity values are spreaded over the whole range.
To accomplish the equalization effect, the remapping should be the cumulative distribution function (cdf) (more details, refer to Learning OpenCV). For the histogram , its cumulative distribution is:
To use this as a remapping function, we have to normalize such that the maximum value is 255 ( or the maximum value for the intensity of the image ). From the example above, the cumulative function is:
Finally, we use a simple remapping procedure to obtain the intensity values of the equalized image:
What does this program do?
Downloadable code: Click here
Code at glance:
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
/* @function main */
int main( int argc, char** argv )
{
Mat src, dst;
char* source_window = "Source image";
char* equalized_window = "Equalized Image";
/// Load image
src = imread( argv[1], 1 );
if( !src.data )
{ cout<<"Usage: ./Histogram_Demo <path_to_image>"<<endl;
return -1;}
/// Convert to grayscale
cvtColor( src, src, COLOR_BGR2GRAY );
/// Apply Histogram Equalization
equalizeHist( src, dst );
/// Display results
namedWindow( source_window, WINDOW_AUTOSIZE );
namedWindow( equalized_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
imshow( equalized_window, dst );
/// Wait until user exits the program
waitKey(0);
return 0;
}
Declare the source and destination images as well as the windows names:
Mat src, dst;
char* source_window = "Source image";
char* equalized_window = "Equalized Image";
Load the source image:
src = imread( argv[1], 1 );
if( !src.data )
{ cout<<"Usage: ./Histogram_Demo <path_to_image>"<<endl;
return -1;}
Convert it to grayscale:
cvtColor( src, src, COLOR_BGR2GRAY );
Apply histogram equalization with the function equalizeHist :
equalizeHist( src, dst );
As it can be easily seen, the only arguments are the original image and the output (equalized) image.
Display both images (original and equalized) :
namedWindow( source_window, WINDOW_AUTOSIZE );
namedWindow( equalized_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
imshow( equalized_window, dst );
Wait until user exists the program
waitKey(0);
return 0;
To appreciate better the results of equalization, let’s introduce an image with not much contrast, such as:
which, by the way, has this histogram:
notice that the pixels are clustered around the center of the histogram.
After applying the equalization with our program, we get this result:
this image has certainly more contrast. Check out its new histogram like this:
Notice how the number of pixels is more distributed through the intensity range.
Note
Are you wondering how did we draw the Histogram figures shown above? Check out the following tutorial!