Zax
Zax

Reputation: 199

Pillow - Adding transparency depending on grayscale values

Based on this post: Converting image grayscale pixel values to alpha values , how could I change an image transparency based on grayscale values with Pillow (6.2.2)?

I would like the brighter a pixel, the more transparent it is. Thus, pixels that are black or close to black would not be transparent.

I found the following script that works fine for white pixels but I don't know how to modify it on order to manage grayscale values. Maybe there is a better or faster way, I'm a real newbie in Python.

    from PIL import Image
    img = Image.open('Image.jpg')
    
    img_out = img.convert("RGBA")
    datas = img.getdata()
    
    target_color = (255, 255, 255)
    newData = list()
    for item in datas:
        newData.append((
            item[0], item[1], item[2],
            max( 
                abs(item[0] - target_color[0]), 
                abs(item[1] - target_color[1]), 
                abs(item[2] - target_color[2]), 
            )  
        ))
    img_out.putdata(newData)

    img_out.save('ConvertedImage', 'PNG')

Upvotes: 1

Views: 1191

Answers (1)

Zax
Zax

Reputation: 199

This is what I finally did:

from PIL import Image, ImageOps
img = Image.open('Image.jpg')

img = img.convert('RGBA')   # RGBA = RGB + alpha
mask = ImageOps.invert(img.convert('L'))    # 8-bit grey
img.putalpha(mask)
    
img.save('ConvertedImage', 'PNG')

Upvotes: 1

Related Questions