Created
March 28, 2019 15:32
-
-
Save njanakiev/1932e0a450df6d121c05069d5f7d7d6f to your computer and use it in GitHub Desktop.
Concat images in a matrix grid with Python and PIL
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
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') |
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
hello sir i have total 55 images in a folder and want to concatenate all in single image