用C/C++读取rgb格式文件数据并分析其概率分布

rgb格式文件并不多见。其存储方式为B G R Y 的数值顺序存储
以下图为例:
用C/C++读取rgb格式文件数据并分析其概率分布_第1张图片
将此图的rgb格式文件用FlexHEX打开后是这样的:

用C/C++读取rgb格式文件数据并分析其概率分布_第2张图片
其中存储数据的顺序为B G R Y
我们用codeblock编译C++语言文件对其进行分析
代码如下:


```cpp
#include "iostream"
#include"stdio.h"
#include"math.h"
using namespace std;
double entropy(double freq[256])
{
    double entropy = 0;
    for (int i = 0; i < 256; i++)
    {
        if (freq[i] == 0)
            continue;
        entropy = entropy - freq[i]*log(freq[i])/log(2);//计算BGR的熵
    }
    return entropy;
}

int main()
{
	//图像分辨率为256*256,格式为bgr
	unsigned char* b = new unsigned char[256*256];
	unsigned char* g = new unsigned char[256*256];
	unsigned char* r = new unsigned char[256*256];
	unsigned char* img = new unsigned char[256*256*3];
	FILE* fp = fopen("E:\\大三下\\数据压缩\\down.rgb", "rb");
	if (fp == NULL)
		cout << "无法读取图像" << endl;
	fread(img, sizeof(unsigned char), 256*256*3, fp);
	fclose(fp);
	for (int i = 0;i < 256*256; i++)
	{
		b[i] = img[3*i];
		g[i] = img[3*i+1];
		r[i] = img[3*i+2];
	}
	//计算分布概率
	double freb[256] = {0};
	double freg[256] = {0};
	double frer[256] = {0};
	for (int i = 0; i < 256; i++)
	{
	    int countb = 0, countg = 0, countr = 0;
		for (int j = 0; j < 256 * 256; j++)
		{
			if ((int)b[j] == i)
				countb ++;
			if ((int)g[j] == i)
				countg ++;
			if ((int)r[j] == i)
				countr++;
		}
		freb[i] = (double)countb/256/256;
		freg[i] = (double)countg/256/256;
		frer[i] = (double)countr/256/256;
	}
	//计算熵
	double entropyB = 0, entropyG = 0, entropyR = 0;
	entropyB = entropy(freb);
	entropyG = entropy(freg);
	entropyR = entropy(frer);
	//输出txt文件
	char s[] = "symbol\tfrequency\n";
	FILE* dataB = fopen("E:\\大三下\\数据压缩\\b.txt","w");
	fprintf(dataB, s);
	FILE* dataG = fopen("E:\\大三下\\数据压缩\\g.txt","w");
	fprintf(dataG, s);
	FILE* dataR = fopen("E:\\大三下\\数据压缩\\r.txt","w");
	fprintf(dataR, s);
	for (int i = 0;i < 256; i++)
	{
		fprintf(dataB,"%d\t%f\n",i, freb[i]);
		fprintf(dataG,"%d\t%f\n",i, freg[i]);
		fprintf(dataR,"%d\t%f\n",i, frer[i]);
	}
	fprintf(dataB,"entropy = %f",entropyB);
    fprintf(dataG,"entropy = %f",entropyG);
    fprintf(dataR,"entropy = %f",entropyR);
	fclose(dataB);
	fclose(dataG);
	fclose(dataR);
}

最后输出到txt文件中是这样的用C/C++读取rgb格式文件数据并分析其概率分布_第3张图片
将其中的数据导入excel生成概率分布图:
用C/C++读取rgb格式文件数据并分析其概率分布_第4张图片
用C/C++读取rgb格式文件数据并分析其概率分布_第5张图片
之前因为不熟悉编辑器没有显示图片,已更正(2020.5.4)

你可能感兴趣的:(Assignment)