[Image-SIG] Making the "outside" of an image transparent

Paul Moore p.f.moore at gmail.com
Fri May 5 12:38:40 CEST 2006

I have a rectangular image, which is a logo on a white background. I
would like to modify the image to make the white background
transparent (in effect, giving an irregularly shaped image). I've
searched the archives, and found some details on how to make parts of
an image transparent, but they aren't quite what I need. The problem I
have is that parts of the interior of the image are also white, and
those parts I don't want to make transparent.

I searched for a flood fill algorithm that would do what I wanted, and
couldn't find anything that I could use. I did find one algorithm,
which I tried to modify to do what I wanted, but I've clearly
misunderstood something vital, as the resulting image looked identical
to the original :-(

Can anyone help me? I attach my code in case it's of use, but to be
honest, I'm not sure it's even close...


import Image

def crop_background(image, colour = None):
    w, h = image.size
    print w*h
    mask = Image.new("L", image.size)
    if colour is None:
	colour = image.getpixel((0, 0))
    pt = 0, 0
    background = set()
    seen = set()
    candidates = set((pt,))
    while candidates:
	pt = candidates.pop()
	if image.getpixel(pt) == colour:
	i, j = pt
	for new_i, new_j in (i+1, j), (i, j+1), (i-1, j), (i, j-1):
	    if 0 <= new_i < w and 0 <= new_j < h and (new_i, new_j) not in seen:
		candidates.add((new_i, new_j))
    pix = mask.load()
    for i in range(w):
	for j in range(h):
	    if (i, j) in background:
		pix[i, j] = 0
		pix[i, j] = 1
    print len(background)
    return image

More information about the Image-SIG mailing list