[python] ffmpeg-python读取rtsp(tcp方式)

[python] ffmpeg-python读取rtsp(tcp方式)

问题描述

在多路无线摄像头同时接入时,网络不稳定,经常出现雪花屏的问题。参考网上资料,怀疑是网络摄像头默认使用RTSP协议,RTSP下层默认使用UDP传输,而UDP传输是不可靠的,会丢包,所以导致雪花屏。

RTSP使用TCP或者UDP传输,使用TCP还是UDP取决于客户端的SETUP请求。所以尝试将由UDP改为TCP取流。

opencv-python的videocapture获取rtsp只支持UDP方式,改为用FFmpeg-python以tcp方式获取流

两种库和方式取流的速度、延迟和稳定性还待测试

FFmpeg-python

安装

pip install ffmpeg-python
  • Github仓库地址

  • API 文档

  • 使用样例

ffmpeg学习资源

  • FFmpeg Homepage
  • FFmpeg Documentation
  • FFmpeg Filters Documentation

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ffmpeg
import numpy as np
import cv2

camera = 'rtsp://admin:[email protected]/h264/ch1/main/av_stream'

probe = ffmpeg.probe(camera)
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
width = int(video_stream['width'])
height = int(video_stream['height'])

out = (
    ffmpeg
        .input(camera, rtsp_transport='tcp')
        .output('pipe:', format='rawvideo', pix_fmt='bgr24', loglevel="quiet", r=25)
        .run_async(pipe_stdout=True)
)
cnt_empty = 0
while True:
    in_bytes = out.stdout.read(height * width * 3)
    if not in_bytes:
        cnt_empty += 1
        if cnt_empty > 10:
            break
    cnt_empty = 0
    frame = np.frombuffer(in_bytes, dtype=np.uint8).reshape(height, width, 3)
    # to process frame
    cv2.imshow('test', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

参考

解决摄像头花屏问题

你可能感兴趣的:(Python,python,ffmpeg,opencv)