我用MATLAB和C++计算同一副图像的信息熵 结果却不一样
MATLAB代码:
I=imread(path);
[C,R]=size(I); %求图像的规格,如果I是一个矩阵,返回行和列
H_img=0;
temp=zeros(1,256);
for c=1:C
for r=1:R
i=I(c,r)+1; %获取图像的灰度级
temp(i)=temp(i)+1; %统计每个灰度级像素的点数
end
end
for k=1:length(temp)
temp(k)=temp(k)/(C*R); %计算每一个灰度级像素点所占的概率
if temp(k)~=0 %去掉概率为0的像素点
H_img=-temp(k)*log2(temp(k))+H_img; %求熵值的公式
end
end
C++代码:
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// calculate entropy of an image
double Entropy(Mat img)
{
// 将输入的矩阵为图像
double temp[256];
for (int i = 0; i<256; i++)
{
temp[i] = 0.0;
}
// 计算每个像素的累积值
for (int m = 0; m<img.rows; m++)
{// 有效访问行列的方式
const uchar* t = img.ptr<uchar>(m);
for (int n = 0; n<img.cols; n++)
{
int i = t[n];
temp[i] = temp[i] + 1;
}
}
// 计算每个像素的概率
for (int i = 0; i<256; i++)
{
temp[i] = temp[i] / (img.rows*img.cols);
}
double result = 0;
// 根据定义计算图像熵
for (int i = 0; i<256; i++)
{
if (temp[i] == 0.0)
result = result;
else
result = result - temp[i] * (log(temp[i]) / log(2.0));
//result = result - temp[i] * (log2(temp[i]));
}
return result;
}
int main(int argc, char ** argv)
{
const char* imagename = "pano_b.jpg";
//从文件中读入图像
Mat img = imread(imagename);
//如果读入图像失败
if (img.empty())
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
double a = Entropy(img);
cout<<a<<endl;
return 0;
}
上面这张图的分辨率是2048*2048,MATLAB中行循环2048次,列循环2048*2次;C++中行和列都循环2048次。这是我能想到的唯一不同了。
希望大家帮我看一下为什么计算结果不一样。谢谢~