Sunday 17 June 2018

Pi Camera stop motion animation

In preparation for a Raspberry Pi event I decided to create a simple GUI for creating stop motion animations using the Pi camera module to use for a demo.


Its a really simple application, you start it up, you click "take image", you re-position the scene, you click "take image" and so on until you are happy with your animation and you click "save" to store it as an animated gif.



You can find the source code at goo.gl/4Xvu7b.

Install
1. Connect a camera module
2. Enable the camera (Menu > Preferences > Raspberry Pi Configuration, Interfaces, Camera)
3. Open a terminal (Menu > Accessories > Terminal), install the modules and download the code:
sudo pip3 install guizero
sudo pip3 install imageio
wget -O guizero_stopmotion.py https://goo.gl/zMTjas
4. Run the program:
python3 guizero_stopmotion.py

A couple of "interesting" things about this project

The gui was created using guizero which is a super simple to use library for creating GUI's, definitely have a look.

Most of the work was finding a way to create animated gifs in Python and working with images in memory rather than stored on disk

When the image is captured from the camera it isn't stored to a file, it is stored in a numpy array, this means each frame is only stored in memory making it faster:
# create the camera
camera = PiCamera(resolution="640x480")
camera_output = PiRGBArray(camera)
...
# capture the image
camera.capture(camera_output, "rgb")
# append the camera image to the list as a numpy array
animation.images.append(camera_output.array)
The python module imageio is used to create the gif by passing the frames as a list, but again rather than being written to disk each time it is created as an in memory BytesIO stream:
gif_output = BytesIO()
imageio.mimsave(gif_output, animation.images, format="gif")
When the animated gif is displayed in guizero the BytesIO stream has to be open into a PIL Image.
animation.image = Image.open(gif_output)


2 comments:

  1. That is amazing, my grad 5 class will use this for a stop motion we are looking to create. A quick question, is it possible to create an .obj or .stl from Minecraft Pi. I noticed it is possible https://support.playpiper.com/hc/en-us/articles/115002425947-3D-Printing-from-Story-Mode just wondering if you might know a way to do it without installing piper?

    ReplyDelete
  2. When I try to play the gif with the Raspian image viewer, it seems to only be showing the first couple of frames. Is there a better way to view the stored animation?

    ReplyDelete

Note: only a member of this blog may post a comment.