当摄像机断开连接而不是返回

当摄像机断开连接而不是返回

本文介绍了当摄像机断开连接而不是返回"False"时,opencv videocapture挂起/冻结.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OpenCV-Python 3.1,遵循此处的示例代码: http://opencv-python-tutroals.readthedocs .io/zh-CN/latest/py_tutorials/py_gui/py_video_display/py_video_display.html 并使用http摄像机流而不是默认摄像机,videocapture中的读取功能在以下情况下永远不会返回"False"(或类似的任何值)摄像头实际上已断开连接,因此完全挂起/冻结了该程序.有人知道如何解决这个问题吗?

I'm using OpenCV-Python 3.1 Following the example code from here:http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html and using a http camera stream instead of the default camera, the read function in videocapture never returns "False" (or anything for that matter) when the camera is physically disconnected, thus hanging/freezing the program entirely. Does anyone know how to fix this?

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的调用.

I'm experiencing the same issue with the webcam of my MacBook, when the lid is closed (i.e. cam not available). After a quick look at the doc, the VideoCapture constructor doesn't seem to have any timeout parameter. So the solution has to involve forcibly interrupting this call from Python.

在对Python的asyncio然后是threading进行了更多的阅读之后,我无法提供有关如何中断解释器外部繁忙方法的任何线索.因此,我求助于每个VideoCapture调用创建一个守护程序,然后让它们自行死亡.

After yet more readings about Python's asyncio then threading in general, I couldn't come up with any clue on how to interrupt a method which is busy outside the interpreter. So I resorted to creating a daemon per VideoCapture call, and let them die on their own.

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

如果有人有更好的选择,我会全力以赴.

If anyone has better, I'm all ears.

这篇关于当摄像机断开连接而不是返回"False"时,opencv videocapture挂起/冻结.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 17:32