How to overlay / superimpose two images using python and pillow ?

Published: April 16, 2019

DMCA.com Protection Status

Examples of how to overlay / superimpose two images using python and pillow

Overlay two images of same size

To overlay two images in python, a solution is to use the pillow function paste(), example:

from PIL import Image

import numpy as np

img = Image.open("data_mask_1354_2030.png")

background = Image.open("background_1354_2030.png")

background.paste(img, (0, 0), img)
background.save('how_to_superimpose_two_images_01.png',"PNG")

Note: to make white pixels transparent a solution is to add the following line:

new_image = Image.new("RGBA", img.size, "WHITE")

Example of result: overlay the left image to the right image

How to overlay / superimpose two images using python and pillow ? How to overlay / superimpose two images using python and pillow ?
How to overlay / superimpose two images using python and pillow ?

the above script will then return:

How to overlay / superimpose two images using python and pillow ? How to overlay / superimpose two images using python and pillow ?
How to overlay / superimpose two images using python and pillow ?

Overlay two images of different size

If the two images have different size, a solution is to use resize(), example:

from PIL import Image

import numpy as np

img = Image.open("data_mask_1354_2030.png")

print(img.size)

background = Image.open("background_730_1097.png")

print(background.size)

# resize the image
size = (1354,2030)
background = background.resize(size,Image.ANTIALIAS)

background.paste(img, (0, 0), img)
background.save('how_to_superimpose_two_images_02.png',"PNG")

References