Flask 串流 Webcam 教學

介紹如何使用 Flask 與 OpenCV 在 Raspberry Pi 上建立簡單的 Webcam 串流網頁。

很適合搭配 1080p Web CAM,延伸成監控、智慧門鈴或影像辨識展示系統。

FlaskWeb CAMOpenCVStreaming

一、教學目標

二、安裝環境

python3 -m venv venv
source venv/bin/activate
python3 -m pip install flask opencv-python

三、專案結構

webcam_flask/
├── app.py
└── templates/
    └── index.html

四、app.py 範例

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)

五、templates/index.html 範例

<!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 反向代理。

如果你想把這份教材再延伸,我下一步就可以接成「Flask Webcam 串流 + 拍照存檔 + Nginx 部署」完整專題頁。

九、常見問題

十、推薦參考