Created
April 20, 2024 08:24
-
-
Save jelofsson/f997cfe1b990db8efa3e7d0039a69d89 to your computer and use it in GitHub Desktop.
Generates an mosaic image based on images in path
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
# | |
# 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