Examples of how to overlay / superimpose two images using python and pillow
Table of contents
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
the above script will then return:
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
Links | Site |
---|---|
pillow | pillow doc |
paste() | pillow doc |
resize() | pillow dic |
How to merge a transparent png image with another image using PIL | stackoverflow |
Saving Image with PIL | stackoverflow |
How replace transparent with a color in pillow | stackoverflow |