user3598726 user3598726 - 2 months ago 11
Python Question

Empty .mp4 file created after making video from matplotlib using matplotlib.animation

I found this little code, and I am able to save a video (random colors changing in a grid) using it:

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import rand

Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='xy'), bitrate=3600)

fig = plt.figure()
frames = []
for add in np.arange(15):
base = rand(10, 10)
frames.append((plt.pcolormesh(base, ),))

im_ani = animation.ArtistAnimation(fig, frames, interval=500, repeat_delay=3000,
blit=True)
im_ani.save('Vid.mp4', writer=writer)


I tried to insert it into my simulation, I get no errors, but the video is empty, the whole picture is white. Can you help me with that? This is the simplest case where I got it:

class Dummy():

def __init__(self):
self.video=[]

def addFrame(self):

Frame=rand(10,10)
print (Frame)
self.video.append((plt.pcolormesh(Frame),))

def saveVideo(self):

Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
fig = plt.figure()

im_ani = animation.ArtistAnimation(fig, self.video, interval=500, repeat_delay=3000,
blit=True)
im_ani.save('myVid.mp4', writer=writer, dpi=dpi)


You can try it out:

from scipy import rand

foo=Dummy()

for i in range(20):
foo.addFrame()

foo.saveVideo()

DJV DJV
Answer

Your self.video.append((plt.pcolormesh(Frame),)) line is fine. You just changed the order of statements.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np


class Dummy():
    def __init__(self, fname):
        self.fname = fname
        self.video = []
        self.fig, self.ax = plt.subplots()  # Create new figure here

    def addFrame(self):
        Frame = np.random.rand(10, 10)
        self.video.append((self.ax.pcolormesh(Frame), ))

    def saveVideo(self):
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
        im_ani = animation.ArtistAnimation(self.fig, self.video, interval=500,
                                           repeat_delay=3000, blit=True)
        im_ani.save(self.fname, writer=writer)


foo1 = Dummy('foo1.mp4')
for i in range(20):
   foo1.addFrame()
foo1.saveVideo()

foo2 = Dummy('foo2.mp4')
for i in range(40):
   foo2.addFrame()
foo2.saveVideo()
Comments