介紹如何使用 Flask 與 OpenCV 在 Raspberry Pi 上建立簡單的 Webcam 串流網頁。
很適合搭配 1080p Web CAM,延伸成監控、智慧門鈴或影像辨識展示系統。
python3 -m venv venv
source venv/bin/activate
python3 -m pip install flask opencv-python
webcam_flask/
├── app.py
└── templates/
└── index.html
from flask import Flask, render_template, Response
import cv2
app = Flask(__name__)
camera = cv2.VideoCapture(0)
def generate_frames():
while True:
success, frame = camera.read()
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')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flask Webcam</title>
</head>
<body>
<h1>Flask Webcam Stream</h1>
<img src="{{ url_for('video_feed') }}" width="720">
</body>
</html>
python3 app.py
瀏覽器開啟:
http://樹莓派IP:5000
開發階段可直接用 Flask 執行,正式展示時可再結合 Gunicorn 與 Nginx 反向代理。