daily pastebin goal
47%
SHARE
TWEET

full-color GIF fancy

a guest Feb 19th, 2013 242 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python2
  2.  
  3. import sys
  4. import os.path
  5. from PIL import Image
  6. from random import shuffle
  7.  
  8. # Color difference metric: sum of squares of channel differences
  9. def diff((r,g,b), (R,G,B)):
  10.     return (r - R)**2 + (g - G)**2 + (b - B)**2
  11.  
  12. # Get the input file path:
  13. _,path = sys.argv
  14. root, _ = os.path.splitext(path)
  15.  
  16. # Open input image:
  17. img = Image.open(path)
  18. dat = img.getdata()
  19. w,h = img.size
  20. col = list(set(dat))
  21. shuffle(col)
  22. rev = dict((rgb,i) for (i, rgb) in enumerate(col))
  23. idx = [ rev[rgb] for rgb in dat ]
  24. apr = [ 0 ] *len(col)
  25.  
  26. # Generate a list of output images:
  27. out = Image.new('P', img.size)
  28. nfr = (len(col) + 253)//255
  29. opt = {}
  30. for frame in range(nfr):
  31.     start = 255*frame + 1
  32.     end   = min(start + 255, len(col))
  33.     for i in range(start, end):
  34.         apr[i] = i
  35.         if frame < 1:  # number of frames to approximate all pixels
  36.             for j in range(end, len(col)):
  37.                 if diff(col[i], col[j]) < diff(col[apr[j]], col[j]):
  38.                     apr[j] = i
  39.     out.putpalette(sum(col[start - 1:end], tuple()))
  40.     out.putdata([ 0 if apr[i] < start else 1 + apr[i] - start for i in idx ])
  41.     out.save('%s-%04d.gif' % (root, frame), **opt)
  42.     opt['transparency'] = 0  # all frames except the first use transparency
  43.  
  44. # Since PIL doesn't support creating multi-frame GIF files, the resulting
  45. # files must be converted with another tool.  I used gifsicle.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top