Linux Format

Picamera: Build a photo booth

Dan Frost shares a fun photograph­ic project that will help newcomers get to grips with both coding and the Raspberry Pi.

- Dan Frost is Tech Lead in edtech R&D, working on VR, blockchain, voice tech, cloud, web and more. He blogs and talks about technology at https:// thebaselin­e.co.

Dan Frost shares a fun photograph­ic project that will help newcomers get to grips with both coding and the Raspberry Pi camera module.

The Raspberry Pi camera module is a great little addition to get people into both coding and hardware. This project has been adapted from a coding club; the school had bought a few Raspberry Pis, a temperatur­e sensor and a camera. The original plan was to record a time-lapse film of plants growing and plot the temperatur­e against this. But the kids in the club were having none of that – they wanted something where they could point the camera at each other, so this is what became plan B.

The project recreates a simple photo booth which takes a photo, applies an effect to the picture and puts a frame around it. This was enough to learn about handling input from devices, storing files and using methods in a library.

This is a great little starter project for kids or adults because it does something tangible but doesn’t require a lot of new concepts to be learnt. This tutorial doesn’t assume much prior knowledge at all and tries to explain the terms as much as is practical as we go. If you get stuck at any point, you should have enough informatio­n to find meaningful help via Google. This might be useful for yourself or as the basis of lessons or coding club projects that you run.

What you’ll need

This has been tested on the Raspberry Pi v1 onwards, so you shouldn’t have trouble doing this on any of version of the Pi. If you want to be sure, just search for the camera support for your particular model.

You’ll also need a Raspberry Pi camera. If you haven’t played with this module before, all you need to know is that’s it’s much easier to set up than you might expect. The additional hardware is usually preconfigu­red for the Pi, or the Pi will support it without having to do what we did in the ‘old’ days: spend days compiling and configurin­g drivers for each new piece of hardware. The tutorial uses Python, which comes preinstall­ed on the Pi.

The advantage of using the Pi Camera is that it’s built to work with the Raspberry Pi, meaning that you don’t have to worry about device drivers (the software which lets the hardware work together). The Pi Camera also comes with a Python module so it’s easy to write code to interact with it. Before components such as the Pi Camera and computers like the Raspberry Pi were popular, it was much harder to get started using these kinds of devices, which is why they’re a really fun thing with which to get people started in coding.

Setting up the Camera

Most of the tutorial doesn’t require access to the internet, but for a first step we’re going to update the OS, which does of course require internet access. Run these commands:

sudo apt-get update sudo apt-get upgrade

Now we need to enable support for the Camera. Run the following command which will launch a commandlin­e configurat­ion tool:

sudo raspi-config

Navigate down to Camera, select Enable and then Finish. Now reboot your Raspberry Pi:

sudo reboot

Let’s test that the Camera is working. Plug in the camera by lifting up the small plastic handle on the DSI Display Connector. Plug it in, point it at something and open the command line.

cd ~/Desktop raspistill -o image.jpg

Now open image.jpg from the desktop and you should see the picture you’ve just taken.

Love, life and running Python scripts

In this tutorial, we want to focus on playing with the Raspberry Pi camera, but to save you Googling too many steps let’s give a quick introducti­on to editing and running Python scripts.

Python scripts are just text files which end in .py instead of .txt. You can edit them on the Raspberry Pi by opening any text editor and opening the file. Do this now with any text editor you’re happy with (although don’t use a fully fledged word processor, as that will probably add unnecessar­y formatting which will confuse Python).

When the file is created and saved, open up the terminal (which you can find through the menu) and navigate to where the file is stored. You can ‘execute’ (run) the file with:

python3 name-of-file.py

Now put this line into the file and execute it:

print(“hiya, world!”)

Obviously, change name-of-file.py to whatever you named the file. If you’re going to use this tutorial with newcomers to computing, I suggest you give a few challenges such as: Change the text in the file. Create another file with a different message and execute it. Google how to create a loop in Python, and put that into a new file.

Having basic control over the file and ability to execute it will, I’ve found, give most newcomers the independen­ce to solve a lot of basic problems which would otherwise frustrate them.

Starting the project

The project is going to take a picture, like you just did, and then apply a filter and add a frame. Start by creating a directory for our project; we’re going to put it on the desktop so we can get to it easily, but you can put it wherever you prefer. mkdir ~/Desktop/photobooth && cd ~/Desktop/ photobooth touch camera.py

We’ll also make a directory for the finished photos to live in:

mkdir ~/Desktop/pics/ mkdir ~/Desktop/frames/

The first version of the script will just take a picture. Add these lines to the camera.py file:

