Tuesday 6 February 2018

Sample code to capture .bmp images from the Raspberry Pi Module

Here is a short sample Python 3 program to control a Raspberry Pi camera module and capture a specified number of named .bmp images to a folder. It also allows the camera to be set to capture mono or colour images.
It makes use of the PiCamera Class which provides a pure Python interface to the Raspberry Pi camera modules.

The program (Could be saved as 'Capture.py' for exmple.)

# Pi Camera Capture Demo Program
# by Steve Wainwright
import picamera
camera = picamera.PiCamera()
camera.resolution = (800, 600)
i=0
count = 30
num = 0
# Start preview overlay top left of screen, of size 800 x 600
camera.start_preview(alpha=255,fullscreen=False, window=(0, 0,800, 600))
# Bring the output below the overlay by printing empty lines
while i < count:
    i=i+1
    print ("")
    continue
print (" ")
print ("Commands MENU")
print ("mono = Unsaturated images")
print ("col = Colour images")
print ("cap = capture images")
print ("q = quit")
while True:
    command = input('Enter a command: ')
    if command == "mono":
        camera.saturation=-100
    elif command == "col":
        camera.saturation=0
    elif command == "cap":
        print ("Enter filename")
        fnam = input()
        print ("Enter number of images to be captured for  ",fnam)
        picno = input()
        picno = int(picno)
        print ("Capturing   ", fnam)
        for i in range(picno):
            # The path for saving must be set something like the next line
            # where images are saved to a folder on the desktop called PiImage
            camera.capture('/home/steve/Desktop/PiImage/%s_%s.bmp' % (fnam, num))
            num = num + 1
# Close camera and quit
    elif command == "q":
        camera.close()
        break

When loaded into IDLE 3 or the Thonny IDE, The code should look like this:

The program can be run from this IDLE 3 window by clicking Run and selecting Run Module as below:

Or from Thonny, the program can be run by clicking on the standard Run icon.
This will open the Python Shell and run the program.

Documentation for PiCamera can be found HERE.