简体   繁体   中英

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)

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM