如何使用 Python 访问我的摄像头?

我想从 Python 访问我的网络摄像头。

我尝试使用 视频捕捉扩展(教程) ,但是效果不是很好,我不得不解决一些问题,比如分辨率大于320x230的时候速度有点慢,有时候它无缘无故返回 None

有没有更好的方法从 Python 访问我的摄像头?

214949 次浏览

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

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")