OpenCV视频捕获在相机断开连接时挂起/冻结,而不是返回"False"

opencv videocapture hangs/freeze when camera disconnected instead of returning "False"

本文关键字:冻结 False 返回 挂起 视频 相机 连接 断开 OpenCV      更新时间:2023-10-16

我正在使用OpenCV-Python 3.1 按照这里的示例代码:http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html 并使用http相机流而不是默认相机,当相机物理断开连接时,videocapture中的读取功能永远不会返回"False"(或任何与此相关的内容),从而完全挂起/冻结程序。 有谁知道如何解决这个问题?

import numpy as np
import cv2
cap = cv2.VideoCapture('http://url')
ret = True
while(ret):
    # Capture frame-by-frame
    ret, frame = cap.read()
    print(ret)
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

盖子关闭(即凸轮不可用)时,我的MacBook的网络摄像头遇到了同样的问题。快速查看文档后,VideoCapture构造函数似乎没有任何timeout参数。因此,解决方案必须涉及强制中断来自Python的调用。

在阅读了更多关于 Python asyncio然后threading的阅读之后,我无法想出任何关于如何中断解释器外繁忙的方法的线索。所以我求助于为每个VideoCapture调用创建一个守护进程,让它们自己死去。

import threading, queue
class VideoCaptureDaemon(threading.Thread):
    def __init__(self, video, result_queue):
        super().__init__()
        self.daemon = True
        self.video = video
        self.result_queue = result_queue
    def run(self):
        self.result_queue.put(cv2.VideoCapture(self.video))

def get_video_capture(video, timeout=5):
    res_queue = queue.Queue()
    VideoCaptureDaemon(video, res_queue).start()
    try:
        return res_queue.get(block=True, timeout=timeout)
    except queue.Empty:
        print('cv2.VideoCapture: could not grab input ({}). Timeout occurred after {:.2f}s'.format(video, timeout))

如果有人有更好的,我全听。