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

用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)

结果:

R G B
7.229552890551847 7.178462484835099 6.856861210882991

2.YUV

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

结果:

Y U V
6.3318185418675075 5.126401914399721 4.113143002049819

四、总结

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

猜你喜欢

转载自blog.csdn.net/cppKillMe/article/details/114417577