opencv + python 实时获取视频流最新帧

该方法通过基于 cv2.VideoCapture 能够获取视频流入(rtmp/rtsp等)实时帧,能够解决由于图像处理速度不够等原因造成帧堆积的问题。

import cv2
from threading import Thread


class ThreadedCamera(object):
    def __init__(self, source=0):

        self.capture = cv2.VideoCapture(source)

        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True  # 防止主线程挂掉,子线变成程僵尸进程
        self.thread.start()

        self.status = False
        self.frame = None

    def update(self):
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def grab_frame(self):
        if self.status:
            return self.frame
        return None


if __name__ == '__main__':
    stream_link = "http://livebroadcast.ccwb.cn/live/w1627026956756903.m3u8"
    streamer = ThreadedCamera(stream_link)

    while True:
        frame = streamer.grab_frame()
        if frame is not None:
            cv2.imshow("Context", frame)
        cv2.waitKey(1)

 

posted @ 2021-08-02 09:29  牛郎  阅读(3865)  评论(0编辑  收藏  举报