影象資訊熵計算的OpenCV程式碼
阿新 • • 發佈:2018-11-08
// 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));
}
return result;
}