Making Animations using MoviePy

This notebook shows how to make animations using MoviePy and Matplotlib. Here are links to the MoviePy documentation and a short tutorial:

Let's start by importing everything we need:


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from moviepy.video.io.bindings import mplfig_to_npimage
import moviepy.editor as mpy


WARNING:py.warnings:/usr/local/lib/python3.4/dist-packages/skimage/filter/__init__.py:6: skimage_deprecation: The `skimage.filter` module has been renamed to `skimage.filters`.  This placeholder module will be removed in v0.13.
  warn(skimage_deprecation('The `skimage.filter` module has been renamed '


In [2]:
plt.ioff()

To create an animation we need to do two things:

  1. Create the initial visualization, with handles on the figure and axes object.
  2. Write a function that will get called for each frame that updates the data and returns the next frame.

In [3]:
duration = 10.0 # this is the total time

N = 500

# Make the initial plot outside the animation function
#fig = plt.gcf()
fig_mpl, ax = plt.subplots(1,figsize=(5,3), facecolor='white');
x = np.random.normal(0.0, 1.0, size=N)
y = np.random.normal(0.0, 1.0, size=N)
plt.sca(ax)
plt.xlim(-3,3)
plt.ylim(-3,3)
scat = ax.scatter(x, y);
# lines, = ax.plot(x,y,'b.')

In [4]:
def make_frame_mpl(t):
    # t is the current time between [0,duration]
    newy = y*np.cos(4.0*t/duration)
    # Just update the data on each frame
#     lines.set_xdata(x)
#     lines.set_ydata(newy)
    # set_offset takes a Nx2 dimensional array of positions
    #First column is x, second is y.
    scat.set_offsets(np.transpose(np.vstack([x, newy])))
    # The mplfig_to_npimage convert the matplotlib figure to an image that
    # moviepy can work with:
    return mplfig_to_npimage(fig_mpl)

"""First argument is a function that takes time. Movipy calls function and passes the current time. 
Times passed is between 0 and the duration. The exact values of the time passed depends on the fps."""

animation = mpy.VideoClip(make_frame_mpl, duration=duration)

Use the following call to generate and display the animation in the notebook:


In [5]:
animation.ipython_display(fps=24)



Out[5]:

Use the following to save the animation to a file that can be uploaded you YouTube:

Save as a video file so that we can use this on github, upload mp4 to youtube then use the youtube object to display the video inline.


In [6]:
animation.write_videofile("scatter_animation.mp4", fps=20)


[MoviePy] >>>> Building video scatter_animation.mp4
[MoviePy] Writing video scatter_animation.mp4
[MoviePy] Done.
[MoviePy] >>>> Video ready: scatter_animation.mp4