如何正确启用matplotlib.animation的ffmpeg?

如何正确启用matplotlib.animation的ffmpeg?

为了启用 matplotlib.animation的ffmpeg ,我们可以执行以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。

  • 设置 ffmpeg 目录。

  • 创建一个新图或激活现有图,使用 figure() 方法。

  • ‘ax1’ 添加到图形作为子图排列的一部分。

  • 基于预先存在的轴绘制分割线。

  • 创建随机数据以被绘制,以显示数据作为图像,即,在2D规则光栅上。

  • ScalarMappable 实例 cb 创建颜色条。

  • 将当前帧设置为标题。

  • 制作颜色地图列表。

  • 通过反复调用函数animate创建动画。该函数创建新的随机数据,然后使用 imshow() 方法将数据显示为图像。

  • 获取基于气管的 ffmpeg 编写者的实例。

  • 保存当前动画图。

实例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'

fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('帧 0')

cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']

def animate(i):
    cax.cla()
    data = np.random.rand(5, 5)
    im = ax.imshow(data, cmap=cmap[i%len(cmap)])
    fig.colorbar(im, cax=cax)
    tx.set_text('帧 {0}'.format(i))

ani = animation.FuncAnimation(fig, animate, frames=10)
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)

输出

当我们执行代码时,它将创建一个名为’plot.mp4’的mp4文件,并将其保存在项目目录中。

您的浏览器不支持HTML5视频。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程