0

Simple script for image transparency.

Someone asked one some time ago, and i had other but for a different system, and decided to write a Python/PIL version.

The value of the color used as transparent is the value of the pixel at position (0, 0).

You can adjust tolerance value.

Happy coding!

Edited by Beat_Slayer: n/a

Attachments masked.jpg 4.32 KB original.jpg 4.21 KB
import Tkinter 
import Image
import ImageTk

def color_cmp(orig, comp):
    tolerance = 5   #  You can adjust color tolerance value
    inside = []
    for i in range(len(orig) - 1):
        if (orig[i] - tolerance) <= comp[i] >= (orig[i] + tolerance):
            inside.append(True)
        else:
            inside.append(False)
    if not inside.count(False):
        return 255
    else:
        return 0

def automask(img):
    backcolor = img.getpixel((0, 0))
    alpha_mask = Image.new('1', img.size)
    alpha_mask.load()
    for y in range(img.size[1]):
        for x in range(img.size[0]):
            pix_color = img.getpixel((x, y))
            if color_cmp(pix_color, backcolor):
                alpha_mask.putpixel((x, y), 1)
            else:
                alpha_mask.putpixel((x, y), 0)
    img.putalpha(alpha_mask)
    return img

root = Tkinter.Tk()

masked = automask(Image.open('grim_reaper.jpg'))

maskedtk = ImageTk.PhotoImage(masked)

Tkinter.Label(root, image=maskedtk).pack()

root.mainloop()
3
Contributors
3
Replies
6
Views
7 Years
Discussion Span
Last Post by gleam.uahmed
0

Hi , But it doesnt work perfect when i want to putt that image over a button having image ! , it doesnt show any transparency

0

Simple transparent overlaying image

import Image

handle = Image.open("fd.png")## Your first image file name

handle.putalpha(30)
handle.save("bv.png")
df=Image.open("bv.png")
dd =Image.open("i.jpg") ## Put your second image file name here
df.paste(dd,(100,200))
df.save("gg.png")

This is more simple :)

0

Offcourse it is but it will create a new picture and still the transperency issue remain when u putt a label with transparent pic over the button it will not work ..

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.