【问题标题】:How do I access my webcam in Python?如何在 Python 中访问我的网络摄像头?
【发布时间】:2010-10-10 22:10:28
【问题描述】:

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

我尝试使用 VideoCapture 扩展 (tutorial),但这对我来说效果不佳,我不得不解决一些问题,例如分辨率 >320x230 时它有点慢,有时它会返回None 不明原因。

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

【问题讨论】:

标签: python webcam


【解决方案1】:

OpenCV 支持从网络摄像头获取数据,并且默认带有 Python 包装器,您还需要安装 numpy 才能使 OpenCV Python 扩展(称为 cv2)工作。 截至 2019 年,您可以使用 pip 安装这两个库: pip install numpy pip install opencv-python

More information on using OpenCV with Python.

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

【讨论】:

  • 如果从 wheel 安装,则支持 Python 3。我成功使用了本教程:solarianprogrammer.com/2016/09/17/…
  • 您还必须释放相机,否则即使窗口关闭也会打开:vc.release()
【解决方案2】:

gstreamer 可以处理网络摄像头输入。如果我没记错的话,它有 python 绑定!

【讨论】:

  • padsp streamer -q -c /dev/video0 -f rgb24 -F stereo -r 24 -s 1280x720 -t 00:10 -o test.avi 将以 24 fps 录制 10 秒的高清网络摄像头,并将其保存为 test.avi。 (请注意,padsp 仅用于确保在较新的 Ubuntu 版本下捕获音频。)
【解决方案3】:
import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0

cv.waitKey(20) & 0xFF==ord('d')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多