Image Overlaying in Python with Pillow

Pillow – Image Overlaying

Overlaying is the process of placing one image on top of another.

To overlay an image over a base image in Python with Pillow library, you can use Image.paste() method.

Pillow - Image Overlaying

In this tutorial, you will learn how to use Image.paste() to over an image over another.

Steps to overlay image

The steps to overlay an image over another image with Pillow are

  1. Import Image module from Pillow library.
  2. Read the two input images using Image.open() function, say base_img and overlay_img.
  3. Convert the overlay image to RGBA mode using Image.convert() function.
  4. Define the position where the overlay image will be pasted on the base image. This must be a tuple of (x position, y position).
  5. Overlay the image over base image using Image.paste() method. The base image object is modified with the resulting image.
  6. Save the base image to required location using Image.save() function.

Examples

1. Overlay an image on given image

In the following example, we read two images: test_image.jpg and test_image_house.jpg, and overlay the second image on the first image.

We save the resulting image to a file overlayed_image.jpg.

Python Program

from PIL import Image

# Open the base and overlay images
base_img = Image.open('test_image.jpg')
overlay_img = Image.open('test_image_house.jpg')

# Convert the overlay image to RGBA mode
overlay_img = overlay_img.convert('RGBA')

# Define the position where the overlay image will be pasted
position = (200, 100)

# Overlay the image over base image
base_img.paste(overlay_img, position, overlay_img)

# Save the resulting image
base_img.save('overlayed_image.jpg')
Copy

Input Images

base_img

Base image for Image Overlaying with Pillow

overlay_img

Overlay image for Image Overlaying with Pillow

overlayed_image.jpg

Resulting image for Image Overlaying with Pillow

You may change the position, or change the size of the overlay image to get the desired results.

Summary

In this Python Pillow Tutorial, we learned how to overlay an image on a base image using PIL.Image.paste() function, with the help of examples.

Related Tutorials

Code copied to clipboard successfully 👍