Flask读取RTSP视频流,及其简单的一个案例
此章节包括通过是使用Flask可以实时地显示RTSP视频流。代码确实非常简单,源于Github,主要为为Nvidia Deepstream极致细节:3. Deepstream Python RTSP视频输出显示这篇博客写的。这里会附上所有代码,如果对其中某些部分不明白的,可以翻看我这个系列文档,很容易使用。
喜欢的朋友收藏点赞哦。
app.py
from flask import Flask, render_template, Response
import cv2
app = Flask(__name__)
camera = cv2.VideoCapture('rtsp://localhost:8554/ds-test')
# use 0 for web camera
# for cctv camera use rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' instead of camera
# for local webcam use cv2.VideoCapture(0)
def gen_frames():
# generate frame by frame from camera
while True:
# Capture frame-by-frame
success, frame = camera.read() # read the camera frame
if not success:
break
else:
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat frame one by one and show result
@app.route('/video_feed')
def video_feed():
#Video streaming route. Put this in the src attribute of an img tag
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/')
def index():
"""Video streaming home page."""
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Live Streaming Demonstration</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h3 class="mt-5">Live Streaming</h3>
<img src="{{ url_for('video_feed') }}" width="100%">
</div>
</div>
</div>
</body>
</html>
结果
结果如下(当然,你需要保证有rtsp的数据先):
运行
需要先安装一下flask以及opencv-python(pip3 install…),然后在主路径下运行python3 app.py
。(这里写的很不专业,因为只是实现一下效果,如对flask感兴趣,请参见我的Flask 极致细节
系列文档)。