How to access my webcam in Python?

I would like to access my webcam from Python.

I tried to use the VideoCapture extension ( tutorial ), but it didn’t work for me, I had to work a little on some problems, for example, a bit slow with a resolution> 320x230, and sometimes it returns None no apparent reason.

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

+53
python webcam
Mar 03 '09 at 1:11
source share
4 answers

OpenCV supports receiving data from a webcam, and by default it comes with the Python shell, you also need to install numpy so that the OpenCV Python extension cv2 (called cv2 ). Since 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

More information on using OpenCV with Python .

Example copied from showing a 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") 
+49
Mar 03 '09 at 12:09
source share

It should have been a comment on @John Montgomery, but my representative does not allow me to comment. Your answer is great, but at least on Windows there is no line

 vc.release() 

before

 cv2.destroyWindow("preview") 

Without this, the camera resource is locked and cannot be captured even before the python console is started.

+10
May 19 '16 at 14:16
source share

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

+1
Mar 03 '09 at 2:33
source share

The only thing I used was VideoCapture, which you already mentioned that you don't like (although I had no problems with this, what errors did you encounter?)

I was not able to find alternatives in the past or now, so you can either get stuck with VideoCapture or find a beautiful C library and write a Python shell for it (which may be more work than you are ready to put into it).

-2
Mar 03 '09 at 1:42
source share



All Articles