I need code to find entropy of an image.
for(int i=0;i<grey_image.rows;i++)
{
for(int j=1;j<grey_image.cols;j++)
{
//cout<<i<<" "<<j<<" "<<(int)grey_image.at<uchar>(i,j)<<endl;
int a=(int)grey_image.at<uchar>(i,j);
int b=(int)grey_image.at<uchar>(i,j-1);
int x=a-b;
if(x<0)
x=0-x;
probability_array[x]++;
//grey_image.at<uchar>(i,j) = 255;
}
}
//calculating probability
int n=rows*cols;
for(int i=0;i<256;i++)
{
probability_array[i]/=n;
//cout<<probability_array[i]<<endl;
}
// galeleo team formula
float entropy=0;
for(int i=0;i<256;i++)
{
if (probability_array[i]>0)
{
float x=probability_array[i]*log(probability_array[i]);
entropy+=x;
}
}
return 0-entropy;
Actually I am using this to dump in a programmable camera to measure entropy. Now I want to use it in windows system. I am getting entropy of a gray image as zero.Please help me out. Where did I go wrong.
Without knowing what image are you using, we cannot know if a zero entropy result is not the right answer (as suggested by @Xocoatzin). Besides, your code can benefit from some of the latest OpenCV features 😊: Here is a working implementation using OpenCV histograms and matrix expressions:
if (frame.channels()==3) cvtColor(frame,frame,CV_BGR2GRAY);
/// Establish the number of bins
int histSize = 256;
/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ;
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
/// Compute the histograms:
calcHist( &frame, 1, 0, Mat(), hist, 1, &histSize, &histRange, uniform, accumulate );
hist /= frame.total();
hist += 1e-4; //prevent 0
Mat logP;
cv::log(hist,logP);
float entropy = -1*sum(hist.mul(logP)).val[0];
cout << entropy << endl;