将/"inflate"未对齐的像素数据(bgr4)转换为字节对齐的numpy数组

Convert / "inflate" unaligned pixel data (bgr4) to a byte-aligned numpy array

我有一张深奥格式 (BGR4) 的图像,我想将其加载到 numpy 中。在 BGR4 中,各个像素是字节对齐的(谢天谢地)并且由编码在单个字节中的 3 个组件(B、G 和 R)组成。它们的顺序如下:b0000BGGR.

这是一个大小为 (1, 2) 的示例图像,又名。 2 个像素:


img_bytes = b"\x0F\x09"  # this is how it looks in memory
img = np.array([[1, 3, 1], [1, 0, 1]], dtype=np.uint8)  # this is my desired result

由于每张图像中有很多像素,因此扩充此类数组的最高效方法是什么?

我对 BGR8 也有同样的问题(排序:bBBBGGGRR),但我认为方法是相似的,当我到达那里时我会过那座桥:)

这是一个遵循@MichaelButscher 在评论中提出的建议的 numpy 实现:

img_bytes = b"\x0f\x09"  # this is how it looks in memory

#    b0000BGGR
b = 0b00001000
g = 0b00000110
r = 0b00000001

template = np.array([b, g, r], dtype=np.uint8)[:,None]
shifts   = np.array([3, 1, 0], dtype=np.uint8)[:,None]

arr = np.frombuffer(img_bytes, dtype=np.uint8)
res = (arr & template) >> shifts
print(res.T)
[[1 3 1]
 [1 0 1]]

您可能需要调整转置顺序以获得更好的性能。