Question

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 None for no apparent reason.

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

Was it helpful?

Solution

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. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

More information on using OpenCV with Python.

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

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

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

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
cv2.destroyWindow("preview")

OTHER TIPS

This should have been a comment to @John Montgomery, but my rep does not allow me to make comments. Your answer is great, but at least on Windows, it is missing the line

vc.release()

before

cv2.destroyWindow("preview")

Without it, the camera resource is locked, and can not be captured again before the python console is killed.

gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

The only one I've used is VideoCapture, which you've already mentioned you don't like (although I had no problems with it; what bugs did you encounter?)

I was unable to find any alternatives in the past or now, so you might be stuck either using VideoCapture, or finding a nice C library and writing a Python wrapper for it (which might be more work than you're willing to put into it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top