Python 动图 动画制作 —— moviepy matplotlib animation

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       
 

进入命令行界面(windows ⇒ cmd),下载安装,pip install moviepy

0. figure 的成员函数

# 创建 figurefig, ax = plt.subplots()fig = plt.figure(figsize(6, 8))# 成员函数fig.set_tight_layout(True)fig.get_dpi()fig.get_size_inches() 
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

1. 使用 moviepy

from moviepy.video.io.bindings import mplfig_to_npimageimport moviepy.editor as mpyf = plt.figure(figsize=(8, 8))# 接受一个时间参数,def make_frame_mpl(t):    ...    return mplfig_to_npimage(f)                # 所有的图像都在同一个figure上animation = mpy.VideoClip(make_frame_mpl, duration=5)animation.write_gif("animation-94a2c1ff.gif", fps=20)        # 这样其实就可以做一个动态图出来了;
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2. 使用 matplotlib.animation

import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationimport numpy as npimport seabornfig, ax = plt.subplots()x = np.arange(0, 20, .01)ax.scatter(x, x+np.random.normal(0, 3, len(x)))line, = ax.plot(x, x-5, 'r-', lw=2)# i => ith framedef update(i):    line.set_ydata(x-5+i)    ax.set_xlabel('frame {0}'.format(i))    return line, axif __name__ == '__main__':    animation = FuncAnimation(fig, update, frames=np.arange(0, 20), interval=200)        # 200ms 的间隔,相当于 5fps,一秒 5 帧    plt.show()
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

如果想要保存 animation,使得 gif 足够小,可在保存时,设置足够小的 dpi,以及在创建 fig 时,figsize 也设置为尽可能得小。

animation.save('line.gif', dpi=80, writer='imagemagick')
   
   
  • 1
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hftytf/article/details/83988782