首页 > 解决方案 > Cannot identify image file io.BytesIO on raspberry Pi using PiCamera library and PIL

问题描述

I am having trouble using the output from PiCamera capture function (directed in a BytesIO stream) and opening it using the PIL library. Here is the code (based on the PiCamera basic examples):

#Camera stuff
camera = PiCamera()
camera.resolution = (640, 480)
stream = io.BytesIO()
sleep(2)

try:
    for frame in camera.capture_continuous(stream, format = "jpeg", use_video_port = True):
        frame.seek(0)
        image = Image.open(frame) //THIS IS WHERE IS CRASHES
        #OTHER STUFF THAT IS NON IMPORTANT GOES HERE
        frame.truncate(0)
finally:
    camera.close()
    stream.close()

The error is : PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0xaa01cf00>

Any help would be greatly appreciated :)

Have a nice day!

标签: raspberry-pipython-imaging-librarybytesiopicamera

解决方案


问题很简单,但我想知道为什么 io 库会这样工作。只需要在截断流后将流返回到 0 或搜索到 0,然后简单地调用不带参数的 truncate (所有在你完成打开图像之后)。像这样:

for frame in camera.capture_continuous(stream, format = "jpeg", use_video_port = True):
    stream.seek(0)
    image = Image.open(stream)
    #Do stuff with image
    stream.seek(0)
    stream.truncate()

基本上,当您打开图像并对其进行一些操作时,BytesIO 的指针可以四处移动并最终到达零位置以外的其他位置。之后,当您调用 truncate(0) 时,它不会像我想的那样将指针移回零(对我来说,将指针移回发生截断的位置似乎是合乎逻辑的)。当代码再次运行时,捕获写入流中,但这次它没有从头开始写入,之后一切都中断了。

希望这可以帮助将来的人:)


推荐阅读