Raspberry Pi Camera Test

First we import the libraries we need and initialize a camera 'object.'


In [1]:
import os
from picamera import PiCamera
from picamera.color import Color
from time import sleep

camera = PiCamera()

In [2]:
camera.start_preview()
sleep(3)
camera.stop_preview()

TADA ... wait, nothing happened.


In [3]:
camera.hflip = True

In [4]:
camera.vflip = True

In [5]:
camera.brightness = 50 # the default is 50, but you can set it to whatever.

How about some text on the image.


In [6]:
camera.annotate_foreground = Color(1.0,1.0,0.5)

In [7]:
camera.annotate_text = "STEM Camp ROCKS!"
camera.annotate_text_size = 36

In [8]:
camera.start_preview()
sleep(1)
camera.capture('./img/image_test.jpg')
camera.stop_preview()

How about taking several shots...


In [9]:
camera.start_preview()
for i in range(5):
    sleep(3)
    camera.capture('./img/image%s.jpg' % i)
camera.stop_preview()

What about video?


In [14]:
camera.resolution = (1280, 720)
camera.start_preview()
camera.start_recording('img/videotest.h264')
camera.wait_recording(3)
camera.stop_recording()
camera.stop_preview()

This did generate a file, but the default format isn't playable through the browser, so... Note: this did require the installation of gpac with:

sudo apt-get install -y gpac


In [15]:
# convert the video above to something playable through the browser, then delete the original unplayable version.
msg = os.system("MP4Box -fps 30 -add img/videotest.h264 img/videotest2.mp4")
os.remove("img/videotest.h264")
print msg


0

Now let's add a calculated annotation to the recording (a timestamp)


In [17]:
import datetime as dt

In [20]:
camera.resolution = (1280, 720)
camera.framerate = 24
camera.start_preview()
camera.annotate_background = Color('black')
camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
camera.start_recording('img/timestamped2.h264')
start = dt.datetime.now()
while (dt.datetime.now() - start).seconds < 5:
    camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    camera.wait_recording(0.2)
camera.stop_recording()

In [21]:
# convert the video above to something playable through the browser, then delete the original unplayable version.
msg = os.system("MP4Box -fps 30 -add img/timestamped2.h264 img/timestamped2.mp4")
os.remove("img/timestamped2.h264")

When we're all finished with the camera module, it's a good idea to close the object to prevent GPU memory leakage.


In [22]:
camera.close()

In [23]:
del camera

In [ ]: