用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,但學識有限,目前還不清楚是否與此相關(搞懂了回來更新),
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266999.html
標籤:其他
下一篇:【MFC】多國語言工具列
