如何从编码的字节数组中读取 png 图像并将其存储到 numpy 数组中?

How to read a png image from an encoded bytearray and store it into a numpy array?

我的 python socked 收到编码为 bytearray 的 PNG 图像。 该图像最初具有 RGBA32 格式和 160 x 90 的分辨率。编码后,我收到一个 bytearray,长度为 31529(相对于原始数据大小,应为 160 * 90 * 4 = 57600)字节。

如何再次解码此 bytearray 并 1) 使用 PIL 库显示它以及 2) 将其转换为 numpy 数组以处理数据?

我尝试使用 PIL 的图像模块(received_data 是我的 bytearray):

import PIL.Image as Image
# socket code...
Image.frombytes('RGBA', (160, 90), received_data)

但出现以下错误:

argument 1 must be read-only bytes-like object, not bytearray

编辑: 按照@thshea的建议,我将代码更改为 Image.frombytes('RGBA', (160, 90), bytes(received_data)),解决了上面的错误。但是,该函数似乎仍然需要原始图像数据,我得到了这个错误:

not enough image data

此外,我认为这是为了获取原始数据,并可选择编写自定义解码器?

可能有一些更好的方法,但是将字节数组包装在 BytesIO 对象中并将其作为打开的文件提供给 PIL 应该可以做到:

import io
f = io.BytesIO(received_data)
im = Image.open(f)