Histogram equalization

Once the image histogram is calculated, it can be modelled so that the image is modified and the histogram has a different shape. This is useful to change the low-contrast levels of images with narrow histograms, since this will spread out the gray levels and thus enhance the contrast. Histogram modeling, also known as histogram transfer, is a powerful technique for image enhancement. In histogram equalization, the goal is to obtain a uniform histogram for the output image. That is, a flat histogram where each pixel value has the same probability. In OpenCV, histogram equalization is performed with the function void equalizeHist(InputArray src, OutputArray dst). The first parameter is the input image and the second one is the output image with the histogram equalized.

The following EqualizeHist_Demo example shows how to calculate and display the histogram equalized and the effect on the two-dimensional image:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>

using namespace cv;
using namespace std;

int main( int, char *argv[] )
{
  Mat src, image, hist;
  int histSize = 255;
  long int dim;

  //Read original image
  src = imread( "fruits.jpg");

  //Convert to grayscale
  cvtColor( src, src, COLOR_BGR2GRAY );

  //Apply Histogram Equalization
  equalizeHist( src, image );

  //Display results
  namedWindow("Source image", 0 );
  namedWindow("Equalized Image", 0 );

  imshow( "Source image", src );
  imshow( "Equalized Image", image );

  //Calculate Histogram of the Equalized Image and display
  calcHist(&image, 1, 0, Mat(), hist, 1, &histSize, 0);
  dim=image.rows *image.cols;
  Mat histImage = Mat::ones(255, 255, CV_8U)*255;
  normalize(hist, hist, 0, histImage.rows, CV_MINMAX, CV_32F);
  histImage = Scalar::all(255);
  int binW = cvRound((double)histImage.cols/histSize);

  for( int i = 0; i < histSize; i++ )
  rectangle( histImage, Point(i*binW, histImage.rows), Point((i+1)*binW, histImage.rows – cvRound(hist.at<float>(i))), Scalar::all(0), -1, 8, 0 );

  namedWindow("Histogram Equalized Image", WINDOW_AUTOSIZE);
  imshow("Histogram Equalized Image", histImage);
 
  waitKey();// Exits the program
  return 0;
}

The code explanation is given as follows. The example first reads the original image and converts it to grayscale. Then, histogram equalization is performed using the equalizeHist function. Finally, the histogram of the equalized image is shown together with the two previous images. The following screenshot shows the output of the example, where three windows are created with the grayscale image, the equalized image, and its histogram:

Histogram equalization

Output of the histogram equalization example

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset