Reputation: 27
I am trying to combine 4 images, image 1 on top left, image 2 on top right, image 3 on bottom left and image 4 on bottom right. However, my images are different sizes and not sure how to resize the images to same size. I am pretty new to Python and this is my first time using PIL.
I have this so far (after opening the images)
img1 = img1.resize(img2.size)
img1 = img1.resize(img3.size)
img1 = img1.resize(img4.size)
Upvotes: 1
Views: 1229
Reputation: 329
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 your case) 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)
To create advanced college make you can look into this: https://codereview.stackexchange.com/questions/275727/python-3-script-to-make-photo-collages
Upvotes: 1