Exemples de comment superposer deux images avec le module python pillow:
Superposer deux images de même taille
Pour superposer deux images de même taille on peut utiliser la fonction pillow paste(), exemple:
from PIL import Imageimport numpy as npimg = 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: pour rendre les pixels de couleurs blanche transparent on peut ajouter la ligne suivante
new_image = Image.new("RGBA", img.size, "WHITE")
Exemple de résultat: on veut superposer l'image de gauche sur l'image de droite
on obtient alors l'image suivante:
Superposer deux images de tailles différentes
Si les deux images ont des tailles différentes on peut utiliser la fonction resize(), exemple:
from PIL import Imageimport numpy as npimg = Image.open("data_mask_1354_2030.png")print(img.size)background = Image.open("background_730_1097.png")print(background.size)# resize the imagesize = (1354,2030)background = background.resize(size,Image.ANTIALIAS)background.paste(img, (0, 0), img)background.save('how_to_superimpose_two_images_02.png',"PNG")
Références
| Liens | 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 |
