[20200315]RGB文件中的概率分布示意图

作业3:读入一个24bitRGB文件(以down.rgb为例,其分辨率为256*256),输出该数据文件中R、G、B三个分量(各8bit表示)的概率分布示意图(类似下图)和熵。

#define Height 256
#define Width 256
#define color 256

#include<iostream>
#include<fstream>
#include<string>
#include<math.h>
using namespace std;

void percent(int* cnt_color, double* pct_color) 
{
	for (int i = 0; i < color; i++)
		*(pct_color + i) = *(cnt_color + i) / (Height * Width);
}

double H(double* pct_color)
{
	double h_color = 0.00;
	for (int i = 0; i < color; i++)
	{
		if (*(pct_color+i))
		{
			h_color = h_color + (*(pct_color + i)) * log2(1 / (*(pct_color + i)));
		}
	}
	return h_color;
}


int main()
{
	//创建数组
	unsigned char pic_Red[Height][Width] = { 0 },
				  pic_Green[Height][Width] = { 0 },
				  pic_Blue[Height][Width] = { 0 };
	int cnt_Red[color] = { 0 },
		cnt_Green[color] = { 0 },
		cnt_Blue[color] = { 0 };
	double pct_Red[color] = { 0.00 },
		pct_Green[color] = { 0.00 },
		pct_Blue[color] = { 0.00 };
	//double h_Red = 0.00, h_Green = 0.00, h_Blue = 0.00;
	ifstream file_in;
	ofstream Red_num, Green_num, Blue_num;
	

	//打开rgb文件
	file_in.open("down.rgb", ios::in | ios::binary);
	if (!file_in) {
		cout << "Error opening picture!" << endl;
		return 0;
	}

	//创建txt
	Red_num.open("Red_num.txt", ios::out, ios::trunc);
	Green_num.open("Green_num.txt", ios::out, ios::trunc);
	Blue_num.open("Blue_num.txt", ios::out, ios::trunc);
	if (!Red_num || !Green_num || !Blue_num) {
		cout << "Error opening txt!" << endl;
		return 0;
	}

	//统计数据
	for(int i = 0; i < Height; i++)
		for (int j = 0; j < Width; j++)
		{
			file_in.read((char*)(*(pic_Blue + i) + j), sizeof(unsigned char));
			cnt_Blue[*(*(pic_Blue + i) + j)] ++;

			file_in.read((char*)(*(pic_Green + i) + j), sizeof(unsigned char));
			cnt_Green[*(*(pic_Green + i) + j)] ++;

			file_in.read((char*)(*(pic_Red + i) + j), sizeof(unsigned char));
			cnt_Red[*(*(pic_Red + i) + j)] ++;
		}
	
	//计算百分比
	percent(cnt_Blue, pct_Blue);
	percent(cnt_Red, pct_Red);
	percent(cnt_Green, pct_Green);
	
	//输出
	Red_num << "symbol" << "\t" << "freq" << endl;
	Green_num << "symbol" << "\t" << "freq" << endl;
	Blue_num << "symbol"<<"\t"<<"freq" << endl;

	for (int i = 0; i < color; i++) 
	{
		Red_num << i << "\t" << *(pct_Red + i) << endl;
		Green_num << i << "\t" << *(pct_Green + i) << endl;
		Blue_num << i << "\t" << *(pct_Blue + i) << endl;
	}


	//计算熵
	cout << "Red分量熵为" << H(pct_Red) << endl;
	cout << "Green分量熵为" << H(pct_Green) << endl;
	cout << "Blue分量熵为" << H(pct_Blue) << endl;

	file_in.close();
	Red_num.close();
	Green_num.close();
	Blue_num.close();

	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值