Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imageio in python : compressing gif

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)

like image 914
kada Avatar asked Mar 31 '17 12:03

kada


1 Answers

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.

like image 145
Luca Cappelletti Avatar answered Nov 03 '22 03:11

Luca Cappelletti