首页 > 解决方案 > 为什么我不能在 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

我究竟做错了什么?

标签: pythonfileopencvimage-processingwebcam

解决方案


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


推荐阅读