You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python和OpenCV录制RTSP视频并保存5分钟时长

使用类和函数实现RTSP视频录制(固定5分钟时长)

下面是基于OpenCV实现的RTSP视频录制类,专门处理固定5分钟时长的录制需求,逻辑清晰且易于复用:

import cv2
import time

class RTSPCaptureRecorder:
    def __init__(self, rtsp_url, save_path, record_duration=300):
        self.rtsp_url = rtsp_url
        self.save_path = save_path
        self.record_duration = record_duration  # 默认5分钟,单位秒
        self.cap = None
        self.out = None
        self.fps = 25  # 默认帧率,可根据实际流调整

    def _init_capture(self):
        # 初始化RTSP流捕获
        self.cap = cv2.VideoCapture(self.rtsp_url)
        if not self.cap.isOpened():
            raise Exception("无法打开RTSP流")
        
        # 获取实际流的帧率(如果能获取到)
        actual_fps = self.cap.get(cv2.CAP_PROP_FPS)
        if actual_fps > 0:
            self.fps = actual_fps

        # 获取视频宽高
        width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        
        # 初始化视频写入器
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        self.out = cv2.VideoWriter(self.save_path, fourcc, self.fps, (width, height))

    def start_recording(self):
        try:
            self._init_capture()
            total_frames = int(self.fps * self.record_duration)
            recorded_frames = 0

            print(f"开始录制,将持续{self.record_duration}秒...")
            start_time = time.time()

            while recorded_frames < total_frames:
                ret, frame = self.cap.read()
                if not ret:
                    print("RTSP流读取失败,尝试重新连接...")
                    time.sleep(1)
                    self._init_capture()
                    continue
                
                self.out.write(frame)
                recorded_frames += 1

                # 可选:每100帧打印进度
                if recorded_frames % 100 == 0:
                    elapsed = time.time() - start_time
                    print(f"已录制{elapsed:.2f}秒,完成{recorded_frames/total_frames*100:.1f}%")

            print("录制完成,视频已保存至:", self.save_path)

        except Exception as e:
            print(f"录制过程出错: {str(e)}")
        finally:
            # 释放资源
            if self.cap:
                self.cap.release()
            if self.out:
                self.out.release()
            cv2.destroyAllWindows()

# 使用示例
if __name__ == "__main__":
    recorder = RTSPCaptureRecorder(
        rtsp_url="rtsp://your_rtsp_stream_url",
        save_path="recorded_video.avi",
        record_duration=300  # 5分钟=300秒
    )
    recorder.start_recording()

关键细节说明

  • 时长控制逻辑:通过总帧数=帧率×时长秒数来精准控制录制时长,相比单纯用时间计时,能避免因流卡顿导致的时长误差。
  • 流异常处理:如果RTSP流中断,会自动尝试重新连接,提升录制稳定性。
  • 帧率适配:优先获取RTSP流的实际帧率,若获取失败则使用默认25fps,保证视频播放速度正常。
  • 资源释放:在finally块中统一释放捕获和写入资源,避免内存泄漏。

注意事项

  • 确保安装了OpenCV:pip install opencv-python
  • 编码格式可根据需求调整,比如MP4V对应MP4格式,需注意保存文件后缀名一致。
  • 如果RTSP流需要用户名密码,格式为rtsp://username:password@stream_url。

内容的提问来源于stack exchange,提问作者Anoop Maurya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:40:46