Python3 PyAV 解析Rtsp流显示和保存为mp4文件

 本文使用pyav 解析视频流并且保存为mp4,详见代码。使用opencv 的VideoWriter 保存的mp4 编码有问题不能在web 端使用H5

播放器进行播放。所以采用pyav 来实现录像功能。

import av
import cv2


# rtsp 是标准的海康威视3级子码流
video = av.open('rtsp://admin:haifan123@10.0.0.69:554/Streaming/Channels/103')
print("format:" , video.dumps_format())
video_context = video.streams.video[0].codec_context

container = av.open('test.mp4', mode='w')
stream = container.add_stream('h264', rate= video_context.framerate)
stream.width = video_context.width
stream.height = video_context.height
stream.pix_fmt = 'yuv420p'

try:
    for packet in video.demux():
        for frame in packet.decode():
            if packet.stream.type == 'video':
                print("frame = ", frame)
                
                img = frame.to_ndarray(format='bgr24')
                frame2 = av.VideoFrame.from_ndarray(img, format='bgr24')
                for packet2 in stream.encode(frame2):
                    container.mux(packet2)
                cv2.imshow("Video", img)

            
        if cv2.waitKey(1) & 0xFF == ord('q'):
            # Flush stream
            for packet2 in stream.encode():
                container.mux(packet2)
            # Close the file
            container.close()
            break
except KeyboardInterrupt:
    pass
 
cv2.destroyAllWindows()

 

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值