0

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!

1 Answers1

1

The problem is simple but I am wondering why the io library works that way. One simply needs to seek back the stream to 0 after truncating it or seek to 0 and then simply call truncate with no parameter (all after you are done opening the image). Like so:

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

Basically when you open the image and do some operation on it, the pointer of the BytesIO can move around and end up somewhere else than the zero position. After that when you call truncate(0) it does not move the pointer back to zero as I thought it would (seems logical to me to move the pointer back to where the truncation occurs). When to code runs once more, the capture writes in the stream but this time it does not start writing at the beginning and everything breaks after that.

Hope this can help someone in the future :)