Wednesday, March 11, 2009

Capturing an image from a webcam using Python

It is amazingly simple to do this. All you need is the VideoCapture library for python and Python Imaging Library (PIL).

The VideoCapture library wraps the interactions between Python and the webcam or any other camera (not sure if this works against other imaging devices like scanners). It is a very simple-to-use library. You can download the VideoCapture library from here.

Python Imaging Library (PIL) is the standard python library for image manipulations. The VideoCapture library returns the captured image as an Image object as represented by PIL so it can be used across many other modules of python just like any other image. Download PIL here.

The following is a simple example app. It captures an image from the webcam and converts it into grayscale and shows it to the user.

import VideoCapture as VC
from PIL import Image
from PIL import ImageOps
import time

def capture_image():
cam = VC.Device() # initialize the webcam
img = cam.getImage() # in my testing the first getImage stays black.
time.sleep(1) # give sometime for the device to come up
img = cam.getImage() # capture the current image
del cam # no longer need the cam. uninitialize
return img

if __name__=="__main__":
img = capture_image()

# use ImageOps to convert to grayscale.
# show() saves the image to disk and opens the image.
# you can also take a look at Image.save() method to write image to disk.
ImageOps.grayscale(img).show()

Simple, isn't it?

No comments:

Post a Comment