Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an animation out of Matplotlib .pngs

Hello I just finished to write a code that compute the orbitals of the hydrogen atom. I wrote a for loop to create 300 pictures using the command

plt.savefig("image{i}.png".format(i=i))

Now I wanted to ask what is the easiest way to create a high quality .mp4 or .gif file out of the pictures using python. I saw several tutorials that didn't helped me because the gif was messed up or the quality was too low.

Thank you for your support

like image 324
Phicalc Avatar asked Oct 18 '25 03:10

Phicalc


2 Answers

The easiest I know is to use imageio's mimwrite.

import imageio
ims = [imageio.imread(f) for f in list_of_im_paths]
imageio.mimwrite(path_to_save_gif, ims)

There are obvious options such as duration, number of loops, etc.
And some other options you can read about in the documentation by using imageio.help('gif').

Hope that helps.

like image 175
ShlomiF Avatar answered Oct 20 '25 17:10

ShlomiF


The faster way is to use imageio as in @ShlomiF's answer, but you can do the same thing with pure matplotlib if you so prefer:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

nframes = 25
plt.subplots_adjust(top=1, bottom=0, left=0, right=1)

def animate(i):
    im = plt.imread('image'+str(i)+'.png')
    plt.imshow(im)

anim = FuncAnimation(plt.gcf(), animate, frames=nframes, 
                     interval=(2000.0/nframes))
anim.save('output.gif', writer='imagemagick')

But if your first priority is the quality of the output you may want to consider using ffmpeg and convert directly,

ffmpeg -f image2 -i image%d.png output.mp4
ffmpeg -i output.mp4 -vf "fps=10,scale=320:-1:flags=lanczos" -c:v pam -f \ 
    image2pipe - | convert -delay 10 - -loop 0 -layers optimize output.gif

Changing the scale argument as needed to control the size of the final output, scale=-1:-1 leaves the size unchanged.

like image 40
William Miller Avatar answered Oct 20 '25 17:10

William Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!