20

Is there a way to compress the gif while making it with imageio in python? I am making gif with about 200 images and the final file is 30MB. I would prefer if it is 5-10 MB. Anyway the images are mono-colour so should be fine to compress. Is there a tool I can use or specify it with imageio ?

Here is my code to make gif :

    import os
    import imageio as io
    import re
    
    # Key to sort the file_names in order
    numbers = re.compile(r'(\d+)')
    def numericalSort(value):
        parts = numbers.split(value)
        parts[1::2] = map(int, parts[1::2])
        return parts
    

    file_names = sorted((fn for fn in os.listdir('.') if fn.startswith('timestamp_')), key = numericalSort)
    

    # GIF writer
    with io.get_writer('output_gif.gif', mode='I', duration=0.1) as writer:
        for filename in file_names:
            image = io.imread(filename)
            writer.append_data(image)

jkhadka
  • 2,443
  • 8
  • 34
  • 56

2 Answers2

8

Faced the very same problem, I've created a wrapper for gifsicle library called pygifsicle and one can use it as follows:

from pygifsicle import optimize
optimize("path_to_my_gif.gif")

As every other package on pip, one can install it by running:

pip install pygifsicle

A full example for using this library is available in the imageio documentation.

While installing pygifsicle you will automatically install also, if you are on MacOS, the gifsicle library using Brew. For the other systems, a step-by-step guide will be provided, which it basically just asks to install the library via apt-get on Debian / Ubuntu (since it seems a good idea to not ask for sudo within the package setup):

sudo apt-get install gifsicle

Or on windows you can install one of the available ports.

Luca Cappelletti
  • 2,485
  • 20
  • 35
  • Hey, cool solution, I have not tested this yet but I will try it, thanks a lot for making this! – jkhadka Feb 24 '20 at 10:58
  • hi, i actually noticed that this is increasing, rather than decreasing my file size... Initally, test.gif==13M. After running `pygifsicle.optimize("test.gif")`, test.gif==23M – Avi Vajpeyi Aug 04 '20 at 11:21
  • 1
    Hello @AviVajpeyi, pygifsicle offers bindings to the [gifsicle](https://www.lcdf.org/gifsicle/) library, which often is able to compress the images. In my test cases, the library is always effective, but I suppose that there are cases where the compression algorithm fails. I would suggest you open a pull request with this case [in their github repository](https://github.com/kohler/gifsicle). – Luca Cappelletti Aug 04 '20 at 13:37
  • @LucaCappelletti how to add other gifsice options like `lossy` to `optimize` function? – Jimson James Mar 02 '21 at 15:18
  • Hello @JimsonKannantharaJames, please do open an issue on the documentation of the repository for this sort of question, so that we may explore it there. – Luca Cappelletti Mar 03 '21 at 14:20
  • Holy guacamoly, this saved my like 60%! Much wow ;) seriously, the compression is quite good. – Marco Apr 11 '21 at 18:40
  • Do say thanks to the authors at gifsicle, mine is just a wrapper! – Luca Cappelletti Apr 11 '21 at 18:57
  • FileNotFoundError: The gifsicle library was not found on your system. On MacOS it is automatically installed using brew when you use the pip install command. On other systems, like Linux systems and Windows, it prompts the instructions to be followed for completing the installation. You can learn more on how to install gifsicle on the gifsicle and pygifsicle documentation. – Feraru Silviu Marian Sep 08 '21 at 14:33
  • Yeah, @FeraruSilviuMarian that is the extremely explicative error that my library provides when you do not have the Gifsicle library installed. In my answer, there are the instructions for Ubuntu, macOS and Windows. What problem are you encountering? Possibly you should ask a question about it. – Luca Cappelletti Sep 08 '21 at 15:04
  • It is increasing the gif size. Can we pass any additional parameters to this function? – Osama Bin Saleem Jan 04 '23 at 10:51
1

Another method is to resize and reduce the quality of an image before you create the gif.

from PIL import Image
# Resizing
image.resize((x, y), Image.ANTIALIAS)
# Reducing Quality
quality_val = 90
image.save(filename, 'JPEG', quality=quality_val)

Full code for turning images into compressed gif

from PIL import Image
import glob
x = 250
y = 250
fp_in = 'path/to/images'
fp_in = 'path/to/gif/output'
q = 50 # Quality
img, *imgs = [Image.open(f).resize((x,y),Image.ANTIALIAS) for f in sorted(glob.glob(fp_in))] 
img.save(fp=fp_out, format='GIF', append_images=imgs,quality=q, 
         save_all=True, duration=15, loop=0, optimize=True)
HarriS
  • 605
  • 1
  • 6
  • 19