如何解决如何使用多线程和 cv2.VideoCapture()?
我想显示两个或更多单独的视频,并使用 cv2 应用轻微的图像处理。
如果我不使用 threading/multiprocessing
,很多时间都浪费在使用 cv2.waitKey(timeThatCouldBeSpentFetchingAFrameForAnotherVideo)
显示帧上。
我尝试使用 threading
,但它不能正常工作。我收到此警告:WARNING: nextEventMatchingMask should only be called from the Main Thread! This will throw an exception in the future.
。这通常会导致简单的崩溃。
所以,我决定尝试实现 multiprocessing
,理论上应该比 threading
更快,处理更复杂的图像(对吗??)。 I used this as an example. 但是,在这种情况下,我遇到了另一个问题,此方法只能获取视频的第一帧。另外,我尝试将 cv2.VideoCapture() 放在 Process
之外,但结果是:TypeError: cannot pickle 'cv2.VideoCapture' object
。
这是我的代码:
class CamManager:
def __init__(self):
self.saving = Saving()
self.cams = self.createCamObjList()
self.buffers = [Buffer(cam.FPS*BUFFER_SIZE) for cam in self.cams]
def createCamObjList(self):
l = []
for i,url in enumerate(STREAM_URLS):
saved_data = self.saving.getDataFor(url)
cam = BufferedCamera(url,i,saved_data)
l.append(cam)
return l
def startStreamCapture(self):
queue_for_cams = multiprocessing.Queue()
processes = [multiprocessing.Process(
target=cam.readloop,args=[queue_for_cams]).start() for cam in self.cams]
while True:
if not queue_for_cams.empty():
from_queue = queue_for_cams.get()
self.buffers[from_queue[0]].add(from_queue[1])
class BufferedCamera():
def __init__(self,streamURL,cam_id,saved_data=None):
self.streamURL = streamURL
self.cam_id = cam_id
# get current camera's framerate
cam = cv2.VideoCapture(streamURL)
self.FPS = cam.get(5)
if self.FPS == 0:
self.FPS = 24
cam.release()
print(f"Input res: {cam.get(3)}x{cam.get(4)} | FPS: {self.FPS}")
# use that framerate to adjust the time between each iteration of mainloop
self.period = int((1.0/self.FPS)*1000)
def readloop(self,queue):
while True:
self.read(queue)
def read(self,queue):
cam = cv2.VideoCapture(self.streamURL)
_,frame = cam.read()
if frame is not None:
queue.put((self.cam_id,frame))
cv2.waitKey(self.period)
解决方法
通过在我的 multiprocessing
函数内和 readloop 之前创建 cv2.VideoCapture
对象,我让 Process
工作:
def readloop(self,queue):
cam = cv2.VideoCapture(self.streamURL)
while True:
self.read(queue,cam)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。