Using Python to make an animated gif from static images

As part of a collection of visualisations related to Covid-19, I’ve been making a weekly-ish animated map of Covid-19 case rates in English upper tier local authorities.

I’ve been doing this by munging the weekly surveillance data from Public Health England in R, and then generating an image for each week. I then take the data into Photoshop, and make the gif.

The problem with this process is that Photoshop is extremely resource-hungry. I typically need to shut everything else down, and even then, making the gif is hit and miss as to whether it works or not.

I figured there must be a better way to do this, and started to look for something that I could script – firstly in R, and then in Python.

R led me down a few dead-ends, so I started to look at Python, and that’s when I came across PIL – a library designed for image manipulation, which also has the ability to make gifs.

The code itself is fairly straightforward – the tricky part is actually producing the images in the first place, and that may be a blog post for another day. Here’s the code to get a collection of png images, and turn them into a gif.

I’ve annotated the code to show what each section does – hopefully this is all the explanation needed to get someone else started if they’re trying to do the same.

From my point of view, this has turned a task from an hour or two of frustration each week, to less than a minute – so well worth doing!