[Image-SIG] How to display a masked image?

Russell E. Owen rowen at cesmail.net
Thu Apr 13 22:28:46 CEST 2006

I'm trying to use PIL to display a grayscale image with an associated 
mask.  I want the user to clearly see which pixels are masked, yet still 
be able to see the original data in the masked areas.

The algorithm I've come up with is to average the grayscale image with a 
mask that consists of a tint color. It seems to work (but if there's a 
better algorithm I'd love to hear of it).

However, my code to implement this looks pretty messy. Is there a better 

def addMask(im, mask, maskrgb, intens=75):
    """Add a mask to a grayscale image in such a way that the
    masked areas of the image can still be seen.
    - im is an "F" grayscale image that has been scaled into 0-255 range
    - mask is a mask such that 0 = unmasked, nonzero=masked
    - maskrgb is a tuple of RGB color values 0-255 each
    - intens is the intensity of the displayed mask 0-255

    Returns the masked image in color
    lmask = mask.convert("L")
    rgbmaskset = []
    # create color image of mask 
    for colval in maskrgb:
        rgbmaskset.append(lmask.point(lambda i: i * colval))
    rgbmask = Image.merge("RGB", rgbmaskset)
    # create transparency version of mask
    transmask = lmask.point(lambda i: i * intens)
    # merge mask and image
    rgbim = im.convert("RGB")
    rgbim.paste(rgbmask, mask=transmask)
    return rgbim

-- Russell

More information about the Image-SIG mailing list