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

Streamlit的st.video()无法播放.avi视频及numpy.array帧的问题问询

Streamlit st.video() 播放异常解决方案

1. 适配兼容的视频编码

  • st.video 依赖浏览器原生<video>标签实现,仅支持H.264编码的MP4格式视频,其余格式如avi、原始H264流、非H.264编码的MP4都会出现空白无内容的问题
  • 解决方案:先将本地视频转码为H.264编码的MP4格式,可通过ffmpeg命令快速处理:
    ffmpeg -i input.avi -vcodec libx264 output.mp4

2. 修正视频字节读取逻辑

  • 不要直接用open()读取字节后传入,部分场景下文件句柄未正确释放会导致字节流损坏,建议使用上下文管理器读取,同时显式指定format参数避免格式识别错误:
with open("output.mp4", "rb") as f:
    video_bytes = f.read()
st.video(video_bytes, format="video/mp4")

3. numpy帧序列播放方案

  • st.video 不支持直接传入numpy数组格式的帧序列,需要先将帧序列编码为符合要求的视频字节流再传入,示例代码如下:
import cv2
import tempfile
import streamlit as st

# 假设frames是numpy帧序列,格式为(H, W, 3),BGR通道顺序
height, width, _ = frames[0].shape
fps = 24

# 创建临时视频文件
with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp:
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(tmp.name, fourcc, fps, (width, height))
    for frame in frames:
        out.write(frame)
    out.release()
    
    # 读取转码后的视频字节流播放
    with open(tmp.name, 'rb') as f:
        st.video(f.read(), format="video/mp4")

4. 其他排查点

  • 确认Streamlit版本不低于1.10.0,旧版本存在st.video字节流解析的已知Bug,可通过pip install --upgrade streamlit升级
  • 优先使用Chrome、Edge等主流浏览器播放,避免使用小众浏览器或过旧版本浏览器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:09:03