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

Flask中OpenCV VideoWriter无法保存视频问题求助

问题

单独运行make_vid.py中的video()函数可正常生成video.mp4,但在Flask的app.py中调用该函数时,终端显示处理提示(出现“OpenH264 Video Codec provided by Cisco Systems, Inc.”),却无法生成实际文件。其他外部函数在Flask中运行正常,仅该OpenCV相关函数异常。

相关代码

video()函数代码

def video():
    pathIn=''
    pathOut = ''
    fps = 10
    frame_array = []
    files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
    #for sorting the file names properly
    files.sort(key = lambda x: x[5:-4])
    files.sort()

    for i in range(len(files)):
        filename=pathIn + files[i]
        #reading each files
        img = cv2.imread(filename)
        height, width, layers = img.shape
        size = (width,height)
    
    #inserting the frames into an image array
        frame_array.append(img)
    out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'avc1'), fps, size)
    for i in range(len(frame_array)):
    # writing to a image array
        out.write(frame_array[i])

Flask调用代码

from make_vid import video
@app.route('/upload_gpx', methods=["GET", "POST"])
def upload_gpx():
    video()
    return render_template('public/display_vid.html')
解决方案
  • 使用绝对路径替代相对路径:空字符串的pathIn和pathOut会依赖当前工作目录。单独运行make_vid.py时,工作目录是该脚本所在路径;而Flask默认以app.py所在目录为工作目录,两者路径不同会导致找不到帧文件或写入路径无效。将路径改为绝对路径,比如:
    pathIn = "/your/absolute/path/to/frames"
    pathOut = "/your/absolute/path/to/output/video.mp4"
    
  • 显式释放VideoWriter资源:OpenCV的VideoWriter必须调用release()方法才能完成文件写入流程,否则资源未及时释放会导致文件无法生成。在写入所有帧后添加这行代码:
    for i in range(len(frame_array)):
        out.write(frame_array[i])
    out.release()  # 新增释放操作
    
  • 检查目录权限:Flask运行进程的用户(如服务器用户www-data)可能没有目标目录的写入权限。通过chmod调整目录权限,或修改目录所有者,确保Flask进程能写入pathOut指定的位置。
  • 修正排序逻辑:代码中先后执行两次排序,第二次files.sort()会覆盖第一次的排序结果,可能导致帧顺序混乱。保留符合需求的单次排序即可,比如删除files.sort(),只保留按x[5:-4]的排序规则。
  • 添加错误排查逻辑:在读取帧时加入判断,排查是否存在无法读取的图片文件,避免后续流程中断:
    img = cv2.imread(filename)
    if img is None:
        print(f"Failed to read image: {filename}")
        continue
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:05:26