Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- import sys
- import os.path
- from PIL import Image
- from collections import Counter
- # Get the input file path:
- _,path = sys.argv
- root, _ = os.path.splitext(path)
- # Open input image:
- img = Image.open(path)
- dat = img.getdata()
- w,h = img.size
- col = [ rgb for (rgb, cnt) in Counter(dat).most_common() ]
- rev = dict((rgb,i) for (i, rgb) in enumerate(col))
- idx = [ rev[rgb] for rgb in dat ]
- # Generate a list of output images:
- out = Image.new('P', img.size)
- nfr = (len(col) + 253)//255
- opt = {}
- for frame in range(nfr):
- start = 255*frame + 1
- end = min(start + 255, len(col))
- out.putpalette(sum(col[start - 1:end], tuple()))
- out.putdata([ 1 + i - start if start <= i < end else 0 for i in idx ])
- out.save('%s-%04d.gif' % (root, frame), **opt)
- opt['transparency'] = 0 # all frames except the first use transparency
- # Since PIL doesn't support creating multi-frame GIF files, the resulting
- # files must be converted with another tool. I used gifsicle.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement