opencv 十八 python下实现0缓存掉线重连的rtsp直播流播放器

使用opencv打开rtsp视频流时,会因为网络问题导致VideoCapture掉线;也会因为图像的后处理阶段耗时过长导致opencv缓冲区数据堆积,从而使程序无法及时处理最新的数据。为此对cv2.VideoCapture进行封装,实现0缓存掉线重连的rtsp直播流播放器,让程序能一直处理最新的数据。

代码实现

from collections import deque
import threading
import cv2,time
#接收摄影机串流影像,采用多线程的方式,降低缓冲区栈图帧的问题。
class VideoCapture:
    def __init__(self, URL):
        self.URL = URL
        self.isstop = False
        self.lock = threading.RLock()
        self.q=deque(maxlen=100)
        # 摄影机连接。
        self.capture = cv2.VideoCapture(self.URL)
        threading.Thread(target=self.readframe, daemon=True, args=()).start()
        print('VideoCapture started!')
        
    def release(self):
        # 记得要设计停止无限循环的开关。
        self.isstop = True
        print('VideoCapture stopped!')
   
    def read(self):
        i=0
        while len(self.q)==0 and i<100: #尽可能避免读不到数据
            time.sleep(0.005)
            i+=1
        if len(self.q)>0:
            res=self.q.pop()# 只要最新的数据
            self.q.clear()# 直接清空原先的数据
            return res
        else:
            return False,None
    
    #进行实时数据读取
    def readframe(self):
        while (not self.isstop):
            ok, frame = self.capture.read()   
            if ok:        
                self.q.append((ok, frame))
            else:
                self.capture = cv2.VideoCapture(self.URL) #掉线重连
        self.capture.release()


if __name__ == '__main__':
    path="rtmp://rtmp.rtc.qq.com/pull/19"
    cap = VideoCapture(path)
    while True:
        ok, frame = cap.read()
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if not ok:
            continue
        cv2.imshow("cam", frame)

    cap.release()
    cv2.destroyAllWindows()


使用说明

使用代码如下所示,与cv2.VideoCapture是一模一样的用法,具备0缓存,自动断线重连的特点

if __name__ == '__main__':
    path="rtmp://rtmp.rtc.qq.com/pull/19"
    cap = VideoCapture(path)
    while True:
        ok, frame = cap.read()
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if not ok:
            continue
        cv2.imshow("cam", frame)

    cap.release()
    cv2.destroyAllWindows()

与vlc相比,通过本程序读取出的视频帧实时性更高在这里插入图片描述

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摸鱼的机器猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值