读入一个RGB文件,输出各分量概率分布示意图和熵

代码实现

#include
#include
#include
using namespace std;
const int width = 256;
const int height = 256;

int num_b[width * height] = { 0 };
int num_g[width * height] = { 0 };
int num_r[width * height] = { 0 };
//由于局部变量的申请空间存放于栈中,windows里默认栈内存是1M,当申请空间大于1M时就会出现溢出错误。所以放到全局变量中
unsigned char A[width * height * 3]; 
unsigned char R[width * height];
unsigned char G[width * height];
unsigned char B[width * height];

double En_R = 0;
double En_G = 0;
double En_B = 0;

int main()
{
 FILE* Image;
 fopen_s(&Image, "down.rgb", "rb");
 FILE* RED;
 fopen_s(&RED, "R_sat.txt", "w");
 FILE* GREEN;
 fopen_s(&GREEN, "G_sat.txt", "w");
 FILE* BLUE;
 fopen_s(&BLUE, "B_sat.txt", "w");//打开所需文件
 fread(A, sizeof(unsigned char), width * height * 3, Image);//存储down.rgb中的全部数据到A中
 for (int i = 0; i < width * height; i++)
 {
  B[i] = A[i * 3];
  G[i] = A[i * 3 + 1];
  R[i] = A[i * 3 + 2];
 }//将rgb数据分别保存在3个数组中
 for (int i = 0; i < width * height; i++)
 {
  num_b[B[i]]++;
  num_g[G[i]]++;
  num_r[R[i]]++;
 }//计算每个数出现的次数
 for (int i = 0; i < width * height; i++)
 {
  if (num_b[i] != 0)
  {
   En_B += (double)num_b[i] / width / height / log(2) * (log(width * height)-log(num_b[i]) );
  }
  if (num_g[i] != 0)
  {
   En_G += (double)num_g[i] / width / height / log(2) * (log(width * height) - log(num_g[i]));
  }
  if (num_r[i] != 0)
  {
   En_R += (double)num_r[i] / width / height / log(2) * (log(width * height) - log(num_r[i]));
  }
 }//求信息熵
 cout << "H(Red) = " << En_R << endl;
 cout << "H(Green) = " << En_G << endl;
 cout << "H(Blue) = " << En_B << endl;
 fprintf(BLUE, "symbol\tfreq\n");
 fprintf(GREEN, "symbol\tfreq\n");
 fprintf(RED, "symbol\tfreq\n");
 for (int i = 0; i < 256; i++)
 {
  fprintf(BLUE, "%d\t%f\n", i, (double)num_b[i]/(width * height));
  fprintf(GREEN, "%d\t%f\n", i, (double)num_g[i] / (width * height));
  fprintf(RED, "%d\t%f\n", i, (double)num_r[i] / (width * height));
 }
}

运行结果

读入一个RGB文件,输出各分量概率分布示意图和熵_第1张图片
读入一个RGB文件,输出各分量概率分布示意图和熵_第2张图片读入一个RGB文件,输出各分量概率分布示意图和熵_第3张图片读入一个RGB文件,输出各分量概率分布示意图和熵_第4张图片
读入一个RGB文件,输出各分量概率分布示意图和熵_第5张图片

你可能感兴趣的:(读入一个RGB文件,输出各分量概率分布示意图和熵)