Search code examples
pythonmatplotlibpython-imaging-library

PIL creates GIFs with less images than the input, despite save_all=True


I was trying to make plots using matplotlib into GIFs for further analysis, when during the analysis I noticed that the output of the analysis consisted of less images than expected. I created and saved 3956 plots with axes turned off (this would make my analysis simpler) then proceeded to create GIFs in the easiest way I found, using PIL, I opened the images to a list, then sorted the list into 2 further lists of 1978 images, then used im.save with save_all=True and append_images=im[1:]. The code ran without an issue and the GIFs opened normally. It was during the further analysis I noticed something was up and I confirmed it later using GIMP that the two output GIFs had 1798 and 1784 images only, instead of the 1978 I used to create them.

The opening of the images shouldn't be the problem as the opened image lists both have lengths of 1978, the problem has to happen with the code:

imS[0].save( "filename.gif",
save_all=True,
append_images=imS[1:],
duration=250,
loop=0)

I tried using multiple image formats, tried changing the duration, tried changing the "interlace" and "optimize" options in im.save(), deleting and reinstalling the PIL module, none of them changed the result. I thought that there might be an issue with consecutive images being empty (Each image is supposed to show data in a unit time and there are intervals with no data so that's where the empty images come from) and some compression is deleting the multiple empty images but this clearly isn't the case after eyeballing the GIFs. That's where I'm stuck


Solution

  • I do not have enough reputation to make this a comment, so I respond without solving the issue completely, sorry for that.

    I was running into the same issue until now. Does your list of frames contain duplicates or very similar frames? In this git issue it is outlined that it is intended behaviour from pillow to remove these duplicates. Here they explicitly state:

    Removing duplicate consecutive frames is intended to be a feature, reducing file size without affecting the visual output.

    Currently, I am also stuck with this and cannot find a solution as the workarounds from the git issue do not work anymore. My workaround is to create a list of pngs in python and then compose them using ImageMagick.