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

Python动画保存为MP4失败,寻求分步解决方案

解决Matplotlib动画保存时FFmpeg H264编码报错问题

问题描述

我在用Matplotlib保存Python动画时遇到报错,尝试过相关解决方案但无效,求分步解决方法。

我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, writers

x_data = []
y_data = []

fig, ax = plt.subplots()
ax.set_xlim(0, 105)
ax.set_ylim(0, 12)
line, = ax.plot(0, 0)

def animation_frame(i):
    x_data.append(i * 10)
    y_data.append(i)

    line.set_xdata(x_data)
    line.set_ydata(y_data)
    return line, 

animation = FuncAnimation(fig, func=animation_frame, frames=np.arange(0, 10, 0.1), interval=10)

# setting up writers object
Writer = writers['ffmpeg']
writer = Writer(fps=15, metadata={'artist': 'Me'}, bitrate=1800)

animation.save('Line Graph Animation.mp4', writer)

收到的错误信息:

subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '640x480', '-pix_fmt', 'rgba', '-r', '15', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-b', '1800k', '-metadata', 'artist=Me', '-y', 'Line Graph Animation.mp4']' returned non-zero exit status 1.

分步解决方法

1. 验证FFmpeg安装与环境变量配置

  • 打开命令行输入ffmpeg -version,若提示“找不到命令”,说明FFmpeg未安装或未添加到系统环境变量。
  • 下载对应系统的FFmpeg安装包,解压后将包含ffmpeg.exe的文件夹路径添加至系统PATH环境变量。
  • 重启命令行和Python编辑器,再次执行ffmpeg -version确认正常输出版本信息。

2. 直接指定FFmpeg可执行文件路径

若环境变量配置无效,在代码中添加FFmpeg路径配置,放在导入Matplotlib的语句之后:

plt.rcParams['animation.ffmpeg_path'] = '你的FFmpeg完整路径'
# Windows示例:'C:/ffmpeg/bin/ffmpeg.exe'
# Linux/macOS示例:'/usr/local/bin/ffmpeg'

3. 更换具体的H264编码器名称

部分FFmpeg版本中h264别名无法匹配编码器,可指定具体编码格式:

  • 软件编码通用选项:libx264
  • 硬件加速选项:NVIDIA显卡用h264_nvenc,AMD显卡用h264_amf
  • 修改Writer初始化代码:
writer = Writer(fps=15, metadata={'artist': 'Me'}, bitrate=1800, codec='libx264')

4. 检查输出路径权限

  • 避免保存到系统保护目录(如C盘根目录),选择有写入权限的文件夹(如用户文档目录)。
  • 可尝试使用相对路径,比如./animation.mp4,或明确指定用户路径。

5. 开启详细日志排查具体错误

调高FFmpeg日志级别,查看更详细的报错原因:

writer = Writer(fps=15, metadata={'artist': 'Me'}, bitrate=1800, extra_args=['-loglevel', 'info'])

运行后根据日志提示定位问题,比如编码器缺失、像素格式不兼容等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:55:13