python - 为什么我不能在 Python 中使用 OpenCV 多次使用我的网络摄像头进行捕获?
问题描述
我尝试编写一个小型 Python 程序,它可以让我启动网络摄像头并捕获图像并将其保存到 .png 文件中:
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
cap.release()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)
但是当我执行它时,它只会将图像保存一次0image.png
,然后在控制台中显示:
Webcam not working
False
Webcam not working
False
我究竟做错了什么?
解决方案
cap.release() 函数可以帮助您释放系统,即相机设备资源,如果不这样做,如果您尝试创建新实例,它将引发设备或资源繁忙等错误。因此,您需要从循环中删除 cap.release() 并将其放在程序的末尾。这应该工作。
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)`
cap.release()
推荐阅读
- python - 通过平均对 Python 中的 numpy 图像数组进行下采样
- reactjs - 为什么我不能将响应数据传递给 redux 存储
- c++ - 用于测试目标的具有不同源文件夹的 Makefile
- python - 我正在尝试用python制作游戏,首先让角色移动,但我一直收到同样的错误
- sql - SQL Server 2019 数据库中 ID、文件组和文件的命名约定
- c++ - 为什么这个 lambda 模棱两可?
- ssas - 为什么要使用 Process Data 与 Process Full 来处理分区
- assembly - 为什么 lw 和 sw 的 ALU 操作码是 00?
- python - Python 中的容器转换函数有多贵?
- c - 为什么在 c 中打印字符串数组不提供相同的输出?