Wednesday 15 May 2019

USB Webcam using a Raspberry Pi and Python - test

Introduction

USB webcams are very cheap, and in many cases you may already own one. Though the Official Raspberry Pi Camera is often far superior (many "High Resolution" webcams are 'Nineties era VGA resolution - 640x480), the fact that webcams are cheap and cased can make them very useful for some projects.

This posting covers the simplest of Python programs to take a photograph using the OpenCV library.

Installation

Install OpenCV

sudo apt-get install python-opencv libopencv-dev

You might find it is already installed.

Install Python bindings

Remember that pip probably installs for Python 2.x, so you will need to use pip3.

sudo pip3 install opencv-python

Please note that if you forget the sudo, you do not get an error, but it also does not work (you get an error "ImportError: No module named 'cv2'").

Taking a photograph

The following Python code takes a photograph and saves it to a file in the (pi) user's home directory.

The program takes a number of frames to allow the camera and its software to determine the best settings for exposure etc.

# Test USB web cam with OpenCV

# Imports
import cv2

# Set camera to be the default webcam
camera_port=0

# Set warm up number of frames
skip_frames=7

# Destination file
file="/home/pi/image.jpg"

# Set up camera properties
camera=cv2.VideoCapture(camera_port)
camera.set(cv2.CAP_PROP_FRAME_WIDTH,640) 
camera.set(cv2.CAP_PROP_FRAME_HEIGHT,480)

# Function to get image
def get_image():
    retval,im=camera.read()
    return im

# Test USB web cam
print("Starting photograph")

# Skip frames to allow camera to settle down
for skipping in range(skip_frames):
    temp=get_image()
print("Taking photograph")

camera_capture=get_image()

# Write image to file
cv2.imwrite(file,camera_capture)

# Remove camera object - ensures release of resources
del(camera)

print("Done")