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

使用cv2.VideoWriter导出的视频文件损坏无法播放问题求助

Windows 10下OpenCV导出视频损坏无法播放的解决方案

问题背景

在Windows 10系统(Python 3.11.1 + OpenCV 4.7.0.68)中,使用OpenCV调整视频大小并导出为AVI/MP4格式时,生成的文件损坏无法播放,尝试多种编码组合(MJPG、XVID、H264等)均无效,但相同代码在其他环境可正常运行。

可能的解决方案及修改建议

1. 强制使用整数FPS

Windows下部分编码器不支持浮点数FPS,将cap.get(cv2.CAP_PROP_FPS)返回的浮点值转为整数:

fps = int(cap.get(cv2.CAP_PROP_FPS))

2. 确保输出分辨率与帧尺寸一致

虽然代码中已做resize,但仍需确认resize后的帧尺寸与VideoWriter指定的分辨率完全匹配,可添加打印验证:

frame_resized = cv2.resize(frame, (640, 480))
print(frame_resized.shape)  # 应输出 (480, 640, 3),对应(width=640, height=480)

3. 更换为Windows原生兼容的编码器

优先选择Windows系统对编码器支持更好的组合:

  • AVI格式:使用MJPG编码
    out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), fps, (640, 480))
    
  • MP4格式:使用AVC1编码
    out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'AVC1'), fps, (640, 480))
    

4. 添加事件循环触发

Windows下OpenCV的VideoWriter依赖事件循环完成缓冲区写入,即使不显示窗口,也需在循环中添加cv2.waitKey(1):

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frame_resized = cv2.resize(frame, (640, 480))
    out.write(frame_resized)
    cv2.waitKey(1)  # 触发事件处理,确保帧写入完成

5. 检查帧格式兼容性

确保写入的帧是3通道BGR格式(OpenCV默认),若输入为灰度图需转换:

if frame_resized.ndim == 2:
    frame_resized = cv2.cvtColor(frame_resized, cv2.COLOR_GRAY2BGR)

修改后的完整示例代码

import cv2

cap = cv2.VideoCapture('input.mp4')
fps = int(cap.get(cv2.CAP_PROP_FPS))
target_size = (640, 480)

# 使用MJPG编码的AVI格式
out = cv2.VideoWriter(
    'output_fixed.avi',
    cv2.VideoWriter_fourcc(*'MJPG'),
    fps,
    target_size
)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    frame_resized = cv2.resize(frame, target_size)
    # 转换灰度图为3通道BGR
    if frame_resized.ndim == 2:
        frame_resized = cv2.cvtColor(frame_resized, cv2.COLOR_GRAY2BGR)
    out.write(frame_resized)
    cv2.waitKey(1)

cap.release()
out.release()
cv2.destroyAllWindows()

额外排查点

  • 确认输出目录有写入权限,避免因权限不足导致文件写入不完整
  • 运行print(cv2.getBuildInformation())检查OpenCV是否启用FFMPEG支持,若FFMPEG未启用需重新安装带FFMPEG的OpenCV包

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:50:22