我正在使用 OpenCV-Python 3.1,遵循此处的示例代码:http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html 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
then 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))
如果有人有更好的,我洗耳恭听。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)