贝利信息

如何在 Flask 中正确实现摄像头实时视频流传输

日期:2026-01-16 00:00 / 作者:聖光之護

本文详解 flask 视频流(mjpeg)开发中常见的阻塞与生成器误用问题,通过修正 `yield` 位置、统一生成器层级、确保响应格式合规,使 opencv 摄像头画面可在浏览器中稳定显示。

在 Flask 中实现摄像头实时视频流(如 /video_feed),核心在于正确构造符合 multipart/x-mixed-replace 协议的响应流。你遇到的“Flask 不显示图像”问题,根本原因在于 生成器逻辑错位:algorithms.raw_image() 是一个无限 while True 循环,但其内部调用 c

aller.output(frame) 时未 yield,导致整个函数无法被 Flask 的 Response 迭代;而 server.output() 方法本身虽有 yield,却错误地放在了被调用方(而非被迭代的主生成器中)。

✅ 正确结构:生成器必须逐帧 yield 响应片段

需满足两个关键条件:

  1. video_feed 路由返回的 Response 必须接收一个可迭代的生成器函数
  2. 该生成器必须直接 yield 完整的 MJPEG 帧字节块(含边界头、Content-Type 和图像数据)。

因此,修复方案如下:

? 修改 algorithms.py

import cv2

camera = cv2.VideoCapture(0)

class Algorithms:  # 建议类名 PascalCase
    @staticmethod
    def raw_image():
        while True:
            success, frame = camera.read()
            if not success:
                print("Warning: Failed to read frame from camera")
                continue  # 避免中断整个流
            frame = cv2.flip(frame, 1)
            yield frame  # 直接 yield 原始帧,解耦编码逻辑

? 修改主服务文件(如 app.py)

from algorithms import Algorithms
from flask import Flask, Response
import cv2

app = Flask(__name__)

def generate_frames():
    for frame in Algorithms.raw_image():  # 迭代原始帧
        ret, buffer = cv2.imencode('.jpg', frame)
        if not ret:
            continue
        frame_bytes = buffer.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')

@app.route('/')
def index():
    return '''
    

Live Camera Feed

@@##@@ ''' @app.route('/video_feed') def video_feed(): return Response( generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame' ) if __name__ == '__main__': try: app.run(host='0.0.0.0', port=5000, debug=False) # 生产环境禁用 debug finally: cv2.destroyAllWindows() # 确保退出时释放资源

⚠️ 关键注意事项

按此结构调整后,浏览器访问 http://localhost:5000 即可看到实时镜像画面——这才是 Flask 视频流的标准实践模式。