Created
August 8, 2019 11:53
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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