【问题标题】:BytesIO object to imageBytesIO 对象到图像
【发布时间】:2015-11-19 10:18:49
【问题描述】:

我正在尝试在我的程序中使用 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 的文档暗示这是要走的路。

我尝试应用来自

的解决方案

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

【问题讨论】:

    标签: python python-3.x io python-imaging-library


    【解决方案1】:

    我不确定生成的图像应该是什么样子(您有示例吗?),但是如果您想将每个像素有 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 位小端无符号整数)。最后,看看decoder description,我能够正确解码我的图像:Image.frombuffer("F", (10, 5), rawbytes, "raw", "F;16")
    • 我很高兴 frombuffer() 函数为您完成了您所需要的工作,并且我的建议使您走上了正轨。但是,我确实必须深入研究枕头源代码才能找到此解决方案;-)
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多