#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <stdio.h>
using namespace std;
const int M = 256;
int main ()
{
float P[M]={0}; // P是用来记录每个灰度出现的概率,初始化时为0
unsigned char arr[M][M]; // D 是用来记录每一个象素的内容
float H=0;//保存信息熵的结果
ofstream outFile;
int i;
int j;
//输入文件名字
string FileName;
cout << "Please input filename path:" << endl;
cin >> FileName;
ifstream inFile(FileName.c_str(), ifstream::binary);
if (!inFile)
{
cout<<"Can not open "<<FileName<<endl;
return 1;
}
//输入指定图像的数据
for (i=0 ; i!=M ; ++i)
{
for(j=0 ; j!=M ; ++j)
{
inFile >> arr[i][j];
}
}
inFile.close();
//统计数据
int a;
for(i=0;i!=M;++i)
{
for(j=0;j!=M;++j)
{
if ( static_cast<float>(arr[i][j])==0)
{
a=0;
}
else
{
a= static_cast<float>(arr[i][j]);
}
P[a]=P[a]+1;
}
}
//计算每个灰度出现的概率
for (i=0; i!=M ; ++i)
{
P[i]=P[i]/(M*M);
}
//计算信息熵
for (i=1 ; i<=M-1 ; ++i)
{
if (P[i]==0)
{H=H;}
else
{H=H-P[i]*(log(P[i])/log(2));}
}
//显示信息熵
cout << "图像信息熵H=" << H <<endl;
outFile.open("result.txt");
outFile << "信息熵 H = " << H << endl;
outFile.close();
return 0;
}