作业3:读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图和熵。
问题分解
- 读入并存放入一个unsigned char型数组
- 分开存放为rgb(参考rgb的十六进制后得知排列顺序为bgr)
- 计算出现次数和频率
- 计算信息熵
- 导出txt,绘图
#include<stdio.h>
#include<math.h>
#include <iostream>
int main()
{
FILE *fp;
if ((fp = fopen("down.rgb", "rb")) == NULL)
printf("cannot open file!\n");
else
printf("success\n");//打开文件
const int width = 256;
const int height = 256;
unsigned char cache[width*height * 3];
fread(cache, sizeof(unsigned char), 3 * width*height, fp);
unsigned char red[width*height] = { 0 };
unsigned char green[width*height] = { 0 };
unsigned char blue[width*height] = { 0 };
int ri = 0;
int gi = 0;
int bi = 0;
for (int i = 0;i < 3 * width*height; i++)
{
if (i % 3 == 0)
{
blue[bi] = cache[i];
bi++;
}
else if (i % 3 == 1)
{
green[gi] = cache[i];
gi++;
}
else if (i % 3 == 2)
{
red[ri] = cache[i];
ri++;
}
}//分三基色三组
if (ri == width * height && gi == width * height && bi == width * height)
{
printf("success\n");
}
int rtime[256] = { 0 };
int gtime[256] = { 0 };
int btime[256] = { 0 };
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < width*height; j++)
{
if (i == red[j])
rtime[i]++;
if (i == green[j])
gtime[i]++;
if (i == blue[j])
btime[i]++;
}
}//统计出现次数
double rfreq[256] = { 0 };
double gfreq[256] = { 0 };
double bfreq[256] = { 0 };
for (int i = 0; i < 256; i++) {
rfreq[i] = double(rtime[i]) / (width*height);
gfreq[i] = double(gtime[i]) / (width*height);
bfreq[i] = double(btime[i]) / (width*height);
}//计算频率
FILE *R;
FILE *G;
FILE *B;
if ((R = fopen("red.txt", "w")) == NULL)
printf("fail\n");
else
printf("success3\n");
if ((G = fopen("green.txt", "w")) == NULL)
printf("fail\n");
else
printf("success4\n");
if ((B = fopen("blue.txt", "w")) == NULL)
printf("fail\n");
else
printf("success5\n");//通过w方式用open创建txt
fprintf(R, "symbol\tfreq\n");
for (int i = 0; i < 256; i++)
{
fprintf(R, "%d\t%f\n", i, rfreq[i]);
}
fprintf(G, "symbol\tfreq\n");
for (int i = 0; i < 256; i++)
{
fprintf(G, "%d\t%f\n", i, gfreq[i]);
}
fprintf(B, "symbol\tfreq\n");
for (int i = 0; i < 256; i++)
{
fprintf(B, "%d\t%f\n", i, bfreq[i]);
}//写入txt对应的数据
double hr = 0;
double hg = 0;
double hb = 0;
for (int i = 0; i < 256; i++) {
if(rfreq[i]!=0)
hr=hr -rfreq[i] * log(rfreq[i]) / log(2);
if (gfreq[i] != 0)
hg = hg -gfreq[i] * log(gfreq[i]) / log(2);
if (bfreq[i]!= 0)
hb = hb - bfreq[i] * log(bfreq[i]) / log(2);
}
printf("红基色的熵=%f\n", hr);
printf("绿基色的熵=%f\n", hg);
printf("蓝基色的熵=%f\n", hb);//计算熵
fclose(fp);
fclose(R);
fclose(G);
fclose(B);
return 0;
}
输出结果为
三基色频率柱状图为
红
绿
蓝