思路:开辟3个width*height的unsigned char型数组;打开要读出的RGB文件(以“rb”方式打开),打开3个要输出的数据统计文件(以“w”方式打开,可命名为R_sat.txt等);将RGB数据从RGB文件中读出,并分别保存到3个数组中,期间计算数据的概率分布和熵,并将这些数据写入3个数据统计txt文件中。
#include “pch.h”
#include<stdio.h>
#include<math.h>
#include
int main()
{
FILE fp;
fp = fopen(“down.rgb”, “rb”);
const int width = 256;
const int height = 256;
unsigned char cache[widthheight * 3];
fread(cache, sizeof(unsigned char), widthheight * 3, fp);
unsigned char red[widthheight] = { 0 };
unsigned char green[widthheight] = { 0 };
unsigned char blue[widthheight] = { 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++;
}
}
(这一部分是计算rgb的数目)
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;
R = fopen("red.txt", "w");
G = fopen("green.txt", "w");
B = fopen("blue.txt", "w");
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]);
}
(这一部分写入数据)
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("H(红基色)=%f\n", hr);
printf("H(绿基色)=%f\n", hg);
printf("H(蓝基色)=%f\n", hb);
fclose(fp);
fclose(R);
fclose(G);
fclose(B);
return 0;
}
(这一部分计算熵)
结果如下: