欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

读入 RGB 文件并输出三个分量的概率分布示意图和熵

程序员文章站 2022-07-14 22:16:24
...

基本思路
1.读入一个RGB文件,创建3个空txt文件
2.开辟3个数组,将RGB数据从RGB文件中读出,并分别保存到3个数组中
3.计算各颜色通道数据概率分布,并写入txt文件
4.计算熵并输出
代码如下

#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
#define A  65536
int main()
{
 //打开,创建文件
 FILE* image, * red, * green,*blue; 
 fopen_s(&image, "C:\\Users\\XMGO\\Desktop\\数据压缩\\down.rgb", "rb");
 fopen_s(&red, "C:\\Users\\XMGO\\Desktop\\数据压缩\\Red.txt", "w");
 fopen_s(&green, "C:\\Users\\XMGO\\Desktop\\数据压缩\\Green.txt", "w");
 fopen_s(&blue, "C:\\Users\\XMGO\\Desktop\\数据压缩\\Blue.txt", "w");
 //定义R、G、B分量
 unsigned char R[A] = { 0 },G[A] = { 0 }, B[A] = { 0 };
 //定义频率分量
 double R_F[256] = { 0 },G_F[256] = { 0 },B_F[256] = { 0 };
 //定义熵
 double R_S = 0,G_S = 0, B_S = 0;
 //分别读取R、G、B三个分量到数组中
 unsigned char sum[256*256*3];
 fread(sum, 1, 256*256*3, image);
 for (int i = 0, j = 0; i < 256*256*3; i = i + 3, j++)
 {
  B[j] = *(sum + i);
  G[j] = *(sum + i + 1);
  R[j] = *(sum + i + 2); 
 }
 //计数三通道各颜色值次数
 for (int i = 0; i < 256; i++)
 {
  for (int j = 0; j < A; j++)
  {
   if (int(R[j] == i)) {R_F[i]++;}
   if (int(G[j] == i)) {G_F[i]++;}
   if (int(B[j] == i)) {B_F[i]++;}
  }
 }
//计算频率
 for (int i = 0; i < 256; i++)
 {
  R_F[i] = R_F[i] / (256 * 256);
  B_F[i] = B_F[i] / (256 * 256);
  G_F[i] = G_F[i] / (256 * 256);
 }
 //将频率写入文件
 fprintf(red, "值\t概率\n");
 for (int i = 0; i < 256; i++)
 {
  fprintf(red, "%d\t%f\n", i, R_F[i]);
 }
 fprintf(green, "值\t概率\n");
 for (int i = 0; i < 256; i++)
 {
  fprintf(green, "%d\t%f\n", i, G_F[i]);
 }
 fprintf(blue, "值\t概率\n");
 for (int i = 0; i < 256; i++)
 {
  fprintf(blue, "%d\t%f\n", i, B_F[i]);
 }
 //计算并输出熵
 for (int i = 0; i < 256; i++)
 {
  if (R_F[i] != 0) {R_S += -R_F[i] * log(R_F[i]) / log(2);}
  if (G_F[i] != 0) {G_S += -G_F[i] * log(G_F[i]) / log(2);}
  if (B_F[i] != 0) {B_S += -B_F[i] * log(B_F[i]) / log(2);}
 }
 cout << "R熵为" << R_S << endl;
 cout << "G熵为" << G_S << endl;
 cout << "B熵为" << B_S << endl;
 fclose(image);
 fclose(red);
 fclose(green);
 fclose(blue);
 return 0;
}
 

读入 RGB 文件并输出三个分量的概率分布示意图和熵
读入 RGB 文件并输出三个分量的概率分布示意图和熵
用matlab画图
red
读入 RGB 文件并输出三个分量的概率分布示意图和熵
green
读入 RGB 文件并输出三个分量的概率分布示意图和熵
blue
读入 RGB 文件并输出三个分量的概率分布示意图和熵