Full width home advertisement

OpenCV

HTML

Post Page Advertisement [Top]

OpenCV has inbuilt function for doing histogram equalization, the function equalizeHist has two arguments source and destination image respectively. Below is an example code which show the use of Histogram Equalization using OpenCV C++. Also the code draws the Histograms of the image before and after equalization.


C++ Code

  Mat calculateHostogram(Mat src){
    //Plost the histogram
    int bins = 256;
    int histSize[] = {bins};
    float range[] = { 0, 256 };
    const float* ranges[] = { range };
    MatND hist;

    //compute the histogram 
    calcHist( &src, 1, 0, Mat(),
             hist, 1, histSize, ranges,
             true, // the histogram is uniform
             false );

    Mat histPlot = Mat::zeros(src.rows, src.cols, CV_8UC1);
    // Mat histPlot = Mat::zeros(500, 600, CV_8UC1); // if you need color plot enable this
    double scale = src.cols/bins;

    cv::normalize(hist, hist, 0, histPlot.rows, cv::NORM_MINMAX);
    for( int i = 0; i < 256; i++ ) {
        float binVal = hist.at(0, i);
        rectangle( histPlot, Point(i*scale, histPlot.rows), Point( i*scale , histPlot.rows-binVal),Scalar(255),CV_FILLED );
        //rectangle( histPlot, Point(s*2, histPlot.rows), Point( s*2 , histPlot.rows-binVal),Scalar(255,0,255),CV_FILLED ); // if you need color plot enable this
     }
    return histPlot;
  }


  int main(){
    Mat src = imread("img/histogram.jpg", IMREAD_COLOR);
    Mat histEqulized;
    Mat gray;

    cvtColor( src, gray, CV_BGR2GRAY );

    // Apply Histogram Equalization
    equalizeHist( gray, histEqulized );

    //Plot the hostogram before and after equalizeHist
    Mat srcHistPlot = calculateHostogram(gray);
    Mat eqlHistPlot = calculateHostogram(histEqulized);

    //Show All the result in single Window, for this copy all Mat to single Mat and display
    int offset = 5;
    Mat outPutWin(src.rows*2+offset*4,src.cols*2+offset*4, CV_8UC1,Scalar(50));
    gray.copyTo(outPutWin(Rect(offset,offset,src.cols,src.rows)));
    histEqulized.copyTo(outPutWin(Rect(src.cols+2*offset,offset,src.cols,src.rows)));
    srcHistPlot.copyTo(outPutWin(Rect(offset,src.rows+offset*2,src.cols,src.rows)));
    eqlHistPlot.copyTo(outPutWin(Rect(src.cols+2*offset,src.rows+offset*2,src.cols,src.rows)));

    namedWindow("outPutWin",1);
    imshow("outPutWin",outPutWin);
    waitKey();
    return 0;
  }

Source Image


Histogram Plot for source image


Result after Histogram Equlized


Histogram Plot after Histogram Equlized



No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib