Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check which writers are available for saving an animation in matplotlib?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading