Sushil
Sushil

Reputation: 5531

How to overlay only the needed image?

I have two images.

Image 1:

enter image description here

Image 2:

enter image description here

Both the images have the same resolution. I want to overlay the second image on the first image.

This is what I tried:

from PIL import Image

img1 = Image.open("D:\\obj1__0.png")
img1 = img1.convert("RGBA")
img1 = img1.resize((640,360))

img2 = Image.open('D:\\Renderforest_Watermark.png')
img2 = img2.convert("RGBA")
img2 = img2.resize((640,360))

new_img = Image.blend(img1,img2,0.7)
new_img.save("D:\\Final.png")

Output:

enter image description here

My Question: How do I overlay image 2 on image 1 such that only the watermark is overlaid?

P.S: I already searched for this on Stack Overflow, but couldn't find any answers.

Upvotes: 1

Views: 356

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207445

Your overlay image is incorrectly formed. It should be transparent where it is white. It has no transparency, so it isn't see-through. I can only suggest to make a synthetic alpha channel by guessing that it should be transparent where the overlay image is white:

#!/usr/bin/env python3

from PIL import Image

# Set a common size
size = (640, 360)

# Load background and overlay, removing the pointless alpha channel and resizing to a common size
bg = Image.open('background.png').convert('RGB').resize(size)
overlay = Image.open('overlay.png').convert('RGB').resize(size)

# Try and invent a mask by making white pixels transparent
mask = overlay.convert('L')
mask = mask.point(lambda p: 255 if p < 225 else 0)

# Paste overlay onto background only where the mask is, then save
bg.paste(overlay, None, mask)
bg.save('result.png')

enter image description here


If your image did have an alpha channel, you would avoid deleting the original alpha channel and open it like this instead:

overlay = Image.open('overlay.png').resize(size)

then delete these lines:

# Try and invent a mask by making white pixels transparent
mask = overlay.convert('L')
mask = mask.point(lambda p: 255 if p < 225 else 0)

then change the line after the above to:

# Paste overlay onto background only where the mask is, then save
bg.paste(overlay, None, overlay)

Keywords: Image processing, PIL, Pillow, overlay, watermark, transparent, alpha.

Upvotes: 2

Related Questions