c++代码
#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int w=256;
int h=256;
unsigned char r[65535];
unsigned char g[65535];
unsigned char b[65535];
double p_r[256]={0};
double p_g[256]={0};
double p_b[256]={0};
double h_r,h_g,h_b;
int main()
{
FILE* fp = fopen("D:\\x.rgb", "rb+");
FILE* Red=fopen("Red.txt", "w");
FILE* Green=fopen( "Green.txt", "w");
FILE* Blue=fopen( "Blue.txt", "w");
unsigned char a[196608];
fread(a, sizeof(unsigned char), 196608, fp);
for (int i=0,j=0;i<196608;i=i+3,j++)
{
b[j] = a[i];
g[j] = a[i+1];
r[j] = a[i+2];
}
for(int i=0;i<256;i++)
{
for(int j=0;j<65536;j++)
{
if(int(r[j])==i) {p_r[i]++;}
}
}
for(int i=0;i<256;i++)
{
for(int j=0;j<65536;j++)
{
if(int(g[j])==i) {p_g[i]++;}
}
}
for(int i=0;i<256;i++)
{
for(int j=0;j<65536;j++)
{
if(int(b[j])==i) {p_b[i]++;}
}
}
for(int i=0;i<256;i++)
{
p_r[i]=p_r[i]/double(w*h);
p_g[i]=p_g[i]/double(w*h);
p_b[i]=p_b[i]/double(w*h);
}
for(int i=0;i<256;i++)
{
if(p_r[i]!=0)
{
h_r+=p_r[i]*(log(1/p_r[i])/log(2));
}
}
cout<<"r的熵为"<<h_r<<endl;
for(int i=0;i<256;i++)
{
if(p_g[i]!=0)
{
h_g+=p_g[i]*(log(1/p_g[i])/log(2));
}
}
cout<<"g的熵为"<<h_g<<endl;
for(int i=0;i<256;i++)
{
if(p_b[i]!=0)
{
h_b+=p_b[i]*(log(1/p_b[i])/log(2));
}
}
cout<<"b的熵为"<<h_b<<endl;
fprintf(Red,"数值\t概率\n");
for(int i=0;i<256;i++)
{
fprintf(Red,"%d\t%f\n",i,p_r[i]);
}
fprintf(Green,"数值\t概率\n");
for(int i = 0; i < 256; i++)
{
fprintf(Green,"%d\t%f\n",i,p_g[i]);
}
fprintf(Blue,"数值\t概率\n");
for (int i = 0; i < 256; i++)
{
fprintf(Blue,"%d\t%f\n",i,p_b[i]);
}
fclose(Red);
fclose(Green);
fclose(Blue);
system("pause");
}
相关结果