The code to calculate the entropy of a greyscale image:
#include <opencv2/opencv.hpp>
using namespace cv;
#pragma comment(lib, "opencv_world331.lib")
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main(void)
{
Mat frame = imread("puppets.png", CV_LOAD_IMAGE_GRAYSCALE);
if (frame.empty())
{
cout << "Error loading image file" << endl;
return -1;
}
map<unsigned char, size_t> pixel_map;
for (int j = 0; j < frame.rows; j++)
for (int i = 0; i < frame.cols; i++)
pixel_map[frame.at<unsigned char>(j, i)]++;
//cout << frame.rows*frame.cols << " " << pixel_map.size() << endl;
double entropy = 0;
for (map<unsigned char, size_t>::const_iterator ci = pixel_map.begin(); ci != pixel_map.end(); ci++)
{
double probability = ci->second / static_cast<double>(frame.rows*frame.cols);
entropy += probability * log(probability);
}
entropy = -entropy;
cout << entropy << endl;
return 0;
}