用python读取RGB及YUV格式图片并计算各自熵

本文介绍如何使用Python读取RGB和YUV格式的图像文件,并计算各颜色通道的熵值,以此评估图像的数据分布及潜在压缩效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用python读取RGB及YUV格式图片并计算各自熵

一、前言

本次任务内容:
对down.rgb和down.yuv分析三个通道的概率分布,并计算各自的熵。两个文件的分辨率均为256*256,yuv为4:2:0采样空间,存储格式为:rgb文件按每个像素BGR分量依次存放;YUV格式按照全部像素的Y数据块、U数据块和V数据块依次存放。
虽然上学期曾使用过c++读取YUV格式文件并进行一系列处理,但相比之下,python进行此类操作更加方便,可调用的包更多,个人也更加熟悉。故此次选择python作为编程语言。

二、读取图像

1.RGB

#读取RGB图像
f = open(image_path,"rb")
data = f.read()
f.close()
data = [int(x) for x in data]
data = np.array(data).reshape((256*256, 3)).astype(np.uint8)

原本为了方便查看各个通道的图像将其reshape为(256,256,3)。后来在计算熵时发现np.bincount()函数只能传入一维数据,故改为二维矩阵。

图片显示
在这里插入图片描述
注意:数据存储顺序为BGR,而不是想当然的RGB

通过查阅资料,发现opencv中默认读取方式也为BGR,日后需注意这一点

The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.

2.YUV

先是查阅了csdn上一些别人写的读取YUV的代码,感觉过于复杂。经过试验,发现直接通过f.read()限制每次读取大小即可最快捷的读取YUV,读取的指针会停留在上次读取的结束位置。

#读取YUV图像
f = open(image_path,"rb")
data_Y = f.read(256*256)
data_U = f.read(128*128)
data_V = f.read(128*128)
data_Y = [int(x) for x in data_Y]
data_U = [int(x) for x in data_U]
data_V = [int(x) for x in data_V]

图片显示
Y
在这里插入图片描述
U
在这里插入图片描述
V
在这里插入图片描述

三、计算熵

1.公式与函数

熵计算公式
函数

#计算熵函数
def entropy(X):
    n = len(X)

    counts = np.bincount(X)
    probs = counts[np.nonzero(counts)] / n

    en = 0
    for i in range(len(probs)):
        en = en - probs[i] * np.log(probs[i])/np.log(2)

    return en

np.bincount()函数注释:
在这里插入图片描述
np.nonzero()函数注释
在这里插入图片描述

2.RGB

#计算熵
data_B = data[:,0]
data_G = data[:,1]
data_R = data[:,2]
B = entropy(data_B)
G = entropy(data_G)
R = entropy(data_R)

print(B)
print(G)
print(R)

结果:

RGB
7.2295528905518477.1784624848350996.856861210882991

2.YUV

#计算熵
Y = entropy(data_Y)
U = entropy(data_U)
V = entropy(data_V)

结果:

YUV
6.33181854186750755.1264019143997214.113143002049819

四、总结

通过计算结果可得,以YUV格式存储此图像可以将其压缩的更小。通过文件管理器查看down.rgb大小为192kb,而down.yuv大小仅为96kb,但学识有限,目前还不清楚是否与此相关(搞懂了回来更新)。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值