Histogram Equalization in OpenCV
What is an Image Histogram
- It is a graphical representation of the intensity distribution of an image.
- It quantifies the number of pixels for each intensity value considered.
What is Histogram Equalization
It is a method that improves the contrast in an image, in order to stretch out the intensity range.
How does it work
- 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). For the histogram
, its cumulative distribution
is:
To use this as a remapping function, we have to normalizesuch that the maximum value is 255 ( or the maximum value for the intensity of the image ).
- Finally, we use a simple remapping procedure to obtain the intensity values of the equalized image:
Example
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> using namespace cv; using namespace std; /** @function main */ int main( int argc, char** argv ) { Mat src, dst; IplImage* newImg; /* load an image named "desert.jpg", 1 means this is a color image */ newImg = cvLoadImage("Desert.jpg",1); char* source_window = "Source image"; char* equalized_window = "Equalized Image"; /// Load image src = cvarrToMat(newImg); /// Convert to grayscale cvtColor( src, src, CV_BGR2GRAY ); /// Apply Histogram Equalization equalizeHist( src, dst ); /// Display results namedWindow( source_window, CV_WINDOW_AUTOSIZE ); namedWindow( equalized_window, CV_WINDOW_AUTOSIZE ); imshow( source_window, src ); imshow( equalized_window, dst ); /// Wait until user exits the program waitKey(0); return 0; }