在编写之前需要进行一些准备工作:
- 需要有支持RGB文件读入的头文件
- Xcode本身不支持对数运算,所以在求熵时需要添加cmath头文件
#include <iostream>
#include<cmath>
#include <fstream>
准备工作做好后,可以开始编写代码了:
#include <iostream>
#include<cmath>
#include <fstream>
#define Size 65536
using namespace std;
int main()
{
//导入rgb文件并对txt存储文件命名
ifstream iofile("/Users/yaohaoyuan/Downloads/The Third Work/down.rgb", ios::binary);
ofstream outfileR("/Users/yaohaoyuan/Downloads/The Third Work/R.txt", ios::trunc);
ofstream outfileG("/Users/yaohaoyuan/Downloads/The Third Work/G.txt", ios::trunc);
ofstream outfileB("/Users/yaohaoyuan/Downloads/The Third Work/B.txt", ios::trunc);
//输出txt文件抬头
outfileR << "symbol\tfreq" << endl;
outfileG << "symbol\tfreq" << endl;
outfileB << "symbol\tfreq" << endl;
if (!iofile)
{
cout << "File import failed!" << endl;
exit(1);
}
//创建三个数组用于存储
unsigned char R_i[Size];
unsigned char G_i[Size];
unsigned char B_i[Size];
int R[256] = { 0 }, G[256] = { 0 }, B[256] = { 0 };
//文件读取&复制
for (int i = 0; i < Size; i++)
{
iofile.read((char*)&B_i[i], sizeof(unsigned char));
B[int(B_i[i])]++;
iofile.read((char*)&G_i[i], sizeof(unsigned char));
G[int(G_i[i])]++;
iofile.read((char*)&R_i[i], sizeof(unsigned char));
R[int(R_i[i])]++;
}
//计算各分量的信源熵,信源熵计算公式:H(x)=E[I(xi)]=E[log2 1/p(xi)]=-ξp(xi)log2 p(xi)(i=1,2,..n)
double Entropy_G = 0, Entropy_B = 0, Entropy_R = 0;
for (int i = 0; i < 256; i++)
{
double Probability_G = G[i] / Size;
if (Probability_G != 0)
{
Entropy_G += Probability_G * log(1 / Probability_G) / log(2);
}
double Probability_B = B[i] / Size;
if (Probability_B != 0)
{
Entropy_B += Probability_B * log(1 / Probability_B) / log(2);
}
double Probability_R = R[i] / Size;
if (Probability_R != 0)
{
Entropy_R += Probability_R * log(1 / Probability_R) / log(2);
}
}
//输出各分量的熵值
cout << "Entropy_Red=" << Entropy_R << endl;
cout << "Entropy_Green=" << Entropy_G << endl;
cout << "Entropy_Blue=" << Entropy_B << endl;
//利用outfile对象把希望输出到文件中的数据输出到txt中
for (int i = 0; i < 256; i++)
{
outfileR << i << "\t" << R[i] / Size << endl;
outfileG << i << "\t" << G[i] / Size << endl;
outfileB << i << "\t" << B[i] / Size << endl;
}
//输出完成后要关闭对象与文件之间的联接
iofile.close();
outfileR.close();
outfileG.close();
outfileB.close();
cout << "Files created successfully!" << endl;
return 0;
}
R,G,B的熵值如下:
将数据导入Excel,作表可得:
各熵值比较: