Python多进程读取多个RTSP视频流并显示

import cv2
import time
import multiprocessing as mp

# RTSP视频流地址
rtsp_url = "rtsp://192.168.1.6:8554/video"

def recovery_stream(cap,rtsp_url,retry_delay=10):
    while True:
        try:
            print(f"正在重新连接RTSP流:{rtsp_url}...")
            cap.release()
            cap = cv2.VideoCapture(rtsp_url)
            if cap.isOpened():
                print(f"RTSP流恢复成功:{rtsp_url}")
                return cap
        except Exception as e:
            print(f"尝试恢复RTSP流时遇到错误:{e}")
        time.sleep(retry_delay) # 等待10秒

def image_put(q,rtsp_url):
    # 创建VideoCapture对象,指定RTSP流地址
    cap = cv2.VideoCapture(rtsp_url)
    fps = cap.get(cv2.CAP_PROP_FPS)
    print("FPS:", fps)
    if not cap.isOpened():
        print(f"无法打开RTSP流:{rtsp_url}")
        cap = recovery_stream(cap,rtsp_url,retry_delay=10)

    while True:
        ret, frame = cap.read()
        if not ret:
            cap = recovery_stream(cap,rtsp_url,retry_delay=10)
            ret,frame = cap.read()

        while q.qsize() > 1:
            try:
                _ = q.get_nowait()
            except Exception as e:
                pass

        q.put(frame)
        # time.sleep(1/fps)
        time.sleep(0.01)

def image_get(q, rtsp_url):
    windowname = rtsp_url
    cv2.namedWindow(windowname)
    while True:
        frame = q.get(block=True)
        resized_frame = cv2.resize(frame, (640, 480))
        cv2.imshow(windowname, resized_frame)
        # 按'q'键退出循环
        cv2.waitKey(1)

def run_multi_camera(rtsp_urls):
    mp.set_start_method('spawn')
    queues = [mp.Queue(maxsize=2) for _ in rtsp_urls]

    processes = []

    for queue,rtsp_url in zip(queues,rtsp_urls):
        processes.append(mp.Process(target=image_put, args=(queue,rtsp_url)))
        processes.append(mp.Process(target=image_get, args=(queue,rtsp_url)))

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()

if __name__ == '__main__':
    rtsp_urls = [
        "rtsp://192.168.1.6:8554/video",
        # "rtsp://192.168.1.6:8554/video",
    ]
    run_multi_camera(rtsp_urls)
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Goafan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值