#include
#include
using namespace std;
#define Height 256
#define Width 256
#define Size 256
// 计算熵
double Count_Entropy(double* freq) {
double entropy=0;
for (int i = 0; i < Size; i++)
{
if ((*(freq + i)) != 0) {
entropy += (*(freq + i)) * log2(1 / (*(freq + i)));
}
}
return entropy;
}
// 计算频率
void Count_freq(double *freq,int *cnt) {
for (int i = 0; i < Size; i++) {
*(freq + i) = *(cnt + i) / (double)(Height * Width);
}
}
// 输出至 .txt
void PrintToTxt(double* freq, ofstream& File) {
for (int i = 0; i < Size; i++) {
File <<i<<"\t"<<*(freq+i)<< endl;
}
}
int main(){
// 开辟3个width * height的unsigned char型数组
unsigned char Red[Height][Width] = { 0 }, Green[Height][Width] = { 0 }, Blue[Height][Width] = {};
// 开辟3个数组用以统计
int Red_cnt[Size] = { 0 }, Blue_cnt[Size] = { 0 }, Green_cnt[Size] = { 0 };
// 开辟3个数组用以计算
double Red_freq[Size] = { 0 }, Blue_freq[Size] = { 0 }, Green_freq[Size] = { 0 };
// 打开要读出的RGB文件
ifstream File_in;
File_in.open("C:\\File_xieyh\\FILE\\down.rgb", ios::in | ios::binary);
if (!File_in) {
cout << "Error opening down.rgb" << endl;
return 0;
}
// 打开3个要输出的数据统计文件
ofstream R_sat, G_sat, B_sat;
R_sat.open("R_sat.txt", ios::out, ios::trunc);
G_sat.open("G_sat.txt", ios::out, ios::trunc);
B_sat.open("B_sat.txt", ios::out, ios::trunc);
if (!R_sat||!G_sat||!B_sat) {
cout << "Error opening R_sat.txt||G_sat.txt||B_sat.txt" << endl;
return 0;
}
// 向txt写入抬头
R_sat << "symbol\tfreq" << endl;
G_sat << "symbol\tfreq" << endl;
B_sat << "symbol\tfreq" << endl;
// 将RGB数据从RGB文件中读出,并分别保存到3个数组中
for (int i = 0; i <Height; i++) {
for (int j = 0; j < Width; j++) {
File_in.read((char*)(*(Blue + i)+j), sizeof(unsigned char));
Blue_cnt[*(*(Blue + i) + j)]++;
File_in.read((char*)(*(Green + i) + j), sizeof(unsigned char));
Green_cnt[*(*(Green + i) + j)]++;
File_in.read((char*)(*(Red + i) + j), sizeof(unsigned char));
Red_cnt[*(*(Red + i) + j)]++;
}
}
// 计算数据的概率分布和
Count_freq(Red_freq, Red_cnt);
Count_freq(Green_freq, Green_cnt);
Count_freq(Blue_freq, Blue_cnt);
// 打印至 .txt
PrintToTxt(Red_freq, R_sat);
PrintToTxt(Green_freq, G_sat);
PrintToTxt(Blue_freq, B_sat);
cout << "已输出至txt" << endl;
// 计算熵
double Red_Entropy, Green_Entropy, Blue_Entropy;
Red_Entropy = Count_Entropy(Red_freq);
Green_Entropy = Count_Entropy(Green_freq);
Blue_Entropy = Count_Entropy(Blue_freq);
// 输出熵
cout << "Red_Entropy=" << Red_Entropy << endl;
cout << "Green_Entropy=" << Green_Entropy << endl;
cout << "Blue_Entropy=" << Blue_Entropy << endl;
//关闭文件
File_in.close();
R_sat.close();
G_sat.close();
B_sat.close();
return 0;
}
二、数据统计文件
(1)R分量
- R_sat.txt
- R分量统计图
(2)G分量
- G_sat.txt
- G分量统计图
(3)B分量
- B_sat.txt
- B分量统计图
三、各分量的熵