Displaying a sequence of images in iPython Notebooks

You can rip a sequence of images into an mp4 and display it inline in an ipython notebook using a function like this:

import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import display, HTML
def plot_movie_mp4(image_array):
dpi = 72.0
xpixels, ypixels = image_array[0].shape[0], image_array[0].shape[1]
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
im = plt.figimage(image_array[0])
def animate(i):
im.set_array(image_array[i])
return (im,)
anim = animation.FuncAnimation(fig, animate, frames=len(image_array))
display(HTML(anim.to_html5_video()))

However there’s a disadvantage with this method: You have no control over the encoding settings so you’re likely to get a video with a lot of artifacts.

If you would like a video without artifacts, check out JSAnimation. This sends the sequence of images to the browser along with some javascript to play through them. This looks much better and is much easier to control than an html5 video control:

from JSAnimation import IPython_display
def plot_movie_js(image_array):
dpi = 72.0
xpixels, ypixels = image_array[0].shape[0], image_array[0].shape[1]
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
im = plt.figimage(image_array[0])
def animate(i):
im.set_array(image_array[i])
return (im,)
anim = animation.FuncAnimation(fig, animate, frames=len(image_array))
display(IPython_display.display_animation(anim))

Compiling OpenCV 3.1 on Ubuntu 16.04

16.04 uses gcc 5.4 by default. You’ll need to install gcc 4.9 and configure OpenCV to use 4.9 instead:

sudo apt-get install g++-4.9
cmake -DCMAKE_C_COMPILER=/usr/bin/gcc-4.9 -DCMAKE_CXX_COMPILER=/usr/bin/g++-4.9 .

If you have CUDA installed you may want to disable compiling the CUDA libraries as well, or else suffer another hour+ of compilation time. Add -DWITH_CUDA=OFF to disable CUDA.