rtsp_mp4.py文件内容
import cv2
import json
def rtsp_mp4():
with open('demo.json', 'r', encoding='utf-8') as fp:
opt = json.load(fp)
# 获取视频流地址
cap = cv2.VideoCapture(opt["source"])
# 帧数
fps = cap.get(cv2.CAP_PROP_FPS)
# 宽高
width, height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
size = (width, height)
# 定义视频编码方式,保存为mp4文件
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter()
# 视频存储对象,视频格式,帧数,视频大小
out.open(opt["video_name"], fourcc, fps, size)
while True:
# 获取每一帧
ref, frame = cap.read()
# 若没有帧返回,则重新刷新rtsp视频流
while not(ref):
cap = cv2.VideoCapture(opt["source"])
# 获取每一帧
ref, frame = cap.read()
continue
# 翻转
frame = cv2.flip(frame, 1)
# 保存每一帧合并成视频
out.write(frame)
# 显示视频界面
cv2.imshow("frame", frame)
# 按esc退出检测视频
key = cv2.waitKey(1)
if key == 27:
break
# 按Q退出
# if cv2.waitKey(25) & 0xFF == ord('Q'):
# break
# 释放
cap.release()
out.release()
cv2.destroyAllWindows()
rtsp_mp4()
json文件内容
{
"source": "rtsp://127.0.0.1/live/stream1_renshouyingji",
"video_name": "demo.mp4"
}
视频断流后会自动重连,保存的视频会拼接在之前的视频后面