開發(fā)環(huán)境:Python3.8.9
操作系統(tǒng):MacOS
安裝依賴標(biāo)準(zhǔn)庫:
Flask==2.0.3
opencv-python==4.5.5.64
pip3 install flask
pip3 install opencv-python
文件結(jié)構(gòu)
flask-demo/
├ templates/ # 模板文件目錄
├ index.html # 頁面模板
├ app.py # 項(xiàng)目啟動(dòng)程序
代碼部分:
- app.py
from flask import Flask, render_template, Response
import cv2
app = Flask(__name__)
# 頁面路由
@app.route('/')
def index():
return render_template('index.html')
# 獲取動(dòng)態(tài)數(shù)據(jù)
def gen(capture):
while True:
# 讀取攝像頭數(shù)據(jù)
ref, frame = capture.read()
# 圖片編碼
ret, buffer = cv2.imencode('.jpg', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
# 視頻流接口
@app.route('/video_feed')
def video_feed():
# cv2.VideoCapture(0) 獲取本地?cái)z像頭權(quán)限
return Response(gen(cv2.VideoCapture(0)),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
- templates/index.html
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<!-- 視頻部分 -->
<img src="{{ url_for('video_feed') }}">
</body>
</html>
啟用應(yīng)用
python3 -m flask run --host=<Your IP>
效果展示:
瀏覽器訪問效果
項(xiàng)目命令行啟動(dòng)截圖
大功告成!