from picamera import Picamera from PIL import Image print(“starting photobooth”) camera = Picamera() camera.rotation = 180 print(“\n\nok… you have 3 seconds to get ready! Smile!\n”) camera.start_preview() sleep(3) camera.stop_preview() photo = “/home/pi/desktop/pics/snap.jpg” camera.capture(photo) print(“all done!”)

Run this with the line below and then open the picture to see what you captured. python3 camera.py

Now of course this hasn’t done much more than automate what we did with the test photo we took earlier, but it forms the basis for a script that we can use to do much more interestin­g things once we’ve got the initial picture.

If you’re new to Python or to the Picamera module, there are a few interestin­g things here to learn. camera. rotation=180 rotates the picture by 180 degrees to allow for the fact that you probably have the Raspberry Pi on your desk, and the camera ribbon curls over, so the camera ends up upside down. sleep(3) pauses the program for three seconds and then camera.capture takes a photo and puts it in the location pointed to by the photo variable. The camera module is great for learning coding because you can misspell a few words,

run the script and get errors, but the errors will be pretty self-explanator­y because, as a beginner, the correct spelling will be obvious to you. For example, change capture to capure or photo to phoo .

Create a frame

Next, let’s add a step which the Code Club children being taught really enjoyed: creating a frame for the picture and applying it in the Python script. First, find out the size of the photo you just took by opening it up from the Raspberry Pi desktop. Or you can use the command line tool file to get the informatio­n:

$ cd ~/Desktop/pics

$ file snap.jpg snap.jpg: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 663x994, frames 3

In this example our image has a resolution of 663x994, but you obviously need to use whatever your camera creates. Now create a frame by either drawing it on paper or using GIMP or another package. Make it the same size as the picture the script captured. Using

GIMP or another image editor, delete the centre of the frame and make it transparen­t. Save it as a transparen­t PNG in ~/Desktop/frames/frame1.png.

Now modify the script so that from the capture line onwards you have:

camera.capture(photo) print(“adding the frame”) bg = Image.open( photo ) fg = Image.open( “./Desktop/frames/border1.png” ) bg.paste(fg, (0,0), fg) bg.save(“/home/pi/desktop/photobooth/finished/ snap.png”) print(“done!”)

When you run this, it will create two files: 1 The photo, as you’re used to doing with the camera. 2 A photo with a frame, using a new Image class and bg.paste , which pastes one image on top of another.

This code creates the basic photobooth. Run the script again with python camera.py . Open up the frame and you should see a nicely framed picture. At this stage, you have enough to start playing around with how the script runs and how it feels for the user.

A really good habit in coding clubs, or any environmen­t where you’re teaching or learning coding, is to add extra steps, change the wording, reorganise where the files are stored and replace the frame. These small steps help you to learn the concepts by practising and playing, rather than moving right on to the next thing. Some good tasks are: Create another frame and replace it. Make the welcome message contain more lines and tell the user more of what’s going to happen. Make the variables which are used for applying the frame more meaningful.

That last idea moves into thinking about structurin­g code rather than just getting things working.

A choice of frames

It would be fun to have some kind of user input in the script so that you can let the user decide what frame to have. To do this, you will first need to create a few more frames and place them in the frames directory, named frame1.png, frame2.png and so on.

Next, add a few lines before the camera = Picamera() line: frame = input(“type the number and hit enter. \n>”) frame_id = int(frame) print(“you chose frame %i” % frame) frame_file = “./Desktop/frames/frame” + frame_id + “.png”

Then change the line Image.open to: fg = Image.open( frame_file )

Now if you run the script again, you’ll be given the option to choose your frame. If you’re running a coding club, this is a great point to get creative. Make lots of new frames and decide what order to present them in. Or add more output in the script to describe each of the frames so the user knows what they’re getting.

Another challenge is to make the script more stable by having it check that the frame file really exists. The challenge we gave the group (but it’s optional for this project) was to understand and use the following lines, which will check that the file exists and exit the program if it doesn’t. import os if not os.path.isfile(“~/path/to/file.png”): raise Exception(“file does not exist”)

As a clue, you should put the import line at the start of the file – but the rest is left for you to work out! This gets you thinking about what that code is doing and where to fit it into your program.

Adding effects

We can make the script even more fun by applying some effects which are built into the Picamera module. Start by adding the following line just after the camera. rotation line: camera.image_effect = ‘colorswap’

Run the script again. This is another point to let learners (or yourself) have a play. If you examine the documentat­ion (see ‘Read the flipping manual’ on page

87), you’ll find there are 22 effects to dabble with. Have a play with ‘sketch’, ‘negative’ and ‘watercolor’.

Just as we gave the user the ability to choose their frame, it would be nice for them to choose their effect from some of those that you’ve played with. To do this, we introduce a simple if statement.

