picamera saving duplicate pictures in BytesIO stream

699 views Asked by At

So the idea here is very simple. I want to take and save pictures from the raspberry pi camera through a BytesIO stream and PIL, so that I can draw onto the image before saving it. The code below is simple, however after the program has completed the 10 pictures, all the pictures that are saved are identical.

I'm sure there's an easier way to doing this, but I want to use a BytesIO stream in an attempt to learn more about it.

import picamera, io
from PIL import Image

camera = picamera.PiCamera()
camera.resolution = (1920, 1080)
camera.color_effects = (128, 128)
stream = io.BytesIO()

for n in range(10):
    camera.capture(stream, "jpeg", use_video_port=True)
    stream.seek(0)
    im = Image.open(stream)
    im.save(str(n)+".jpg")
    print n
stream.close()

Any help would be appreciated, Nik

1

There are 1 answers

0
BlackJack On

The problem with your code is not seeking to the start of the in-memory file object before each capture or after reading the captured image. But using io.BytesIO and PIL.Image is unnecessarily complicated anyway. You can capture directly to a file:

#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, division, print_function
import picamera


def main():
    with picamera.PiCamera() as camera:
        camera.resolution = (1920, 1080)
        camera.color_effects = (128, 128)

        for n in range(10):
            camera.capture('{0:04d}.jpg'.format(n), use_video_port=True)
            print(n)


if __name__ == '__main__':
    main()

Here I have used the PiCamera object in a with statement to ensure this resource is properly closed/released when we are done with the camera.