Alv*_*n C 4 c++ python video camera opencv
我正在使用 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 中的 read 函数永远不会返回“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()
Run Code Online (Sandbox Code Playgroud)
当盖子合上时,我的 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))
Run Code Online (Sandbox Code Playgroud)
如果有人有更好的,我全神贯注。
| 归档时间: |
|
| 查看次数: |
3840 次 |
| 最近记录: |