If you’re familiar with Python, you’ll know that there’s a much more elegant way of doing this, using an array to map from numbers to effect names. The reason I chose to do it this way is to make it more readable for first time programmer­s.

First add the following just after the lines which select the frame:

effect = input(“type the number and hit enter. \n>”) effect = int(effect)

Now add a couple of if statements to select the correct effect: if(effect == 1): print(“applying effect 1”) camera.image_effect = ‘colorswap’ elif(effect == 2): print(“applying effect 2”) camera.image_effect = ‘solarize’ else:

print(“i didn’t understand that. Going ahead with no effect.“)

This piece of code first asks if the user typed 1 and then if they typed 2. For 1 , the effect is colorswap and for 2 it’s solarize . If you’re unfamiliar with this, read it through and if you’re using this to teach coding, get your students to read it through.

Then, as a challenge, add some more options. Even for beginner programmer­s, there is enough informatio­n here for them to work out how to make it function. So long as you take a backup of the file before everything goes really wrong (which you should be doing anyway!), you’ll get there eventually through experiment­ation and seeing what works. With this feature added, run the camera script again and test it out.

Setting up the photobooth

What you’ve built so far is nearly enough to be a really simple working product to show off. The way this has been used in coding clubs in my experience is to set it up as a ‘festive photobooth’ at the school’s Christmas fair – or any fair, come to that.

You can setup a table with the Raspberry Pi on and the camera pointing at a couple of chairs. You can add some fun by providing wigs, feather boas and other frippery. People can pay a donation, run the script, select the frame and the effect they’d like. This creates the picture – but maybe you want to add a second script to send it off to a printer for them to take home.

Be my play thing

We’ve only looked at a few examples of the Raspberry Pi camera module, so let’s see what else can be done.

In the example we’ve built, the user doesn’t have a chance to preview the scene before the picture is taken, as you would be able to do in a photo booth or selfie app. You could add this using the start_preview() function. If you call this, it’s going to take over the entire screen, so you’ll need to think about using sleep(x) to make it sleep for x seconds, and then use the correspond­ing stop function, stop_preview() .

If you want to be more advanced, there is an alpha option that you can pass to this function to make it partly transparen­t. Have a look at the documentat­ion for more goodies to play with.

Generate GIFS

Animated gifs are so retro and yet so now. A cool thing to do with the camera output would be to record a short video, convert it to a GIF and display it on a webpage that everyone can see.

If you did this over time – say, at a school fair – you could end up with loads of funny GIFS being played one after the other. Doing this will take a little reworking, but the core idea is to capture a video instead of a still and generate a GIF from the video.

To capture a video, use the _recording() methods,

something like this:

camera.start_recording(‘my_video.h264’) camera.wait_recording(60) camera.stop_recording()

This example is lifted directly from the documentat­ion, just to show how easy it can be to piece these things together. Next, after a few minutes of Googling ‘convert video to GIF’, you’ll find an engineerin­g article from Giphy with this line:

$ ffmpeg -ss 61.0 -t 2.5 -i input-file.mp4 -f gif input-file. gif

If you (or your students) are totally new to those commands then try them out in isolation, and work out what they do by running them. It’s really important that when learning, students learn how to try out ideas rather than just copying and pasting code – just as when learning a foreign language, you need to interact with other speakers rather than just learning the word for ‘comb’ or something.

A learning photobooth

If you’re getting pretty confident with the setup so far, here’s a project which will be a push: what if the photobooth learnt about people it had seen before, using machine learning? You could store the images of people who had used it, create a model using an open source image categorisa­tion library, and run each image taken past the model to see if the person is recognised.

There are a lot of ways of doing this now. You can use hosted services such as Amazon’s AWS, you can find libraries which will hide the details, or you can get into the nitty-gritty with something like Tensorflow.

If you have a mix of students – say some who have loads of experience and others who are newcomers – then you could set the newcomers building the photobooth as we’ve done above and the more experience­d building the machine learning model part of this. However you take it from here, there’s a lot of coding fun to be had with this simple add-on to the Raspberry Pi.

 ??  ?? The Picamera module docs are your way into understand­ing what can be done with the Raspberry Pi Camera.
The Picamera module docs are your way into understand­ing what can be done with the Raspberry Pi Camera.
 ??  ??
 ??  ?? Like the Raspberry Pi, the camera is inexpensiv­e and easy to install.
Like the Raspberry Pi, the camera is inexpensiv­e and easy to install.
 ??  ?? Enabling the camera is the only part which feels low-level, but is straightfo­rward.
Enabling the camera is the only part which feels low-level, but is straightfo­rward.
 ??  ?? Even though this might feel like a big project, there’s plenty of support available for the Picamera module online.
Even though this might feel like a big project, there’s plenty of support available for the Picamera module online.

Newspapers in English

Newspapers from Australia