I am using matplotlib to make an animation of the evolution of a system over time. I want to be able to save the animation as a file. My default choice is to save as an .mp4
file, which means I should use the ffmpeg
writer like this:
anim.save(filename="system_evolution.mp4", writer="ffmpeg", fps=30)
The problem is that I am sharing my code with my classmates who don't necessarily have ffmpeg
installed on their systems. In this case, I would like to fall back to saving a .gif
of the animation using pillow
(most of them install Python using Anaconda
so they probably have Pillow
installed as well). How can I check which writers are available to use for saving the animation?
I would like to have something like this:
if ffmpeg_available():
print("Saving system_evolution.mp4")
anim.save(filename="system_evolution.mp4", writer="ffmpeg", fps=30)
elif pillow_available():
print("Saving system_evolution.gif")
anim.save(filename="system_evolution.gif", writer="pillow", fps=30)
else:
print("Please install either ffmpeg to save a mp4 or pillow to save a gif.")
I couldn't figure out how to actually check if ffmpeg
or pillow
are available, which means the program crashes when I try to save an .mp4
and ffmpeg
isn't installed. How can this be checked?
According to this, the writers
object in this module has a method called is_available()
which can be used to check if a specific writer is available.
You can do sth like that
import matplotlib.animation as animation
def ffmpeg_available():
return animation.writers.is_available('ffmpeg')
def pillow_available():
return animation.writers.is_available('pillow')
if ffmpeg_available():
print("Saving system_evolution.mp4")
anim.save(filename="system_evolution.mp4", writer="ffmpeg", fps=30)
elif pillow_available():
print("Saving system_evolution.gif")
anim.save(filename="system_evolution.gif", writer="pillow", fps=30)
else:
print("Please install either ffmpeg to save a mp4 or pillow to save a gif.")