Skip to content

Instantly share code, notes, and snippets.

@jgrahamc
Created August 8, 2019 11:53
Show Gist options
  • Select an option

  • Save jgrahamc/8b615ca48b2c89dc5a1a19a3bc5bfa17 to your computer and use it in GitHub Desktop.

Select an option

Save jgrahamc/8b615ca48b2c89dc5a1a19a3bc5bfa17 to your computer and use it in GitHub Desktop.

Revisions

  1. jgrahamc created this gist Aug 8, 2019.
    42 changes: 42 additions & 0 deletions collage.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    # 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()