美文网首页
07_MoviePy使用matplotlib_中文文档

07_MoviePy使用matplotlib_中文文档

作者: Zhen斌iOS | 来源:发表于2020-06-01 17:35 被阅读0次

目录

定义自定义动画

MoviePy允许您通过定义一个函数来生成自定义动画,该函数以numpy数组的形式在动画的给定时间返回一帧。

下面是此工作流程的一个示例:

from moviepy.editor import VideoClip

def make_frame(t):
    """Returns an image of the frame for time t."""
    # ... create the frame with any library here ...
    return frame_for_time_t # (Height x Width x 3) Numpy array

animation = VideoClip(make_frame, duration=3) # 3-second clip

然后可以通过通常的MoviePy手段导出此动画:

# export as a video file
animation.write_videofile("my_animation.mp4", fps=24)
# export as a GIF
animation.write_gif("my_animation.gif", fps=24) # usually slower

简单的matplotlib示例

然后,使用matplotlib制作动画的示例如下:

import numpy as np
from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage

x = np.linspace(-2, 2, 200)

duration = 2

fig, ax = plt.subplots()
def make_frame(t):
    ax.clear()
    ax.plot(x, np.sinc(x**2) + np.sin(x + 2*np.pi/duration * t), lw=3)
    ax.set_ylim(-1.5, 2.5)
    return mplfig_to_npimage(fig)

animation = VideoClip(make_frame, duration=duration)
animation.write_gif('matplotlib.gif', fps=20)

在Jupyter Notebook中工作

如果您在Jupyter Notebook中工作,则可以利用以下事实:可以使用ipython_display方法将VideoClips嵌入到Notebook的输出单元中。 上面的示例变为:

import numpy as np
from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage

x = np.linspace(-2, 2, 200)

duration = 2

fig, ax = plt.subplots()
def make_frame(t):
    ax.clear()
    ax.plot(x, np.sinc(x**2) + np.sin(x + 2*np.pi/duration * t), lw=3)
    ax.set_ylim(-1.5, 2.5)
    return mplfig_to_npimage(fig)

animation = VideoClip(make_frame, duration=duration)
animation.ipython_display(fps=20, loop=True, autoplay=True)

相关文章

网友评论

      本文标题:07_MoviePy使用matplotlib_中文文档

      本文链接:https://www.haomeiwen.com/subject/xcmszhtx.html