You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+Flask摄像头网页直播:video标签显示问题排查

问题分析

你的代码存在两个核心问题:

  1. 前端错误使用EventSource处理multipart流:后端输出的multipart/x-mixed-replace格式是用于连续JPEG帧的推送,而EventSource是为Server-Sent Events(文本事件流)设计的,两者不兼容,导致video标签无法加载有效内容。
  2. 根路由页面无内容:大概率是模板渲染问题,需确认模板路径和文件正确性。

解决方案

方案1:用img标签实现低延迟直播(简单兼容)

如果不需要严格使用video标签,这种方式最快捷,利用img标签自动刷新multipart流的特性实现直播效果:

修改index.html

<!doctype html>
<html>
  <head>
    <title>Webcam Stream</title>
  </head>
  <body>
    <h1>Webcam Stream</h1>
    <img src="/video_feed" width="640" height="480" />
  </body>
</html>

根路由问题排查

  • 确认index.html位于项目根目录的templates文件夹下
  • 测试模板渲染是否正常:将index路由临时改为return "Test Template",若能显示,说明模板文件名或路径有误(注意大小写)
  • 清除浏览器缓存或使用隐私模式访问

方案2:用video标签播放标准视频流

若必须使用video标签,需将后端输出从JPEG帧转为标准视频编码流(如H.264):

修改index.py

import cv2
from flask import Flask, render_template, Response

app = Flask(__name__)
camera = cv2.VideoCapture(0)

# 配置视频编码参数
fourcc = cv2.VideoWriter_fourcc(*'H264')
fps = 20.0
frame_width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))

def generate_video_stream():
    while True:
        success, frame = camera.read()
        if not success:
            break
        # 将帧编码为H.264格式的MP4
        ret, buffer = cv2.imencode('.mp4', frame, [int(cv2.IMWRITE_MP4_FOURCC), fourcc])
        if not ret:
            continue
        yield buffer.tobytes()

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

@app.route('/video_feed')
def video_feed():
    return Response(generate_video_stream(), mimetype='video/mp4')

if __name__ == '__main__':
    app.run(debug=True)

修改index.html

<!doctype html>
<html>
  <head>
    <title>Webcam Stream</title>
  </head>
  <body>
    <h1>Webcam Stream</h1>
    <video id="video" width="640" height="480" autoplay muted playsinline src="/video_feed"></video>
  </body>
</html>

注意:这种方式会有一定缓冲延迟,若追求低延迟,可考虑WebRTC方案,但需要额外的信令服务支持。


内容的提问来源于stack exchange,提问作者Douzooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:47:02