Article directory
References
Network real-time video streaming based on
1 Overview
Use Flask+Python+OpenCV to implement camera reading of image frames and web page video streaming
2. Basic use cases
Step 1: Use Flask
the framework to obtain the video stream
from flask import Flask, render_template, Response
import cv2
"""
本工具,是用openCV获取摄像头的实时视频流,实时显示在前端中
注意:index.html 文件,需要存放在 templates目录中
"""
# 定义 VideoCamera 类表示一个视频摄像头对象
class VideoCamera(object):
def __init__(self):
# 通过 OpenCV 获取实时视频流
self.video = cv2.VideoCapture(0)
def __del__(self):
# 在对象销毁时释放视频捕获对象
self.video.release()
def get_frame(self):
# 从视频捕获中读取一帧图像
success, image = self.video.read()
# 因为 OpenCV 读取的图像并非 JPEG 格式,所以要用 motion JPEG 模式需要先将图像转码成 jpg 格式图像
ret, jpeg = cv2.imencode('.jpg', image)
# 返回转码后的 JPEG 图像数据(以字节形式)
return jpeg.tobytes()
# 创建 Flask 网络应用对象
app = Flask(__name__, static_folder='./static')
# 定义主页路由
@app.route('/')
def index():
# 使用 jinja2 模板渲染 index.html 文件并返回给客户端
return render_template('index.html')
# 定义生成器函数 gen,用于不断输出视频流帧
def gen(camera):
while True:
# 从 VideoCamera 对象获取一帧图像
frame = camera.get_frame()
# 使用 generator 函数输出视频流,每次请求输出的 content 类型是 image/jpeg
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
# 定义视频流地址的路由
@app.route('/video_feed')
def video_feed():
# 返回 Response 对象,通过 gen(VideoCamera()) 生成视频流响应
# 使用 multipart/x-mixed-replace 内容类型,其中 boundary=frame 表示分隔符为 frame 来分隔不同的数据部分
return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')
# 当脚本作为主程序运行时,启动 Flask 应用在 0.0.0.0:5000 地址上,并开启调试模式
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5000)
Supplement: Parameter explanation
- At the beginning of the function,
@app.route('/')
the next function is executed, namely index(), corresponding to index.html- In index.html, the link of the picture corresponds to that in flask , and the link of the picture is constructed in
url_for()
this functionvideo_feed()
- In video_feed,
Response()
the function is used to return data, and the corresponding data isgen()
streamed out by the functionyeild
VideoCamera()
Mainly use the read function in OpenCV to read image data
Step 2: Write the front end
templates
Createindex.html
file in directory
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<img src="{
{ url_for('video_feed') }}">
</body>
</html>
illustrate:
Create
index.html
files to facilitate backend routing
Step 3: Demo
1. View the console
2. View browser