我正在使用 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 的 asynciothreading 之后,我想不出任何关于如何中断解释器外忙碌的方法的线索。所以我诉诸于为每个 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))

如果有人有更好的,我全神贯注。

关于python - 当相机断开连接而不是返回 "False"时,opencv videocapture 挂起/卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38234407/

10-11 02:22
查看更多