一、实验内容
分析test.rgb文件三个通道的概率分布,并通过编程计算各自的熵。图像文件的分辨率为256*256,存储格式为按每个像素BGR分量依次存放。
二、实验程序
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
//读取文件
FILE* fp = fopen("E:\\大三下\\数据压缩\\test1\\test.rgb", "rb");
FILE* fp1 = fopen("E:\\大三下\\数据压缩\\test1\\r.txt", "w");
FILE* fp2 = fopen("E:\\大三下\\数据压缩\\test1\\g.txt", "w");
FILE* fp3 = fopen("E:\\大三下\\数据压缩\\test1\\b.txt", "w");
//
int height=256;
int width=256;
double height1=256;
double width1=256;
unsigned char* Y_buffer;
Y_buffer = new unsigned char[width*height*3];
fread(Y_buffer, 1, width*height*3, fp);
unsigned char* r;
r = new unsigned char[width*height];
unsigned char* g;
g = new unsigned char[width*height];
unsigned char* b;
b = new unsigned char[width*height];
//概率
double p_r[256]={0};
double p_g[256]={0};
double p_b[256]={0};
//熵
double H_r=0;
double H_g=0;
double H_b=0;
//提取rgb分量
int i=0;
int j=0;
for (i = 0, j = 0; i < width*height*3; i = i + 3, j++)
{
b[j] = Y_buffer[i + 1]; //注意图像存储格式BGRBGRBGR...
g[j] = Y_buffer[i + 1];
r[j] = Y_buffer[i + 2];
}
//计算rgb分量各数值出现次数
for(i=0;i<256;i++) //分量的取值范围0-255
{
for (j = 0; j < width*height; j++)
{
if (r[j] == i)
{
p_r[i]++;
}
if (g[j] == i)
{
p_g[i]++;
}
if (b[j] == i)
{
p_b[i]++;
}
}
}
//计算概率
for (i = 0; i < 256; i++)
{
p_r[i] = p_r[i] /(width1*height1);
p_g[i] = p_g[i] /(width1*height1);
p_b[i] = p_b[i] /(width1*height1);
}
//计算熵
for (i = 0; i < 256; i++)
{
if (p_r[i] != 0)
{
H_r += (-1) * p_r[i] * (log(p_r[i]) / log(2.0));
}
if (p_g[i] != 0)
{
H_g += (-1) * p_g[i] * (log(p_g[i]) / log(2.0));
}
if (p_b[i] != 0)
{
H_b += (-1) * p_b[i] * (log(p_b[i]) / log(2.0));
}
}
//设置txt文件title
fprintf(fp1, "Symbol\tFrequency\n");
fprintf(fp2, "Symbol\tFrequency\n");
fprintf(fp3, "Symbol\tFrequency\n");
//将数据存放进txt文件中
for (i = 0; i < 256; i++)
{
fprintf(fp1, "%-3d\t%-8f\n", i, p_r[i]);
fprintf(fp2, "%-3d\t%-8f\n", i, p_g[i]);
fprintf(fp3, "%-3d\t%-8f\n", i, p_b[i]);
}
cout << "r=" << H_r << endl;
cout << "g=" << H_g << endl;
cout << "b=" << H_b << endl;
return 0;
}
三、实验结果
- 程序运行结果
- 生成的txt文件截图