Question

My question is when we normalize the histogram , is there any build-in function for that , if not than obviously we can calculate the histogram of the image using the function calcHist() , but the formula of normalizing histogram is Nk/N so what calcHist return us is N in this formula , or we have to calculate N on our own , and whats its role in entropy formula

Was it helpful?

Solution

I am not sure I get your question. But here is a simple example of how to get the l1 normalised histogram of a grayscale image with OpenCV.

In case of an image N is the number of pixels which can be computed simply by multiplying the width and the height of the image. Then it is simply a matter of dividing the histogram by N.

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, char** argv)
{
    Mat img = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE);
    Mat hist;

    int channels[] = {0};
    int histSize[] = {32};
    float range[] = { 0, 256 };
    const float* ranges[] = { range };

    calcHist( &img, 1, channels, Mat(), // do not use mask
         hist, 1, histSize, ranges,
         true, // the histogram is uniform
         false );

   Mat histNorm = hist / (img.rows * img.cols);

   return 0;
}

To get the example I modified the one from the OpenCV documentation.

If you want to compute the entropy with this histogram, you can do this:

double entropy = 0.0;
for (int i=0; i<histNorm.rows; i++)
{
    float binEntry = histNorm.at<float>(i,0);
    if (binEntry != 0.0)
        entropy -= binEntry * log2(binEntry);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top