Python Pillow - Concatenating two Images



Concatenating two images with Pillow typically refers to combining or joining two separate images to create a single image either horizontally or vertically. This process allows us to merge the content of the two images into a larger image.

Pillow is a Python Imaging Library (PIL) which provides various methods and functions to perform image manipulation including image concatenation. When concatenating images we can choose to stack them on top of each other vertical concatenation or place them side by side horizontal concatenation.

There are no direct methods in pillow to concatenate the images but we can perform that by using the paste() method in python.

Here is a step-by-step guide on how to perform concatenation of two Images.

  • Import the necessary modules.

  • Load the two images that we want to concatenate.

  • Decide whether we want to concatenate the images horizontally or vertically.

  • Save the concatenated image to a file.

  • Optionally we can display the concatenated image. This step is useful for visualizing the result but it's not required.

Following is the input images used in all the examples of this chapter.

butterfly original image flowers

Example

In this example we are concatenating two input images horizontally.

from PIL import Image
image1 = Image.open("Images/butterfly.jpg")
image2 = Image.open("Images/flowers.jpg")
result = Image.new("RGB", (image1.width + image2.width, image1.height))
result.paste(image1, (0, 0))
result.paste(image2, (image1.width, 0))
result.save("output Image/horizontal_concatenated_image.png")
result.show()

Output

horizontal concatenated

Example

Here in this example we are concatenating the given two input images vertically.

from PIL import Image
image1 = Image.open("Images/butterfly.jpg")
image2 = Image.open("Images/flowers.jpg")
result = Image.new("RGB", (image1.width, image1.height + image2.height))
result.paste(image1, (0, 0))
result.paste(image2, (0, image1.height))
result.save("output Image/vertical_concatenated_image.png")
result.show()

Output

vertical concatenated
Advertisements