Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a video from array of images in matplotlib?

I have a couple of images that show how something changes in time. I visualize them as many images on the same plot with the following code:

import matplotlib.pyplot as plt
import matplotlib.cm as cm

img = [] # some array of images
fig = plt.figure()
for i in xrange(6):
    fig.add_subplot(2, 3, i + 1)
    plt.imshow(img[i], cmap=cm.Greys_r)

plt.show()

and get something like:enter image description here

Which is ok, but I would rather animate them to get something like this video. How can I achieve this with python and preferably (not necessarily) with matplotlib

like image 794
Salvador Dali Avatar asked Jan 24 '16 12:01

Salvador Dali


2 Answers

For a future myself, here is what I ended up with:

def generate_video(img):
    for i in xrange(len(img)):
        plt.imshow(img[i], cmap=cm.Greys_r)
        plt.savefig(folder + "/file%02d.png" % i)

    os.chdir("your_folder")
    subprocess.call([
        'ffmpeg', '-framerate', '8', '-i', 'file%02d.png', '-r', '30', '-pix_fmt', 'yuv420p',
        'video_name.mp4'
    ])
    for file_name in glob.glob("*.png"):
        os.remove(file_name)
like image 132
Salvador Dali Avatar answered Sep 30 '22 20:09

Salvador Dali


Another solution is to use AnimationArtist from matplotlib.animation as described in the animated image demo. Adapting for your example would be

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.animation as animation

img = [] # some array of images
frames = [] # for storing the generated images
fig = plt.figure()
for i in xrange(6):
    frames.append([plt.imshow(img[i], cmap=cm.Greys_r,animated=True)])

ani = animation.ArtistAnimation(fig, frames, interval=50, blit=True,
                                repeat_delay=1000)
# ani.save('movie.mp4')
plt.show()
like image 31
Keith Prussing Avatar answered Sep 30 '22 19:09

Keith Prussing