如何在 Python 中使用 OpenCV 拍摄网络摄像头照片
此代码打开 /dev/video0 并拍摄单张照片,之后关闭设备:
capture_webcam.py
import cv2
video_capture = cv2.VideoCapture(0)
# 检查成功
if not video_capture.isOpened():
raise Exception("Could not open video device")
# 读取图片。成功时 ret === True
ret, frame = video_capture.read()
# 关闭设备
video_capture.release()你也可以使用 cv2.VideoCapture("/dev/video0"),但此方法依赖于平台。cv2.VideoCapture(0) 也将在非 Linux 平台上打开第一个视频设备。
在 Jupyter 中你可以使用以下代码显示图片
display_webcam_jupyter.py
import sys
from matplotlib import pyplot as plt
frameRGB = frame[:,:,::-1] # BGR => RGB
plt.imshow(frameRGB)If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow