根据我的问题 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通道数组,然后你可以将其 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)
编辑:将一个W×H×2的uint8s数组转换成一个W×H的uint16s数组。
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。