Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Matplotlib Animation

I am trying to make an Animation of a wave package and save it as a movie. Everything except the saving is working. Can you please tell me what I am doing wrong? When going into the line ani.save('MovWave.mp4') he tells me:

    writer = writers.list()[0]
IndexError: list index out of range

I tried googling it of course, but I don't even know what it means.

UPDATE: I can call ffmpeg in console now. It says I have ffmpeg version 0.10.7-6:0.10.7-0jon1~precise installed. I updated the code and ran the program, but now I get the following error:

Traceback (most recent call last):
  ani.save('MovWave.mpeg', writer="ffmpeg")
  writer.grab_frame()
  dpi=self.dpi)
  self.canvas.print_figure(*args, **kwargs)
  self.figure.dpi = origDPI
  self.dpi_scale_trans.clear().scale(dpi, dpi)
  self._mtx = np.identity(3)
  from numpy import eye
  File "<frozen importlib._bootstrap>", line 1609, in _handle_fromlist
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Update 2: Apparently there is a bug when using python 3.3 as doctorlove pointed out. I am now trying to use python 2.7 instead. Now it creates an mpeg-file but it cannot be played and it is only about ~150 kB big.

Update 3: Okay, so I tried the exact same code on my Win7 machine and it also works in python 3.3. But I have the same problem, I had earlier with python 2.7. The mpeg-file created cannot be played and is only a few hundred kB.

#! coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
time.clock()

def FFT(x,y):
    X = (x[-1]-x[0])/len(y)
    f = np.linspace(-2*np.pi/X/2,2*np.pi/X/2,len(y))
    F = np.fft.fftshift(np.fft.fft(y))/np.sqrt(len(y))
    return(f,F)

def FUNCTION(k_0,dx,c,t):
    y = np.exp(1j*k_0*(x-c*t))*np.exp(-((x-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
    k,F = FFT((x-c*t),y)
    return(x,y,k,F)

#Parameter
N = 1000
x   = np.linspace(0,30,N)
k_0 = 5
dx  = 1
c   = 1

l = [k_0,c,dx]

fig = plt.figure("Moving Wavepackage and it's FFT")
sub1 = plt.subplot(211)
sub2 = plt.subplot(212)
sub2.set_xlim([-10,10])
sub1.set_title("Moving Wavepackage and it's FFT")
sub1.set_ylabel("$Re[\psi(x,t)]$")
sub1.set_xlabel("$t$")
sub2.set_ylabel("$Re[\psi(k_x,t)]$")
sub2.set_xlabel("$k_x$")


n = 50
t = np.linspace(0,30,n)
img = []
for i in range(n):
    x,y,k,F = FUNCTION(k_0,dx,c,t[i]) 

    img.append(plt.plot(x,np.real(y),color="red", axes=plt.subplot(211)))
    img.append(plt.plot(k,np.real(F),color="red", axes=plt.subplot(212)))

ani = animation.ArtistAnimation(fig, img, interval=20, blit=True, repeat_delay=0)

ani.save('MovWave.mpeg', writer="ffmpeg")

print(time.clock())
plt.show()
like image 970
throwaway17434 Avatar asked Aug 02 '13 12:08

throwaway17434


People also ask

Can you animate Matplotlib?

Animations in Matplotlib can be made by using the Animation class in two ways: By calling a function over and over: It uses a predefined function which when ran again and again creates an animation. By using fixed objects: Some animated artistic objects when combined with others yield an animation scene.

How do I save as mp4 in Python?

To save this animation as an mp4 you can simply call ani. save() . If you just want to take a look at it before you save it call plt. show() instead.

How do you show an animation in Python?

You can create animations in Python by calling a plot function inside of a loop (usually a for-loop). The main tools for making animations in Python is the matplotlib. animation. Animation base class, which provides a framework around which the animation functionality is built.


1 Answers

You mentioned mencoder in your text, but not the code.

Matplotlib docs has a check for mencoder in a demo:

not_found_msg = """
The mencoder command was not found;
mencoder is used by this script to make an avi file from a set of pngs.
It is typically not installed by default on linux distros because of
legal restrictions, but it is widely available.
"""

try:
    subprocess.check_call(['mencoder'])
except subprocess.CalledProcessError:
    print "mencoder command was found"
    pass # mencoder is found, but returns non-zero exit as expected
    # This is a quick and dirty check; it leaves some spurious output
    # for the user to puzzle over.
except OSError:
    print not_found_msg
    sys.exit("quitting\n")
like image 50
doctorlove Avatar answered Sep 17 '22 12:09

doctorlove