MoviePy - 中文文档2-快速上手-使用matplotlib(一个2D绘图库)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ucsheep/article/details/82767025

使用matplotlib(一个2D绘图库)

用户自定义动画

moviepy允许开发者自定义动画:定义一个方法,以numpy数组的形式在动画中给定的时间返回一帧画面。

一个例子如下:

from moviepy.editor import VideoClip

def make_frame(t):
    '''
    返回在t时刻的一帧画面
    '''
    # 通过其他的任意第三方库,创建一帧画面
    return frmae_from_time_t #(height * width * 3) Numpy array
animation = VideoClip(make_frame, duration=3)

这样的animation,通常可以按照moviepy中的方式导出,如下:

# 导出为一个视频
animation.write_videofile("my_animation.mp4", fps=24)
# 导出为一个GIF动图
animation.write_gif("my_animation.gif", fps=24) # 一般情况,这种方式会慢点

简单的matplotlib示例

一个使用matplotlib操作动画的例子,如下:
 

import matplotlib.pyplot as plt
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, 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(name_frame, duration=duration)
animation.write_gif("matplotlib.gif", fps=20)

使用Jupyter Notebook

如果我们在Jupyter Notebook写代码的话,我们就可以享受到使用ipython_display方法将VideoClips嵌入notebook的output部分。下面就是一个实现案例:
 

import matplotlib.pyplot as plt
import numpy as np
from moviepy.editor import VideoClip
from moviepy.vedio.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)

猜你喜欢

转载自blog.csdn.net/ucsheep/article/details/82767025