Simple animation and saving movies in Python

January 26, 2009

Having battled through this in Matlab, doing it the Python way is extremely easy on any platform. One makes use of Mencoder, which we can just call using os.system. Here’s an idiom, culled mostly from the scipy wiki:

from pylab import *
import os
# set the interactive mode of pylab to ON
ion()
# opens a new figure to plot into
fig_hndl = figure()
# make an empty list into which we'll append
# the filenames of the PNGs that compose each
# frame.
files=[]	
# filename for the name of the resulting movie
filename = 'animation'
number_of_frames = 100
for t in range(number_of_frames):
	# draw the frame
	imshow(rand(100,100))
	# form a filename
	fname = '_tmp%03d.png'%t
	# save the frame
	savefig(fname)
	# append the filename to the list
	files.append(fname)
# call mencoder	
os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 
	-ovc lavc -lavcopts vcodec=wmv2 -oac copy 
	-o " + filename + ".mpg")
# cleanup
for fname in files: os.remove(fname)

Depending on how complicated the plot is, this can take anywhere from a while to ages and ages. It’s good quality, though! You can muck about with the frame rate in the call to encoder where it says fps=10. Change that 10 to something else (30 seems popular!). Also there are probably better codecs than wmv2!

Having written this, it strikes me we could probably do all this in Matlab in the same way, rather than trying to make movies using Matlab’s builtins…

Advertisements

One Response to “Simple animation and saving movies in Python”

  1. Jon Allen Says:

    I have used a bit of the code “Simple Animation and Saving Movies in Python” by Mike Dewar. The ion() command was an epiphany for me! It makes the figure window like Matlab where the figure is “current” and writing to it in a loop replaces the current image with the new one. This is EXTREMELY important for viewing 2d array simulations in a loop! It makes writing the images to a movie file unnecessary if you just want to visualize the simulation.
    The only problem I am having is that after the viewing loop, the figure does not close down properly and hangs up. Windows then sends error messages when you try to close the figure.

    What stupid, simple command am I missing here? I’m sure it is something simple, but I just don’t know what it is….? It did not seem to be a problem in your program.

    Please send me an eamil if you can!

    jcallen@sbcglobal.net

    Thanx for any help,
    Jon


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: