OpenCV视频捕获在相机断开连接时挂起/冻结,而不是返回"False"
opencv videocapture hangs/freeze when camera disconnected instead of returning "False"
我正在使用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))
如果有人有更好的,我全听。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 伪造事实↔false
- QueryWorkingSet总是返回false
- WIN32:C++,为什么在WM_CLOSE上调用Messagebox函数程序正在冻结
- 如何区分地图中的 0 和 false?
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- Win32 发送输入鼠标移动滞后并冻结
- Arduino-C++ bool 不会从 false 变为 true
- ImGui 在单击按钮后冻结
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- QWidget UI 在使用 QQuickWidget 时冻结
- 当我的 if 条件计算结果为 false 时,我的 else 块将不会执行
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 等于在 c++ 中返回 false
- strcmp 对于相等的字符序列返回 false
- Adafruit 羽毛RFM69HCW在使用过程中会冻结,需要硬重置
- std::is_class 在引用类上为 false
- MFC/C++ ComboBox:禁用下拉列表关闭和打开(UI 冻结)的绘制
- ios_base::sync_with_stdio(false); cin.tie(NULL);
- OpenCV视频捕获在相机断开连接时挂起/冻结,而不是返回"False"