Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change opacity of image and merge with another image in Python

I've been looking up on how to put two picture together, turning the top one to around 50% transparent.

So far, I managed to find this:

from PIL import Image

def merge():
    background = Image.open("ib.jpg")
    background = background .convert('L') #only foreground color matters
    foreground = Image.open("if.jpg")

    background.paste(foreground, (0, 0), foreground)
    background.show()

But it only outputs a blank image.

Both are same sizes.

ib.jpg:

ib.jpg

if.jpg:

if.jpg

desired output:

enter image description here

Any tips for a way to do this either with a RGB or RGBA file? I should be dealing with both types (some, in fact, have alpha layer).

Thanks,

like image 573
fabda01 Avatar asked Jun 15 '16 21:06

fabda01


People also ask

How do I overlay one image to another in python?

Firstly we opened the primary image and saved its image object into variable img1. Then we opened the image that would be used as an overlay and saved its image object into variable img2. Then we called the paste method to overlay/paste the passed image on img1.


1 Answers

You have to use blend function from PIL.Image:

from PIL import Image
bg = Image.open("1.jpg")
fg = Image.open("2.jpg")
# set alpha to .7
Image.blend(bg, fg, .7).save("out.png")

enter image description here

like image 102
Serenity Avatar answered Sep 27 '22 22:09

Serenity