Search code examples
pythonimageiogif

How to Read and Write gifs in python, PIL and imageio don't seem to work


I've been trying for about a day now to read gif files for an image viewer in python but nothing has worked. Most files load fine, but some retain artifacts from the image frames being incorrectly processed. From what I've read, it seems to have something to do with PIL's management of transparency and/or its way of converting between RGBA and PA image modes. The simplest example of simply loading and then saving the gif with imageio is shown below.

import imageio
gif = imageio.mimread("test.gif")
imageio.mimwrite("out.gif", gif)

which is analogous to this with PIL:

from PIL import Image

gif = Image.open("test.gif")
gif.save("out.gif", save_all=True)

Both produce the same result, which is not surprising as imageio is dependent on PIL

I've tried every combination of commands and arguments that I could find that looked like they may help, like manually setting the palette and transparency, and using the different "disposal" values to change the way the frames are combined. I've also tried using seek() to extract all the frames into an array and created a gif from them, but it seems that PIL is just not capable of properly parsing some GIFs. Here is an example input and output: (The second gif's color palette has been compressed to get it under 2MB but it is a negligible difference if any)

input gif output gif


Solution

  • I quite convinced that your test image does not fully respect the GIF standard: even some image viewer don't show the correct animation (however it does display correctly in all browsers I've tested). This could explain that you notice the problem for only a few of your test images.

    To check this intuition, I extracted all frames, and use them to regenerate the animation in a new GIF file (many software exist for such a task, you may even use some online web sites for this). And guess what ? This new file didn't show any problem with PIL.