【问题标题】:Why can't I capture with my webcam more than once with OpenCV in Python?为什么我不能用我的网络摄像头在 Python 中使用 OpenCV 多次捕获?
【发布时间】:2020-07-23 12:59:04
【问题描述】:

我尝试编写一个小型 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

我做错了什么?

【问题讨论】:

  • 因为你在读完第一帧之后就明确地release了。
  • @DanMašek 谢谢,我将 cap.release() 移到循环之外并将它放在最后并且它起作用了

标签: python file opencv image-processing webcam


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多