python - 如何使用Python将RGB565字节数组转换为RGB888字节数组?

标签 python numpy rgb

根据我的问题RGB888 to 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 channel 数组,然后您可以将其 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。

关于python - 如何使用Python将RGB565字节数组转换为RGB888字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61816430/

相关文章:

python - 如何存储多个不同长度的numpy一维数组并打印它

opencv - 如何将分量从HSV转换为RGB,反之亦然

在 C__ 中将 PPM 从 RGB 转换为 HSL

python - 对彼此链接的 2 个列表进行排序

python - 无法在 Ubuntu Linux 中使用 pip 安装 Python 包 : InsecurePlatformWarning, SSLError,tlsv1 警报协议(protocol)版本

python - Matplotlib 显示错误 - 窄条和扭曲的轴

java - 显示图像的 RGB 编号

python - 如何创建与其自身具有 ManyToMany 关系的 Elixir 类

image-processing - 使用 skimage 或 numpy 进行灰度梯度

python - 计算匹配字符串的实例和累计总值