编程实现RGB文件三通道分量的熵计算。
该测试文件分辨率为256256,数据格式为每个像素占用3字节,BGRBGR…保存。拿到文件可以先计算一下文件大小是否为宽高*3字节。
计算公式:
二、代码实现先从test.rgb中读取rgb分量,再计算各分量出现的次数,由此计算概率密度,按照熵的计算公式计算出各分量的熵值。
采用C++语言。
注意:提取rgb分量时要按照BGR的顺序提取。
#pragma warning(disable:4996); //防止编译时不允许使用fopen函数
#include
#include
#include
using namespace std;
int main()
{
FILE* fp = fopen("C:\\Users\\26617\\Desktop\\数据压缩exe1\\exe1\\test.rgb", "rb"); //打开该文件
double h = 256; //高为256
double w = 256; //宽为256
unsigned char* r = (unsigned char*)malloc(256 * 256 * sizeof(unsigned char)); //分配r、g、b分量和buffer的空间
unsigned char* g = (unsigned char*)malloc(256 * 256 * sizeof(unsigned char));
unsigned char* b = (unsigned char*)malloc(256 * 256 * sizeof(unsigned char));
unsigned char* buffer = (unsigned char*)malloc(256 * 256 * 3*sizeof(unsigned char));
fread(buffer, sizeof(unsigned char), 256 * 256 * 3, fp); //将文件数据读入
double pr[256] = { 0 }; //存放rgb概率
double pg[256] = { 0 };
double pb[256] = { 0 };
double rnum[256] = { 0 }; //存放rgb数量
double gnum[256] = { 0 };
double bnum[256] = { 0 };
double sr = 0; //存放rgb熵值
double sg = 0;
double sb = 0;
int i, j;
//分别提取rgb分量
for (i = 0, j = 0; i < 256 * 256 * 3; i = i + 3, j++)
{
b[j] = buffer[i];
g[j] = buffer[i + 1];
r[j] = buffer[i + 2];
}
//计算rgb分量各数值出现的次数
for (i = 0; i < 256; i++)
{
for (j = 0; j < 256 * 256; j++)
{
if (r[j] == i)
{
rnum[i]++;
}
if (g[j] == i)
{
gnum[i]++;
}
if (b[j] == i)
{
bnum[i]++;
}
}
}
//计算rgb分量概率密度
for (i = 0; i < 256; i++)
{
pr[i] = rnum[i] / double(h * w);
pg[i] = gnum[i] / double(h * w);
pb[i] = bnum[i] / double(h * w);
}
//计算rgb熵值
for (i = 0; i < 256; i++)
{
if (pr[i] != 0)
{
sr += (-1) * pr[i] * (log(pr[i]) / log(2.0));
}
if (pg[i] != 0)
{
sg += (-1) * pg[i] * (log(pg[i]) / log(2.0));
}
if (pb[i] != 0)
{
sb += (-1) * pb[i] * (log(pb[i]) / log(2.0));
}
}
cout << "r的熵值为" << sr << endl;
cout << "g的熵值为" << sg << endl;
cout << "b的熵值为" << sb << endl;
return 0;
}
三、实验结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)