作业3:读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图(类似下图)和熵。
#define Height 256
#define Width 256
#define color 256
#include<iostream>
#include<fstream>
#include<string>
#include<math.h>
using namespace std;
void percent(int* cnt_color, double* pct_color)
{
for (int i = 0; i < color; i++)
*(pct_color + i) = *(cnt_color + i) / (Height * Width);
}
double H(double* pct_color)
{
double h_color = 0.00;
for (int i = 0; i < color; i++)
{
if (*(pct_color+i))
{
h_color = h_color + (*(pct_color + i)) * log2(1 / (*(pct_color + i)));
}
}
return h_color;
}
int main()
{
//创建数组
unsigned char pic_Red[Height][Width] = { 0 },
pic_Green[Height][Width] = { 0 },
pic_Blue[Height][Width] = { 0 };
int cnt_Red[color] = { 0 },
cnt_Green[color] = { 0 },
cnt_Blue[color] = { 0 };
double pct_Red[color] = { 0.00 },
pct_Green[color] = { 0.00 },
pct_Blue[color] = { 0.00 };
//double h_Red = 0.00, h_Green = 0.00, h_Blue = 0.00;
ifstream file_in;
ofstream Red_num, Green_num, Blue_num;
//打开rgb文件
file_in.open("down.rgb", ios::in | ios::binary);
if (!file_in) {
cout << "Error opening picture!" << endl;
return 0;
}
//创建txt
Red_num.open("Red_num.txt", ios::out, ios::trunc);
Green_num.open("Green_num.txt", ios::out, ios::trunc);
Blue_num.open("Blue_num.txt", ios::out, ios::trunc);
if (!Red_num || !Green_num || !Blue_num) {
cout << "Error opening txt!" << endl;
return 0;
}
//统计数据
for(int i = 0; i < Height; i++)
for (int j = 0; j < Width; j++)
{
file_in.read((char*)(*(pic_Blue + i) + j), sizeof(unsigned char));
cnt_Blue[*(*(pic_Blue + i) + j)] ++;
file_in.read((char*)(*(pic_Green + i) + j), sizeof(unsigned char));
cnt_Green[*(*(pic_Green + i) + j)] ++;
file_in.read((char*)(*(pic_Red + i) + j), sizeof(unsigned char));
cnt_Red[*(*(pic_Red + i) + j)] ++;
}
//计算百分比
percent(cnt_Blue, pct_Blue);
percent(cnt_Red, pct_Red);
percent(cnt_Green, pct_Green);
//输出
Red_num << "symbol" << "\t" << "freq" << endl;
Green_num << "symbol" << "\t" << "freq" << endl;
Blue_num << "symbol"<<"\t"<<"freq" << endl;
for (int i = 0; i < color; i++)
{
Red_num << i << "\t" << *(pct_Red + i) << endl;
Green_num << i << "\t" << *(pct_Green + i) << endl;
Blue_num << i << "\t" << *(pct_Blue + i) << endl;
}
//计算熵
cout << "Red分量熵为" << H(pct_Red) << endl;
cout << "Green分量熵为" << H(pct_Green) << endl;
cout << "Blue分量熵为" << H(pct_Blue) << endl;
file_in.close();
Red_num.close();
Green_num.close();
Blue_num.close();
return 0;
}