BytesIO对象到映像

smi*_*y84 5 python io python-imaging-library python-3.x

我试图在程序中使用枕头将摄像机的字节字符串保存到文件中。这是一个示例,该示例包含一个来自我的相机的小原始字节字符串,该字符串应使用LSB和12位表示分辨率为10x5像素的灰度图像:

import io
from PIL import Image

rawBytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
rawIO = io.BytesIO(rawBytes)
rawIO.seek(0)
byteImg = Image.open(rawIO)
byteImg.save('test.png', 'PNG')
Run Code Online (Sandbox Code Playgroud)

但是我在第7行(带有Image.open)收到以下错误:

OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8>
Run Code Online (Sandbox Code Playgroud)

Pillow的文档暗示这是要走的路。

我试图从中应用解决方案

但无法正常运作。为什么这不起作用?

Mic*_*oom 5

我不确定生成的图像应该是什么样子(你有例子吗?),但如果你想将每个像素有 12 位的打包图像解包成 16 位图像,你可以使用以下代码:

import io
from PIL import Image

rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()
Run Code Online (Sandbox Code Playgroud)