数据压缩第三次作业
程序员文章站
2022-07-14 21:56:30
...
读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图(类似下图)和熵。
#include<iostream>
#include<cmath>
#include<malloc.h>
using namespace std;
int main()
{
FILE* down;
FILE* B;
FILE* G;
FILE* R;
const int width = 256;
const int height = 256;
const int Square = width * height;
const int TheWholeNum = width * height * 3;
//打开文件,定义新文件
fopen_s(&down, "D:\down.rgb", "rb");
fopen_s(&B, "D:\B.txt", "w");
fopen_s(&G, "D:\G.txt", "w");
fopen_s(&R, "D:\R.txt", "w");
//定义缓存区
unsigned char* buffer = NULL;
buffer = (unsigned char*)malloc(sizeof(unsigned char)*TheWholeNum);
//每个像素中RGB读入缓存区
//fread的用法:fread(存入地点,每次读的字节数,共读字节数,读取文件名)
fread(buffer, 1, TheWholeNum, down);
//把读取的内容分别放入RGB数组中 RGB储存顺序是B、G、R,所以用模函数
//定义RGB数组
unsigned char b[Square] = { 0 };
unsigned char g[Square] = { 0 };
unsigned char r[Square] = { 0 };
int m = 0, n = 0, k = 0 ;
for (int i = 0; i < TheWholeNum; i++)
{
if (i % 3 == 0)
{
b[m] = *(buffer + i);
m++;
}
else if (i % 3 == 1)
{
g[n] = *(buffer + i);
n++;
}
else
{
r[k] = *(buffer + i);
k++;
}
}
//计算出现的概率
int numB[256] = { 0 },numG[256] = { 0 },numR[256] = { 0 };
double freB[256] = { 0 }, freG[256] = { 0 }, freR[256] = { 0 };
for (int i = 0; i < 256; i++)//灰度值共有256种
{
for (int j = 0; j < Square; j++)//存储在b数组中的值共有Square个
{
if (i == b[j])//判断储存在b数组中的灰度值是多少并且把相同的计数
{
numB[i]++;//并且把相同的计数
}
}
freB[i] = (double)numB[i] / (Square);
}
for (int i = 0; i < 256; i++)//灰度值共有256种
{
for (int j = 0; j < Square; j++)//存储在g数组中的值共有Square个
{
if ( i== g[j])//判断储存在g数组中的灰度值是多少并且把相同的计数
{
numG[i]++;//并且把相同的计数
}
}
freG[i] = (double)numG[i] / (Square);
}
for (int i = 0; i < 256; i++)//灰度值共有256种
{
for (int j = 0; j < Square; j++)//存储在r数组中的值共有Square个
{
if ( i== r[j])//判断储存在r数组中的灰度值是多少并且把相同的计数
{
numR[i]++;//并且把相同的计数
}
}
freR[i] = (double)numR[i] / (Square);
}
//计算熵
double HB = 0, HG = 0, HR = 0;
for (int i = 0; i < 256; i++)
{
if(freB[i]!=0)//!重要,如果概率为零无法计算熵
HB +=-freB[i] * log(freB[i]) / log(2);//B每个灰度值的熵的总和
if(freG[i]!=0)
HG +=-freG[i] * log(freG[i]) / log(2);
if(freR[i]!=0)
HR +=-freR[i] * log(freR[i]) / log(2);
}
cout << "B的熵是:" << HB << endl;
cout << "R的熵是:" << HR << endl;
cout << "G的熵是:" << HG << endl;
//将这些数据写入TXT文件中
fprintf(B, "符号\t频率\n");
fprintf(G, "符号\t频率\n");
fprintf(R, "符号\t频率\n");
for (int i = 0; i < 256; i++)
{
fprintf(B, "%d\t%f\n", i, freB[i]);
fprintf(G, "%d\t%f\n", i, freG[i]);
fprintf(R, "%d\t%f\n", i, freR[i]);
}
//清除缓存,关闭文件
free(buffer);
fclose(down);
fclose(B);
fclose(G);
fclose(R);
system("pause");
return 0;
}
计算出来的熵为:
输出RGB统计文件:
下一篇: 数据压缩第三次作业