BytesIO对象转换为图像

6

我正在尝试在我的程序中使用Pillow将从相机获取的字节字符串保存到文件中。这是一个例子,使用来自相机的小型原始字节字符串,应该代表一个分辨率为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文档中给出的解决方法并不能解决问题。您可以尝试以下链接的解决方案,但是可能无法解决问题:为什么这个方法不能起作用呢?请帮忙检查一下。
1个回答

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

谢谢您的提示!在我的情况下,输出是Windows WORD类型(因此为16位小端无符号整数)。最终,在查看解码器描述后,我能够正确地解码我的图像:Image.frombuffer("F", (10, 5), rawbytes, "raw", "F;16") - smiddy84
我很高兴frombuffer()函数为您提供了所需的功能,并且我的建议让您走上了正确的轨道。不过,我确实不得不深入研究pillow源代码才找到这个解决方案;-) - Michiel Overtoom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接