Skip to content

Instantly share code, notes, and snippets.

@homm
Last active December 15, 2015 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save homm/5233715 to your computer and use it in GitHub Desktop.
Save homm/5233715 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from PIL import Image
from timeit import repeat
def prepare_test_images(dim):
"""Plese, be careful with dim > 32. Result image is have dim ** 4 pixels
(i.e. 1Mpx for 32 dim or 4Gpx for 256 dim).
"""
i1 = bytearray(dim ** 4 * 2)
i2 = bytearray(dim ** 4 * 2)
res = 255.0 / (dim - 1)
rangedim = range(dim)
pos = 0
for l1 in rangedim:
for l2 in rangedim:
for a1 in rangedim:
for a2 in rangedim:
i1[pos] = int(res * l1)
i1[pos + 1] = int(res * a1)
i2[pos] = int(res * l2)
i2[pos + 1] = int(res * a2)
pos += 2
print '%s of %s' % (l1, dim)
i1 = Image.frombytes('LA', (dim ** 2, dim ** 2), bytes(i1))
i2 = Image.frombytes('LA', (dim ** 2, dim ** 2), bytes(i2))
return i1.convert('RGBA'), i2.convert('RGBA')
im1, im2 = prepare_test_images(8)
im1.save('im1.png')
im2.save('im2.png')
im1, im2 = Image.open('im1.png'), Image.open('im2.png')
im1.load(), im2.load()
print repeat(lambda: Image.alpha_composite(im1, im2), number=1)
out2 = Image.alpha_composite(im1, im2)
out2.save('out2.png')
#!/usr/bin/env python
import sys
from PIL import Image, ImageMath
def chanel_diff(c1, c2):
return ImageMath.eval('127 + c1 - c2', c1=c1, c2=c2).convert('L')
def highlight(c):
return c.point(lambda c: c if 126 <= c <= 128 else 127 + (c - 127) * 10)
im1 = Image.open(sys.argv[1])
im2 = Image.open(sys.argv[2])
diff = map(chanel_diff, im1.split(), im2.split())
if len(sys.argv) >= 4:
highlight(Image.merge('RGB', diff[:-1])).save('%s.png' % sys.argv[3])
highlight(diff[-1]).convert('RGB').save('%s.alpha.png' % sys.argv[3])
def stats(ch):
return sorted((c, n) for n, c in ch.getcolors())
for ch, stat in zip(['red ', 'grn ', 'blu ', 'alp '], map(stats, diff)):
print ch, ' '.join('{}: {:>5}'.format(c, n) for c, n in stat)
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment