Skip to content

Instantly share code, notes, and snippets.

@jelofsson
Created April 20, 2024 08:24
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 jelofsson/f997cfe1b990db8efa3e7d0039a69d89 to your computer and use it in GitHub Desktop.
Save jelofsson/f997cfe1b990db8efa3e7d0039a69d89 to your computer and use it in GitHub Desktop.
Generates an mosaic image based on images in path
#
# example usage:
# python3 mosaic.py <source-path> <x-size> <y-size> <images-per-row> <spacing>
# python3 mosaic.py ./images/ 512 512 8 0
#
import os
import sys
from PIL import Image, ImageDraw
# source path
image_dir = sys.argv[1]
# read images size from argv:
image_size = (int(sys.argv[2]), int(sys.argv[3]))
# read images per row from argv:
images_per_row = int(sys.argv[4])
# read spacing from argv:
spacing = int(sys.argv[5])
def create_mosaic(image_dir, output_path, image_size, images_per_row, spacing):
# Get list of all image files in the directory
images = [
f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))
]
# Sort the images by filename
images.sort()
# Open images and resize them
images = [
Image.open(os.path.join(image_dir, img)).resize(image_size) for img in images
]
# Calculate dimensions of the mosaic
total_rows = len(images) // images_per_row + (len(images) % images_per_row > 0)
total_width = (image_size[0] + spacing) * images_per_row - spacing
total_height = (image_size[1] + spacing) * total_rows - spacing
# Create new image object for the mosaic
mosaic = Image.new("RGB", (total_width, total_height), "white")
# Paste images into the mosaic
for i, img in enumerate(images):
row = i // images_per_row
col = i % images_per_row
mosaic.paste(
img, ((image_size[0] + spacing) * col, (image_size[1] + spacing) * row)
)
# print number onto image
# draw = ImageDraw.Draw(mosaic)
# draw.text((col * image_size[0], row * image_size[1]), str(i+1), fill=(255,255,255))
# Save the mosaic image
mosaic.save(output_path)
# Usage
create_mosaic(image_dir, "mosaic.png", image_size, images_per_row, spacing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment