
本文详解 flask 视频流(mjpeg)开发中常见的阻塞与生成器误用问题,通过修正 `yield` 位置、统一生成器层级、确保响应格式合规,使 opencv 摄像头画面可在浏览器中稳定显示。
在 Flask 中实现摄像头实时视频流(如 /video_feed),核心在于正确构造符合 multipart/x-mixed-replace 协议的响应流。你遇到的“Flask 不显示图像”问题,根本原因在于 生成器逻辑错位:algorithms.raw_image() 是一个无限 while True 循环,但其内部调用 caller.output(frame) 时未 yield,导致整个函数无法被 Flask 的 Response 迭代;而 server.output() 方法本身虽有 yield,却错误地放在了被调用方(而非被迭代的主生成器中)。
✅ 正确结构:生成器必须逐帧 yield 响应片段
需满足两个关键条件:
因此,修复方案如下:
? 修改 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() # 确保退出时释放资源⚠️ 关键注意事项
- 不要在 raw_image() 内部调用 output():output 是业务逻辑(如显示/编码),不应混入数据生产流程;
- 避免 yield 嵌套错层:Response 只消费顶层生成器,output() 中的 yield 对 Response 不可见;
- 添加异常防护:camera.read() 失败时用 continue 而非 break 或 print 后挂起,否则流中断;
- 资源清理:务必在程序退出时调用 cv2.destroyAllWindows() 和 camera.release()(可在 atexit 中注册);
- 跨域与部署:开发时用 host='0.0.0.0' 允许局域网访问;生产环境推荐用 Gunicorn + Nginx,并配置 X-Accel-Buffering: no 防止 Nginx 缓存帧。
按此结构调整后,浏览器访问 http://localhost:5000 即可看到实时镜像画面——这才是 Flask 视频流的标准实践模式。










