Combine Images to One Image Horizontally and Vertically Using Python Pillow: A Step Guide – Pillow Tutorial

By | August 30, 2020

Python Pillow allows us to combine some images with different sizes to one big imge. In this tutorial, we will use some examples to illustrate you how to combine images horizontally and vertically.

Preliminary

We will combine three images with different size.

from PIL import Image
imgs = [r'G:\0.png', r'G:\1.png', r'G:\2.png']


Get the total width, total height, maximum width and maximum height

In order to combine images correctly, we should get these value. Here is an example:

total_width = 0
total_height = 0
max_width = 0
max_height = 0
ix =[]
for img in imgs:
im = Image.open(img)
size = im.size
w = size[0]
h = size[1]
total_width += w
total_height += h

if h > max_height:
max_height = h
if w > max_width:
max_width = w
ix.append(im)
print((total_width, total_height, max_width, max_height))

Then we will get the result:

(1356, 984, 452, 534)

We will combine images using pillow now.

Combine images vertically

We should create a new images to save images we plan to combine.

target_vertical = Image.new('RGB', (max_width, total_height))

Then we will combine these images vertically.

pre_w = 0
pre_h = 0
for img in ix:
target_vertical.paste(img, (pre_w, pre_h, pre_w+max_width, pre_h + img.size[1]))
pre_h += img.size[1]
target_vertical.show()
target_vertical.save('vertical.png', quality=100)

The combined image is:

We also can combine these images horizontally.

Combine images horizontally

We also should create a new image to save images. Here is an example:

target_horizon = Image.new('RGB', (total_width, max_height))

pre_w = 0
pre_h = 0
for img in ix:
target_horizon.paste(img, (pre_w, pre_h, pre_w+img.size[0], pre_h + img.size[1]))
pre_w += img.size[0]
target_horizon.show()
target_horizon.save('horizon.png', quality=100)

Run this code, we should get the image:

You must notice:

When you are using pillow Image.paste() function, the box of parameter shoud be the size of image, otherwise you may get the ValueError: images do not match error.

For example, when combining images horizontally.

target_horizon.paste(img, (pre_w, pre_h, pre_w+img.size[0], pre_h + img.size[1]))

The box = (pre_w, pre_h, pre_w+img.size[0], pre_h + img.size[1])

the size of box is (img.size[0], img.size[1]), which is the size of image.