Need a function which takes n images as input forms a collage of pictures/photomontage

Question:

For n images, a collage of a picture should have produce n/2 rows and 2 columns.

I am new to Python. This is the code I have so far:

def create_collage(images):
    images = [io.imread(img) for img in images]
Asked By: rockstar

||

Answers:

This shall suffice your basic requirement. This shall suffice your basic requirement.

Steps:

Images are read and stored to list of arrays using io.imread(img) in a list comprehension.

We resize images to custom height and width.You can change IMAGE_WIDTH,IMAGE_HEIGHT as per your need with respect to the input image size.

You just have to pass the location of n images (n=4 for example) to the function.

If you are passing more than 2 images (for your case 4), it will work create 2 rows of images. In the top row, images in the first half of the list are stacked and the remaining ones are placed in bottom row using hconcat().

The two rows are stacked vertically using vconcat().

Finally, we convert the result to RGB image using image.convert("RGB") and is saved using image.save().

The code:

import cv2
from PIL import Image
from skimage import io

IMAGE_WIDTH = 1920
IMAGE_HEIGHT = 1080

def create_collage(images):
    images = [io.imread(img) for img in images]
    images = [cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT)) for image in images]
    if len(images) > 2:
        half = len(images) // 2
        h1 = cv2.hconcat(images[:half])
        h2 = cv2.hconcat(images[half:])
        concat_images = cv2.vconcat([h1, h2])
    else:
        concat_images = cv2.hconcat(images)
    image = Image.fromarray(concat_images)

    # Image path
    image_name = "result.jpg"
    image = image.convert("RGB")
    image.save(f"{image_name}")
    return image_name
images=["image1.png","image2.png","image3.png","image4.png"]
#image1 on top left, image2 on top right, image3 on bottom left,image4 on bottom right
create_collage(images)
Answered By: Ayush Raj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.