BytesIO对象到imag

2024-05-16 14:02:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

但是,在第7行中(使用Image.open)出现以下错误:

OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8>

来自Pillow的文档暗示这是一条路。

我试着应用

但不能让它工作。为什么这不起作用?


Tags: 字符串ioimageimportpilopenx00identify
1条回答
网友
1楼 · 发布于 2024-05-16 14:02:19

我不确定最终的图像应该是什么样子(你有例子吗?),但如果要将每个像素有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()

相关问题 更多 >