OpenCV-Python:如何从实时视频流中获取最新帧或跳过旧帧 [英] OpenCV-Python: How to get latest frame from the live video stream or skip old ones

查看:140
本文介绍了OpenCV-Python:如何从实时视频流中获取最新帧或跳过旧帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Python 中集成了一个带有 OpenCV 的 IP 摄像头,以便从实时流中逐帧完成视频处理.我已将相机 FPS 配置为 1 秒,以便我可以在缓冲区中每秒处理 1 帧,但我的算法需要 4 秒来处理每一帧,导致缓冲区中未处理的帧停滞,随着时间和时间不断增长;导致指数延迟.为了解决这个问题,我又创建了一个线程,我在其中调用 cv2.grab() API 来清理缓冲区,它在每次调用中将指针移向最新帧.在主线程中,我正在调用retrieve() 方法,该方法为我提供了第一个线程抓取的最后一帧.通过这种设计,帧停滞问题得到解决并去除了指数延迟,但仍然无法去除 12-13 秒的恒定延迟.我怀疑当 cv2.retrieve() 被调用时,它没有得到最新的帧,而是从最新帧的第 4 或第 5 帧.OpenCV 中是否有任何 API 或任何其他设计模式可以解决此问题,以便我可以获取要处理的最新帧.

I've integrated an IP camera with OpenCV in Python to get the video processing done frame by frame from the live stream. I've configured camera FPS as 1 second so that I can get 1 frame per second in the buffer to process, but my algorithm takes 4 seconds to process each frame, causing stagnation of unprocessed frame in the buffer, that keeps growing by time & causing exponentially delay. To sort this out, I have created one more Thread where I'm calling cv2.grab() API to clean the buffer, it moves pointer towards latest frame in each call. In main Thread, I'm calling retrieve() method which gives me the last frame grabbed by the first Thread. By this design, frame stagnation problem is fixed and exponential delay is removed, but still constant delay of 12-13 seconds could not be removed. I suspect when cv2.retrieve() is called its not getting the latest frame, but the 4th or 5th frame from the latest frame. Is there any API in OpenCV or any other design pattern to get this problem fixed so that I can get the latest frame to process.

推荐答案

如果您不介意在速度上妥协.您可以创建一个 python 生成器来打开相机并返回帧.

If you don't mind compromising on speed. you can create a python generator which opens camera and returns frame.

def ReadCamera(Camera):
    while True:
        cap = cv2.VideoCapture(Camera)
        (grabbed, frame) = cap.read()
        if grabbed == True:
            yield frame

现在当你想要处理框架时.

Now when you want to process the frame.

for frame in ReadCamera(Camera):
      .....

这很好用.除了打开和关闭相机会加起来.

This works perfectly fine. except opening and closing camera will add up to time.

这篇关于OpenCV-Python:如何从实时视频流中获取最新帧或跳过旧帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