Skip to content

Instantly share code, notes, and snippets.

@fogleman
Created May 24, 2016 13:47
Show Gist options
  • Save fogleman/baa06e6917acd7b9d41ecc193ba9f2fa to your computer and use it in GitHub Desktop.
Save fogleman/baa06e6917acd7b9d41ecc193ba9f2fa to your computer and use it in GitHub Desktop.
Wigglegrams
from PIL import Image, ImageChops, ImageDraw
import os
def load_images(folder):
result = []
for name in os.listdir(folder):
path = os.path.join(folder, name)
print path
im = Image.open(path)
result.append(im)
return result
def score(im1, im2, box1, box2):
im1 = im1.crop(box1)
im2 = im2.crop(box2)
im = ImageChops.difference(im1, im2)
h = im.histogram()
r = sum([x * i * i for i, x in enumerate(h[:256])]) ** 0.5
g = sum([x * i * i for i, x in enumerate(h[256:512])]) ** 0.5
b = sum([x * i * i for i, x in enumerate(h[512:])]) ** 0.5
return (r + g + b) / 3
def align_pair(im1, im2, box):
l, t, r, b = box
scores = []
n = 64
for dy in range(-n, n + 1):
for dx in range(-n, n + 1):
s = score(im1, im2, box, (l + dx, t + dy, r + dx, b + dy))
scores.append((s, dx, dy))
s, dx, dy = min(scores)
print dx, dy, s
return dx, dy
def align(ims, box):
im1, ims = ims[0], ims[1:]
result = [im1]
minx = 0
miny = 0
for im2 in ims:
dx, dy = align_pair(im1, im2, box)
minx = min(minx, dx)
miny = min(miny, dy)
w, h = im2.size
im2 = im2.crop((dx, dy, w, h))
result.append(im2)
w = min(im.size[0] for im in result)
h = min(im.size[1] for im in result)
result = [im.crop((-minx, -miny, w, h)) for im in result]
return result
def main():
ims = load_images('desk')
w, h = ims[0].size
box = (w / 2 - 32, h / 2 - 32, w / 2 + 32, h / 2 + 32)
# box = (1400, 2000, 1600, 2400)
ims = align(ims, box)
for i, im in enumerate(ims):
im.save('im%d.jpg' % i, 'JPEG')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment