Skip to content

Instantly share code, notes, and snippets.

@njanakiev
Created March 28, 2019 15:32
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save njanakiev/1932e0a450df6d121c05069d5f7d7d6f to your computer and use it in GitHub Desktop.
Save njanakiev/1932e0a450df6d121c05069d5f7d7d6f to your computer and use it in GitHub Desktop.
Concat images in a matrix grid with Python and PIL
import os
import random
from PIL import Image, ImageOps
def concat_images(image_paths, size, shape=None):
# Open images and resize them
width, height = size
images = map(Image.open, image_paths)
images = [ImageOps.fit(image, size, Image.ANTIALIAS)
for image in images]
# Create canvas for the final image with total size
shape = shape if shape else (1, len(images))
image_size = (width * shape[1], height * shape[0])
image = Image.new('RGB', image_size)
# Paste images into final image
for row in range(shape[0]):
for col in range(shape[1]):
offset = width * col, height * row
idx = row * shape[1] + col
image.paste(images[idx], offset)
return image
# Get list of image paths
folder = 'images'
image_paths = [os.path.join(folder, f)
for f in os.listdir(folder) if f.endswith('.jpg')]
# Random selection of images
image_array = random.choices(image_paths, k=8)
# Create and save image grid
image = concat_images(image_array, (300, 300), (2, 4))
image.save('image.jpg', 'JPEG')
@k1ranss
Copy link

k1ranss commented Mar 29, 2022

hello sir i have total 55 images in a folder and want to concatenate all in single image

@k1ranss
Copy link

k1ranss commented Mar 29, 2022

how can i modify canvas size

Create canvas for the final image with total size

shape = shape if shape else (1, len(images))
image_size = (width * shape[1], height * shape[0])
image = Image.new('RGB', image_size)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment