2020.3.9读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图(类似下图)和熵。
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
int main()
{
FILE* photo;
FILE* Bsat;
FILE* Gsat;
FILE* Rsat;
const int width = 256;
const int height = 256;
fopen_s(&photo, "down.rgb", "rb");//打开要读出的RGB文件(以“rb”方式打开)
fopen_s(&Bsat, "B_sat.txt", "w");//打开3个要输出的数据统计文件(以“w”方式打开,可命名为R_sat.txt等)
fopen_s(&Gsat, "G_sat.txt", "w");
fopen_s(&Rsat, "R_sat.txt", "w");
unsigned char* buffer = NULL;
buffer= (unsigned char*)malloc(sizeof(unsigned char) * 3 * width * height);
fread(buffer,sizeof(unsigned char), 3 * width * height, photo);
unsigned char B[width * height] ={ 0 };//开辟3个width*height的unsigned char型数组
unsigned char G[width * height] ={ 0 };
unsigned char R[width * height] ={ 0 };
int nB = 0;
int nG = 0;
int nR = 0;
//将RGB数据从RGB文件中读出,并分别保存到3个数组中
for (int i = 0; i <3*width*height; i++)
{
if (i % 3 == 0)
{
B[nB]= *(buffer+i);
nB++;
}
else if(i % 3 == 1)
{
G[nG]= *(buffer + i);
nG++;
}
else if (i % 3 == 2)
{
R[nR]= *(buffer + i);
nR++;
}
}
//计算数据的概率分布
int numB[256] = { 0 };
double freqB[256] = { 0 };
for (int i = 0; i < 256;i++)
{
for (int j = 0; j < width* height; j++)
{
if (i == B[j])
{
numB[i]++;
}
}
freqB[i]= double(numB[i]) / (width *height);
}
int numG[256] = { 0 };
double freqG[256] = { 0 };
for (int i = 0; i < 256;i++)
{
for (int j = 0; j < width* height; j++)
{
if (i == G[j])
{
numG[i]++;
}
}
freqG[i]= double(numG[i]) / (width *height);
}
int numR[256] = { 0 };
double freqR[256] = { 0 };
for (int i = 0; i < 256;i++)
{
for (int j = 0; j < width* height; j++)
{
if (i == R[j])
{
numR[i]++;
}
}
freqR[i]= double(numR[i]) / (width *height);
}
//计算熵
double HB = 0;
double HG = 0;
double HR = 0;
for (int i = 0; i < 256;i++)
{
if (freqB[i] != 0)
{
double a=2;
HB= HB - freqB[i] * log(freqB[i]) / log(a);
}
if (freqG[i] != 0)
{
double a=2;
HG= HG - freqG[i] * log(freqG[i]) / log(a);
}
if (freqR[i] != 0)
{
double a=2;
HR= HR - freqR[i] * log(freqR[i]) / log(a);
}
}
printf("B的熵是%f\n",HB);
printf("G的熵是%f\n",HG);
printf("R的熵是%f\n",HR);
//将这些数据写入3个数据统计txt文件中。Txt文件的写入方式如下所示(每行的两个数据用tab分开)
fprintf(Bsat,"symbol\tfreq\n");
fprintf(Gsat,"symbol\tfreq\n");
fprintf(Rsat,"symbol\tfreq\n");
for (int i = 0; i < 256;i++)
{
fprintf(Bsat,"%d\t%f\n",i,freqB[i]);
fprintf(Gsat,"%d\t%f\n", i,freqG[i]);
fprintf(Rsat,"%d\t%f\n", i,freqR[i]);
}
free(buffer);
fclose(photo);
fclose(Bsat);
fclose(Gsat);
fclose(Rsat);
system("pause");
return 0;
}