89

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?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Rodrigo
  • 5,938
  • 6
  • 31
  • 39
  • Please clarify which operating systems you need to support. – Johan Dahlin Mar 03 '09 at 03:04
  • See also: [Python library for taking camera images](http://softwarerecs.stackexchange.com/q/18134/1834) – Martin Thoma Apr 28 '16 at 10:09
  • And: [Why are webcam images taken with Python so dark?](http://stackoverflow.com/q/28566972/562769) – Martin Thoma Apr 28 '16 at 10:10
  • John Montgomery's, 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. – Robert May 19 '16 at 14:16

2 Answers2

110

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

vc.release()
cv2.destroyWindow("preview")
Trang Oul
  • 134
  • 1
  • 8
John Montgomery
  • 8,868
  • 4
  • 33
  • 43
  • 2
    There is Python 3 support if you install from wheel. I used this tutorial successfully: https://www.solarianprogrammer.com/2016/09/17/install-opencv-3-with-python-3-on-windows/ – Toke Faurby Apr 19 '17 at 05:43
  • 4
    You have also to release the camera otherwise will be open even if the window is closed: vc.release() – G M Apr 30 '20 at 14:24
4

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

Kknd
  • 3,033
  • 26
  • 29
  • 3
    `padsp streamer -q -c /dev/video0 -f rgb24 -F stereo -r 24 -s 1280x720 -t 00:10 -o test.avi` will record 10 seconds of an HD webcam with 24 fps and save it as *test.avi*. (Notice that padsp is just used to ensure that audio is captured under the newer Ubuntu versions.) – Pithikos Oct 15 '15 at 17:50