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 6 Years Ago 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):
    if not inside.count(False):
        return 255
        return 0

def automask(img):
    backcolor = img.getpixel((0, 0))
    alpha_mask ='1', img.size)
    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)
                alpha_mask.putpixel((x, y), 0)
    return img

root = Tkinter.Tk()

masked = automask('grim_reaper.jpg'))

maskedtk = ImageTk.PhotoImage(masked)

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


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

Simple transparent overlaying image

import Image

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

dd"i.jpg") ## Put your second image file name here

This is more simple :)

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 ..

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.