不直接采取命令行方式,而是采取ffmpeg-python
主函数
import ffmpeg
import numpy as np
import cv2
from flask import Flask, request,jsonify
from multiprocessing import Process
app = Flask(__name__)
def video_start(rtmp):
# 使用 ffmpeg-python 读取视频帧
process = (
ffmpeg
.input(rtmp, hwaccel='cuda')
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True)
)
# 获取视频信息
probe = ffmpeg.probe(rtmp)
video_info = next(stream for stream in probe['streams'] if stream['codec_type'] == 'video')
width = int(video_info['width'])
height = int(video_info['height'])
while True:
# 读取每一帧数据
in_bytes = process.stdout.read(width * height * 3)
if not in_bytes:
break
# 将字节数据转换为 NumPy 数组
frame = np.frombuffer(in_bytes, np.uint8).reshape([height, width, 3])
# 释放资源
process.stdout.close()
process.wait()
@app.route('/api', methods=['POST'])
def api():
data = request.get_json()
rtmp = data['rtmp']
new_process = Process(target=video_start, args=(rtmp,))
new_process.start()
return jsonify({'message': 'success', 'code': 200}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=6009, use_reloader=False)