作业3:读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图(类似下图)和熵。
MATLAB代码
clc;
close all;
clear all;
file1=fopen(“down.rgb”);
X=fread(file1);%读入文件
L=length(X);
R=zeros(256,1);
G=zeros(256,1);
B=zeros(256,1);
for i=1:L
if mod(i,3)==0
R(X(i)+1)=R(X(i)+1)+1;
elseif mod(i,3)==2
G(X(i)+1)=G(X(i)+1)+1;
elseif mod(i,3)==1
B(X(i)+1)=B(X(i)+1)+1;
end
end%用被3除取余数的方法判断是哪一个分量
plot(0:255,R,‘R’);
hold on;
plot(0:255,G,‘G’);
hold on;
plot(0:255,B,‘B’);
MATLAB运行结果
C++代码
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
const int width = 256;
const int height = 256;
int main()
{
const int size = width * height * 3;
FILE *p;
if ((p = fopen("down.rgb", "rb")) == NULL)
cout << "file not opened."<<endl;
else
cout << "file opened."<<endl;//判断是否打开文件
unsigned char a[size];
unsigned char R[width * height] = { 0 };
unsigned char G[width * height] = { 0 };
unsigned char B[width * height] = { 0 };
fread(a, sizeof(unsigned char),size, p);
int x = 0;
int y = 0;
int z = 0;
for (int i = 0; i < width * height * 3; i++)
{
if (i % 3 == 0)
{
B[x] = a[i];
x++;
}
else if (i % 3 == 1)
{
G[y] = a[i];
y++;
}
else if (i % 3 == 2)
{
R[z] = a[i];
z++;
}
}//用被3除求余数的方法判断是RGB哪个分量
int RT[256] = { 0 };
int GT[256] = { 0 };
int BT[256] = { 0 };
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < width * height; j++)
{
if (i == R[j])
RT[i]++;
if (i == G[j])
GT[i]++;
if (i == B[j])
BT[i]++;
}
}//统计各分量出现的次数
double RF[256] = { 0 };
double GF[256] = { 0 };
double BF[256] = { 0 };
for (int i = 0; i < 256; i++) {
RF[i] = double(RT[i]) / (width * height);
GF[i] = double(GT[i]) / (width * height);
BF[i] = double(BT[i]) / (width * height);
}//计算各分量的频率
FILE *r;
FILE *g;
FILE *b;
if ((r = fopen("r.txt", "w")) == NULL)
cout<<"file not opened."<<endl;
else
cout<<"flie opened."<<endl;
if ((g = fopen("g.txt", "w")) == NULL)
cout << "file not opened."<<endl;
else
cout << "flie opened." << endl;
if ((b = fopen("b.txt", "w")) == NULL)
cout << "file not opened."<<endl;
else
cout << "flie opened." << endl;//创建txt文件用来存放各分量数据
fprintf(r, "symbol\tfrequency\n");
for (int i = 0; i < 256; i++)
{
fprintf(r, "%d\t%f\n", i, RF[i]);
}
fprintf(g, "symbol\tfrequency\n");
for (int i = 0; i < 256; i++)
{
fprintf(g, "%d\t%f\n", i, GF[i]);
}
fprintf(b, "symbol\tfrequency\n");
for (int i = 0; i < 256; i++)
{
fprintf(b, "%d\t%f\n", i, BF[i]);
}//写入各分量数据
double HR = 0;
double HG = 0;
double HB = 0;
for (int i = 0; i < 256; i++) {
if (RF[i] != 0)
HR = HR - RF[i] * log(RF[i]) / log(2);
if (GF[i] != 0)
HG = HG - GF[i] * log(GF[i]) / log(2);
if (BF[i] != 0)
HB = HB - BF[i] * log(BF[i]) / log(2);
}//计算各分量的熵值
cout << "H(R)=" << HR <<endl;
cout << "H(G)=" << HG << endl;
cout << "H(B)=" << HB << endl;
fclose(p);
fclose(r);
fclose(g);
fclose(b);
return 0;
}
C++运行结果