RTSP拉流简易py脚本

使用需要更换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 = ("rtsp://****:******2024@192.168.1.***:***/Streaming/Channels/101")

    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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值