Build an image auto-uploader for the Raspberry Pi
Gain access to your images anywhere by combining the Pi Camera, Dropbox and Python code
Your phone can automatically upload pictures to the cloud, so why not the Pi Camera? Learn how to build and code a Dropbox-enabled solution in Python
The Pi Camera Module v2 is a small 8Mp camera board that attaches to your Raspberry Pi. Combine this with the new Pi Zero W board – which has onboard Wi-Fi – a button and the official Raspberry Pi case, and you can build a simple ‘point-and-shoot’ camera.
The issue is, how do access your images? You could plug a monitor into the Pi, use a mouse and keyboard and find the folder with your images in. Or you could SSH in and transfer the images. But a better solution would be to automatically upload each image to your online Dropbox account, so that you can access your images anywhere and share them with your friends and family.
In this tutorial we will set up and configure a Pi Camera. Then we’ll write a simple program to test that the Camera is functioning correctly. Next, we’ll walk you through creating a Dropbox App and setting up the authentication token which enables you to access your account using Python code.
In the final section, we’ll combine the PiCamera and Dropbox programs with GPIO Zero to facilitate image capture and upload via the touch of a button.
01 Setting up the Camera Module
Depending on where you purchased your Camera Module from, this first part may have already be done. Begin by connecting the ribbon cable to the Camera. Pull the small plastic clasp downwards and slide the ribbon in, ensuring that the blue strip is facing you. Push the clasp up, securing the ribbon into place.
Next, locate the Pi Camera socket. You will notice that it also has a clasp similar in style to the clasp on the Pi Camera. Pull this up to open it.
Take the ribbon and place it into the socket, with the blue strip facing towards the audio jack and away from the HDMI socket. Gently push the clasp back down to secure the ribbon into place. Make sure everything is firmly connected.
02 Enabling the Camera Module
The official Raspberry Pi OS comes preinstalled with the Camera Module software, with a Python package for interfacing with the camera. However, in the future you may need to reinstall or update the package when newer versions are released. Add the power supply to the Pi and then open the LXTerminal. Type sudo apt-get update then sudo apt-get install pythonpicamera python3-picamera. You can upgrade next time using sudo apt-get update and then sudo apt-get upgrade. By default, the Pi Camera is turned off, which of course means you can’t use it. In the LXTerminal window type sudo raspi-config to open the configuration tool. Select choice 5, ‘Interfacing Options’, and enable the camera. Use the arrow keys to select exit and restart your Raspberry Pi.
03 Testing the Camera
Next, use the simple test program that displays the camera’s view on your monitor for 10 seconds. If you can see the preview, it confirms that the hardware and software are working correctly. If not, check that the cable is attached correctly to the camera and Raspberry Pi. Also check that the camera is enabled in the configuration settings. Open your Python 3 editor and enter the program below. Then press F5 to save and execute the program.
from picamera import PiCamera from time import sleep camera = PiCamera()
camera.start_preview() sleep(10) camera.stop_preview()
04 Sign up to Dropbox
If you already have a Dropbox account, you can skip this step. Otherwise open the web browser on the Pi and go to www.dropbox.com. Select the ‘Create an account’ option and then follow the steps to set up your Dropbox account. If you prefer, you can sign up using your Google account details.
05 Creating an app, part 1
Once you have a Dropbox account go to www.dropbox.com/developers/apps. You will be presented with a number of options down the left side of the page. The first entry references the API version number, then there’s an entry called ‘My Apps’. Select this option to be taken to your Apps page. If you have not previously created an App, this page will be blank. Select and click the blue ‘Create app’ button which appears at the top right of the page.
06 Creating an app, part 2
On this page you will be presented with further options. First select the ‘Dropbox API’ option which is free for personal use. Next you need to select the type of access that the app requires. For this project select ‘App folder’ access. This gives access to a folder on your Raspberry Pi which you will use to store the images you take with the Camera. The final part is naming the app, so call it something like ‘image upload’. Finally, you’ll have to agree to the Dropbox terms and conditions of use.
07 Creating an app, part 3
On the next page you will be presented with several configuration settings for your app. On the top line keep the status of the app set to Development, and ‘Development users’ to ‘Only you’. You can also edit the app folder name to match the name you used in the previous step. Below these you’ll find your app key and app secret, although for this project you do not require these. Instead, locate the ‘Generated access token’ towards the bottom of the page and if not present, click the button to generate one. This token is important and you will need to use it in your Python program, so make a note of it.
08 Install Dropbox for Python
Now that you have an authenticated Dropbox app, the next step is to install the Python Dropbox library to enable access to your app and online folder from the Python program. Open the LX terminal and type sudo pip3 install dropbox to install the required software. At some stage in the future Dropbox will probably upgrade its software and release new features. To upgrade the software at a later date simply type sudo pip3 install dropbox –upgrade to ensure that the newest update is installed.
09 Upload an image, part 1
In this step, we’ll test that the app configuration is correct by uploading an image file to Dropbox. First locate and save a suitable image to your Pi; in this tutorial the file is named lud.jpg. Open your Python 3 editor and type in the simple program below. We begin by importing the dropbox module, line one, and then assign your Dropbox authentication code to the token variable, line two. Enable authorisation on line three.
import dropbox token = "xxxxxx" dbx = dropbox.Dropbox(token)
10 Upload an image, part 2
Next we open the image file, line one. Note that the full file address is used. rb indicates that we want to read the file as binary, since it contains no text strings or characters. On line two, we read the contents of the open file and upload it. The /lud.jpg on this line is the file name that will appear in the Dropbox folder. The option mute = True results in the user not receiving a notification of the upload. Lastly, add a quick print statement to confirm the upload. Press F5 to save and run the program. Check your Dropbox account and the image will be stored there.
with open("/home/pi/lud.jpg", "rb") as f:
dbx.files_upload(f.read(), '/lud.jpg', mute = True)
11 Live image capture and upload
As with the test program in the previous steps, begin by importing the dropbox module and then the time module so that you can add a short pause to the program code. Import PiCamera and pause to enable the program to loop. On line four, we import Button and then set up a global variable named Image_Number. This is used to store the image number, and on the next line we initially set this file number to zero. Finally, you’ll need to assign the button to GPIO 2 and then set the PiCamera object to camera.
import dropbox from time import sleep from picamera import PiCamera from signal import pause from gpiozero import Button global Image_Number Image_Number = 0 button = Button(2) camera = PiCamera()
12 Create a function
The function controls the image capture and upload. Start by naming the function, line one, and then add the global Image_Number variable, line two. On line three, increment the variable by one; this ensures that the file name for each image will be unique and will upload without overwriting the previous files. Combine the string image with the Image_Number value and .jpg to create the file name for each image taken. This results in files being named image1.jpg, image2.jpg, image3.jpg and so on. The final line adds the file name to the pic variable which is used later to upload the image file.
def Capture_and_Upload(): global Image_Number
Image_Number = Image_Number + 1
camera.capture("image" + str(Image_
Number) + ".jpg")
pic = ("image" + str(Image_Number) + ".jpg")
13 Access Dropbox
As with the test program in Step 9, we need to access Dropbox via your token, which is added on line two (replacing xxxxxx) and used on line three.
On line one, insert a try and except feature; this stops the program crashing if, say, the Pi is not online and cannot upload the file. On line four, a quick message lets you know that the program is ready to upload the image file. The final line opens the file location and then the image file, as binary data. Note that this uses the pic variable from the previous step, which contains our constructed file name.
token = "xxxxxx" dbx = dropbox.Dropbox(token) print ("ready") with open("/home/pi/" + pic, "rb")
14 Upload the image file
Now that the image file has been read it is ready for uploading to Dropbox. Use the function dbx. files_upload() and add the image file, followed by the file name. If you want a notification each time a file is uploaded, change mute = True to False. After the upload notify the user, line two, and then close the image file, line three. The delay is optional but works well for eliminating accidental double-presses of the button.
dbx.files_upload(f.read(), '/ image%s.jpg' %(Image_Number), mute = True) print ("uploaded") f.close() sleep(5)
15 Add the except
On the first line add the except condition that runs if it is not possible to upload the image file to Dropbox. The program passes the step, line two, and then prints a message to let you know that the upload has failed, line three. The image is still stored on your Pi, so you can access it later.
Line four uses the GPIO Zero function button. when_pressed to check for the button being pressed. If it is, then the function created in Step 12 Capture_and_ Upload() is run. Add the final line pause() which ensures that the program loops and waits again for the button to be pressed. Save your program code.
except: pass print("failed")
button.when_pressed = Capture_and_Upload pause()
16 Adding the button
The final part of the setup is to add a physical button which triggers the program to take an image and upload it. If you don’t have a button you can still use jumper wires by touching them together. Attach the first wire to pin GPIO 02 and the other pin to one of the GND pins. This creates the circuit.
Now run the program and press the button to take the picture. If Dropbox already contains a file with the same name, the program will not upload the file and you will get the message “failed”. We’ll leave it up to you to tidy up the error-handling and maybe add in some new functions to make the whole thing a bit friendlier.
The Camera Module software is nifty and can be used to manipulate the image. You could add Instagram-style filters to your pictures before you upload them. In the main program (Step 12), locate the line with camera.capture(). On the previous line add the following code: camera.image_effect = 'emboss'. This will add a simple emboss filter to the image. There are several to choose from and experiment with. How about ‘watercolor’, ‘oilpaint’, ‘hatch’, ‘pastel’, ‘film’, ‘blur’, ‘colorswap’, ‘washedout’ or the classic ‘cartoon’?
Above You could put the Pi in a smart camera-ready case