Rodrigo Rodrigo - 2 years ago 169
Python Question

How do I access my webcam in Python?

I would like to access my webcam from Python.

I tried using the VideoCapture extension (tutorial), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns

for no apparent reason.

Is there a better way to access my webcam from Python?

Answer Source

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work.
At the time of writing (January 2015) there is no Python 3 support yet, so you need to use Python 2.

More information on using OpenCV with Python.

An example copied from Displaying webcam feed using opencv and python:

import cv2

vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame =
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame =
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download