Skip to content

Instantly share code, notes, and snippets.

@jgrahamc
Created August 8, 2019 11:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgrahamc/8b615ca48b2c89dc5a1a19a3bc5bfa17 to your computer and use it in GitHub Desktop.
Save jgrahamc/8b615ca48b2c89dc5a1a19a3bc5bfa17 to your computer and use it in GitHub Desktop.
Create a random photo collage from a directory of square photographs (all the same size)
# Makes a collage image from a directory full of images
#
# Assumes all the images are the same size and square
from os import listdir
from PIL import Image
import random
import math
images = listdir('.')
aspect = 1.77 # Aspect ratio of the output image
# Know cols * rows = len(images)
# Want cols = rows * aspect, multiply by cols
# => cols * cols = rows * cols * aspect, substitute len(images)
# => cols^2 = len(images) * aspect
# => cols = sqrt(len(images) * aspect)
cols = int(math.sqrt(len(images) * aspect))
rows = int(math.ceil(float(len(images))/float(cols)))
random.shuffle(images)
im = Image.open(images[0])
(w, h) = im.size
im.close()
(width, height) = (w*cols, h*rows)
collage = Image.new("RGB", (width, height))
for y in range(rows):
for x in range(cols):
i = y*cols + x
# Fill in extra images by duplicating some images randomly
if i >= len(images):
i = random.randrange(len(images))
p = Image.open(images[i])
collage.paste(p, (x*w,y*h))
im.close()
collage.save('collage.png')
collage.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment