簡體   English   中英

如何使用 Python 將 RGB565 字節數組轉換為 RGB888 字節數組?

[英]How can I use Python to convert RGB565 byte array to RGB888 byte array?

根據我對RGB888 到 RGB565的問題,我想做 RGB565 到 RGB888,這是我的測試代碼,但是我卡在轉換為 RGB888 字節數組上。

import numpy as np
np.random.seed(42)
im = np.random.randint(0,256,(1,4,2), dtype=np.uint8)

# >>> im.nbytes
# 8
# >>> im
# array([[[102, 220],
#        [225,  95],
#        [179,  61],
#        [234, 203]]], dtype=uint8)

# Make components of RGB888
R8 = (im[...,0] & 0xF8).astype(np.uint32) << 8
G8 = (im[...,0] & 0x07).astype(np.uint32) << 5 | (im[...,1] & 0xE0).astype(np.uint32)
B8 = (im[...,1] & 0x1F).astype(np.uint32)
RGB888 = R8 | G8 | B8

# >>> RGB888.nbytes
# 16 <= here I think it should be 12 (4x3 bytes)

# >>> RGB888.reshape(1, 4, 3)
# Traceback (most recent call last):
#   File "<input>", line 1, in <module>
# ValueError: cannot reshape array of size 4 into shape (1,4,3)

當我使用 astype(np.uint16) 時,一些值變為 0,因為它需要更大的數據類型來存儲,這就是我在上面的代碼中使用 unit32 的原因。

我知道unit32會使上面代碼的RGB888大小為16,所以我想問一下是否有其他正確的方法將RGB565轉換為RGB888?

像這樣的東西應該讓你從 RGB565 uint16到三個 uint8 通道 arrays,然后你可以將其dstack成單個 3 維 RGB 圖像:

import numpy as np
np.random.seed(42)
im = np.random.randint(0,65536,(4,4), dtype=np.uint16)

MASK5 = 0b011111
MASK6 = 0b111111

# TODO: BGR or RGB? Who knows!
b = (im & MASK5) << 3
g = ((im >> 5) & MASK6) << 2
r = ((im >> (5 + 6)) & MASK5) << 3

# Compose into one 3-dimensional matrix of 8-bit integers
rgb = np.dstack((r,g,b)).astype(np.uint8)

編輯:將 uint8s 的 W x H x 2 數組轉換為 uint16s 的 W x H 數組,

import numpy as np
np.random.seed(42)
im = np.random.randint(0,256,(4,4,2), dtype=np.uint8)

b1 = im[:,:,0].astype(np.uint16)
b2 = im[:,:,1].astype(np.uint16)
im = (b1 << 8 | b2)

您可能需要根據源數組的字節順序交換 b1 和 b2 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM