Matplotlib借助ImageMagick或ffmpeg生成动图(.gif)或视频可能遇到的问题和解决方案

版权声明:大家说好才是真的吼,承蒙看官老爷厚爱。欢迎常来茶馆做客,https://blankspace.cn. https://blog.csdn.net/icurious/article/details/81709797

准备工作

首先保证要安装matplotlib。假如按照以下流程并且在网上寻求解答依然没能成功运行,可能在于matplotlib版本太旧导致。

更新使用pip:pip install -U matplotlib或者使用conda:conda update conda或者conda update matplotlib.

生成动图(.gif)

ImageMagick

  1. 先下载ImageMagick
    windows最好是下载其dynamic版本(比如ImageMagick-7.0.8-10-Q16-x64-dll.exe)。

  2. 安装后,安装选项中会有安装ffmpeg等选项,建议所有选项都勾选。其中ffmpeg可以用于之后生成.mp4等,也可以单独下载和使用。

  3. 之后检查安装路径下是否有convert.exe,有的话就大体没问题,否则重新选择正确的版本下载。

  4. 安装正确后,将安装文件所在路径加入到环境变量中(通常安装的时候就添加到环境变量中了)。

    不推荐但也是解决方法:假如不想添加到环境变量中或者忘了,则可以参考这里的做法,在notebook或者IDE中打印出matplotlib.matplotlib_fname()所在位置,并修改xxx\Lib\site-packages\matplotlib\mpl-data\matplotlibrc文本文件,将其中animation.convert_path:解注释,并在之后添加convert.exe路径,例如animation.convert_path: '"C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe"'.

  5. 对于Plot的动态效果显示,若是在PyCharm等IDE中,打开终端或者使用命令行模式(而不是直接点击run),才可以显示动画。若是在notebook中,可以在导包语句加入一条%matplotlib notebook,则可以在当前cell运行之后查看动画效果;若想在cell之外即图表窗口中显示,请将%matplotlib notebook改为%matplotlib后面什么都不接(表示使用默认图像引擎),然后重启当前的kernel,重新运行此cell即可。
  6. 动画查看,对于IDE如PyCharm,使用命令行模式打开终端运行当前程序,即可查看动画效果,否则是单张图片。这里给出一个简单的样例:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots(dpi=72, figsize=(8,6))

x = np.arange(-2*np.pi, 2*np.pi, 0.01)
y = np.sin(x)

line,  = ax.plot(x, y)

def init():
    line.set_ydata(np.sin(x))
    return line

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))
    return line

animation = animation.FuncAnimation(fig=fig, 
                                       func=animate,
                                       frames=100, # total 100 frames
                                       init_func=init,
                                       interval=20,# 20 frames per second
                                       blit=False)
animation.save('sinx.gif', writer='imagemagick')
plt.show()

若能生成如下图所示的动图则为正常,若不能请仔细核对上面的几点。
Gif

生成视频(.mp4等)

matplotlib生成的图表同样可以转换为视频。使用的是ffmpeg,可以到官网下载对应的版本,其中windows先点击Download然后点击页面中下的build去选择你电脑的版本,默认选择static就行了。

由于速度超慢,所以这里下载后我把它们放在了百度网盘 密码:jq86了,文件夹中还有上文的ImageMagick,需要者自取。

下载后将安装后文件路径添加到系统环境变量中,cmd中输入ffmpeg -version若显示出对应的版本则表示安装无误。

扫描二维码关注公众号,回复: 3804400 查看本文章

若安装了ImageMagick则生成视频只需要将上面代码的.gif改成.mp4即可,然后以终端/命令行模式运行。

若是单独安装的ffmpeg,则将animation.save('sinx.gif', writer='imagemagick')改为animation.save('sinx.mp4', writer='ffmpeg')或者animation.save('sinx.mp4')默认ffmpeg就能生成.mp4动态图表,同样然后以终端/命令行模式运行。

另外提供官方示例代码:

import numpy as np
import matplotlib
# matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)


fig1 = plt.figure()

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
                                   interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)

fig2 = plt.figure()

x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
    ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
                                   blit=True)
im_ani.save('im.mp4', writer=writer)

祝各位玩得愉快。
视频效果

猜你喜欢

转载自blog.csdn.net/icurious/article/details/81709797