有n条rtsp视频流,通过图像识别后在把这n条流推出去,然后通过http访问,使用python实现
from flask import Flask, Response
import cv2
import threading
app = Flask(__name__)
# RTSP 流地址列表
rtsp_urls = ["rtsp://example.com/stream1", "rtsp://example.com/stream2"]
# 存储所有视频流的字典
video_streams = {}
def start_video_stream(url, stream_name):
cap = cv2.VideoCapture(url)
while True:
ret, frame = cap.read()
if not ret:
break
# 进行图像处理
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# 将处理后的帧转换为JPEG格式
_, jpeg = cv2.imencode('.jpg', edges)
video_streams[stream_name] = jpeg.tobytes()
# 启动所有RTSP流
for i, url in enumerate(rtsp_urls):
thread = threading.Thread(target=start_video_stream, args=(url, f"stream{i}"))
thread.daemon = True
thread.start()
@app.route('/video_feed/<int:stream_id>')
def video_feed(stream_id):
def generate():
while True:
frame = video_streams.get(f"stream{stream_id}")
if frame is not None:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, threaded=True)
如果rtsp的流地址是通过网页下发下来的呢?
from flask import Flask, request, Response
import cv2
import threading
app = Flask(__name__)
# 存储所有视频流的字典
video_streams = {}
stream_threads = {}
def start_video_stream(url, stream_name):
cap = cv2.VideoCapture(url)
while True:
ret, frame = cap.read()
if not ret:
break
# 进行图像处理
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# 将处理后的帧转换为JPEG格式
_, jpeg = cv2.imencode('.jpg', edges)
video_streams[stream_name] = jpeg.tobytes()
@app.route('/add_rtsp', methods=['POST'])
def add_rtsp():
data = request.json
if 'url' not in data:
return "Missing URL", 400
url = data['url']
stream_name = data.get('stream_name', 'default')
if stream_name in stream_threads:
return f"Stream {stream_name} already exists", 400
thread = threading.Thread(target=start_video_stream, args=(url, stream_name))
thread.daemon = True
thread.start()
stream_threads[stream_name] = thread
return f"Stream {stream_name} added successfully", 200
@app.route('/video_feed/<string:stream_name>')
def video_feed(stream_name):
def generate():
while True:
frame = video_streams.get(stream_name)
if frame is not None:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, threaded=True)
发送post请求的接口请求来验证flask响应,使用requests.post实现
import requests
# 假设 Flask 应用运行在本地主机的 5000 端口
url = 'http://127.0.0.1:5000/add_rtsp'
# 定义要发送的 JSON 数据
data = {
'url': 'rtsp://192.168.193.123:8554/live/stream',
'stream_name': 'stream1'
}
# 发送 POST 请求
response = requests.post(url, json=data)
# 检查响应状态码
if response.status_code == 200:
print('Success!')
print(response.text) # 打印响应文本
else:
print(f'Failed with status code: {response.status_code}')
print(response.text) # 打印响应文本