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

使用cv2.VideoWriter.write()无法生成视频的问题排查

问题排查与修复方案

1. 变量名错误(最直接触发报错的原因)

代码里定义了frame_filename = f"{i}",但读取图片时误用了未定义的segmented_frame_filename,导致cv2.imread返回None。虽然代码有读取失败的判断逻辑,但变量名错误不修正,后续帧处理和写入必然出问题。

修复:
将segmented_frame = cv2.imread(segmented_frame_filename)改为segmented_frame = cv2.imread(frame_filename)。

2. VideoWriter初始化有效性检查

如果修正变量名后仍报错,需确认视频写入器是否成功初始化:

  • 检查output_video.avi所在目录是否有写入权限,比如当前目录是否允许创建新文件。
  • 验证编码格式兼容性:XVID适配AVI格式,但部分系统可能不支持,可尝试替换为MJPG(写法为cv2.VideoWriter_fourcc(*'MJPG'))。
  • 初始化后添加状态检查:如果out.isOpened()返回False,说明写入器创建失败,直接终止流程。

3. 帧尺寸与通道数匹配验证

  • 确保resized_image的尺寸和out_size完全一致:代码中resize参数是(800,480),和out_size匹配,但要注意cv2.resize的参数顺序是(width, height),而图片的shape显示为(height, width, channels),正常彩色图打印结果应为(480, 800, 3)。
  • 如果处理的是灰度图,需在VideoWriter初始化时添加isColor=False参数,否则写入会失败。

修复后的完整代码

import cv2
def stich_video(frames):
    output_video_path = 'output_video.avi'
    out_size = (800, 480)
    fourcc = cv2.VideoWriter_fourcc('XVID')
    out = cv2.VideoWriter(output_video_path, fourcc, 24, out_size)
    
    # 检查视频写入器是否成功初始化
    if not out.isOpened():
        print("Error: 初始化VideoWriter失败,请检查路径、编码格式和权限。")
        return
    
    for frame_idx, frame_filename in enumerate(frames):
        segmented_frame = cv2.imread(frame_filename)
        if segmented_frame is None:
            print(f"读取帧失败 {frame_idx}: {frame_filename},请检查文件路径。")
            continue

        resized_image = cv2.resize(segmented_frame, out_size) 
        print(f"调整后帧尺寸: {resized_image.shape}")

        if not out.write(resized_image):
            print(f"写入帧失败 {frame_idx}: {frame_filename}。")

    out.release()

额外注意事项

  • 确保frames数组中的元素是正确的图片路径(相对或绝对路径均可),如果用相对路径,需确认脚本运行的工作目录和图片所在目录一致。

内容的提问来源于stack exchange,提问作者Daim Abbas Kazmi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:27:26