Wednesday 13 February 2013

Entropy-based histogram thresholding

I read about entropy thresholding[1] and I wanted to give it a try. This technique was rather simple to implement in Matlab compared to other more complex methods and performed reasonably (see results).

Code

function [A, T] = EntropyThresholding(img)

[h, ~] = imhist(img);
h = h/sum(h); % Normalize the histogram so that it sums to 1.
entropies = zeros(256, 1); % Intialize array for storing entropies.
for t = 1:254
    White = h(1:t);
    Black = h(t+1:255);
    % Add 0.001 to prevent division by zero(nan) and log of zero(-inf).
    HB =  sum((Black/(0.001+sum(Black))).*log((Black+0.001)/(0.001 +sum(Black))));
    HW =  sum((White/(0.001+sum(White))).*log((White+0.001)/(0.001 +sum(White))));
    entropies(t) = HB+HW; 
end
[~, T] = max(abs(entropies)); % The Maximal entropy determines the threshold.
T = T - 1;
A = img > T;

Results

References

1. J.N. Kapur, P.K. Sahoo and A.K.C. Wong, "A New Method for Gray-Level Picture Thresholding Using the Entropy of the Histogram", CVGIP, (29), pp.273-285 , 1985.

Saturday 2 February 2013

Draw an OpenCV histogram using QWT

The QWT Library gives us the ability to create graphs, scale axes, insert legend and do a whole lot of graphing stuff, in a very easy manner. I wanted to show how easy it was to use so in this tutorial I plot an openCV histogram using QWT.
The set-up for this tutorial is similar to the one in my previous tutorial, only this time I also include the OpenCV library. So we can dive straight into the code.

Code

#include <QApplication>
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_grid.h>
#include <qwt_symbol.h>
#include <qwt_legend.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    if (argc < 2)
        return 1;
    
    //Read input image
    cv::Mat img = cv::imread(argv[1]);
    
    //Convert to grayscale
    if (img.data && img.channels() == 3)
        cv::cvtColor(img, img, CV_BGR2GRAY);
    else
        return 1;

    int histSize[1] = {256}; // number of bins
    float hranges[2] = {0.0, 255.0}; // min and max pixel value
    const float* ranges[1] = {hranges};
    int channels[1] = {0}; // only 1 channel used

    cv::MatND hist;
    // Compute histogram
    cv::calcHist(&img, 1, channels, cv::Mat(), hist, 1, histSize,ranges);

    double minVal, maxVal;
    cv::minMaxLoc(hist, &minVal, &maxVal);//Locate max and min values
   
    QwtPlot plot; //Create plot widget
    plot.setTitle( "Plot Demo" ); //Name the plot
    plot.setCanvasBackground( Qt::black ); //Set the Background colour
    plot.setAxisScale( QwtPlot::yLeft, minVal, maxVal ); //Scale the y-axis
    plot.setAxisScale(QwtPlot::xBottom,0,255); //Scale the x-axis
    plot.insertLegend(new QwtLegend()); //Insert a legend

    QwtPlotCurve *curve = new QwtPlotCurve(); // Create a curve
    curve->setTitle("Count"); //Name the curve
    curve->setPen( Qt::white, 2);//Set colour and thickness for drawing the curve 
    //Use Antialiasing to improve plot render quality
    curve->setRenderHint( QwtPlotItem::RenderAntialiased, true );
    /*Insert the points that should be plotted on the graph in a 
    Vector of QPoints or a QPolgonF */
    QPolygonF points;
    for( int h = 0; h < histSize[0]; ++h) {
        float bin_value = hist.at<float>(h);
        points << QPointF((float)h, bin_value);
    }

    curve->setSamples( points ); //pass points to be drawn on the curve
    curve->attach( &plot ); // Attach curve to the plot 
    plot.resize( 600, 400 ); //Resize the plot
    plot.show(); //Show plot

    return a.exec();

}
The code is well commented and is therefore self explanatory - no need for extra explanations. The result can be seen in the image below.