Python有些出色的数据可视化库,但很少能渲染GIF或视频动画。本文介绍如何运用MoviePy作为其他库的通用动画插件。
有了 MoviePy ,你可以用一个函数 make_(t) 自定义动画,并返回相应的时间t的视频帧(秒):
from moviepy.editor import VideoClip
def make_(t):
""" returns an image of the at time t """
# ... create the with any library
return _for_time_t # (Height x Width x 3) Numpy array
animation = VideoClip(make_, duration=3) # 3-second clip
# For the export, many options/formats/optimizations are supported
animation.write_videofile("my_animation.mp4", fps=24) # export as video
animation.write_gif("my_animation.gif", fps=24) # export as GIF (slow)
在之前的文章中,我用这种方法来做制作矢量图形动画(用Gizeh库),和光线追踪三维场景(由POV-Ray做出)。这篇文章包括 MayaVi、vispy、matplotlib、NumPy 和 Scikit-image 这些科学库。
用Mayavi的动画
Mayavi是一个针对有简单接口的交互3D数据可视化的Python模块。在第一个例子中,我们做一个高度随时间t变化的表面的动画:
import numpy as np
import mayavi.mlab as mlab
import moviepy.editor as mpy
duration= 2 # duration of the animation in seconds (it will loop)
# MAKE A FIGURE WITH MAYAVI
fig_myv = mlab.figure(size=(220,220), bgcolor=(1,1,1))
X, Y = np.linspace(-2,2,200), np.linspace(-2,2,200)
XX, YY = np.meshgrid(X,Y)
ZZ = lambda d: np.sinc(XX**2+YY**2)+np.sin(XX+d)
# ANIMATE THE FIGURE WITH MOVIEPY, WRITE AN ANIMATED GIF
def make_(t):
mlab.clf() # clear the figure (to reset the colors)
mlab.mesh(YY,XX,ZZ(2*np.pi*t/duration), figure=fig_myv)
return mlab.screenshot(antialiased=True)
animation = mpy.VideoClip(make_, duration=duration)
animation.write_gif("sinc.gif", fps=20)