Is it possible to mask an image in Python Imaging Library (PIL)?

I have some traffic camera images, and I want to extract only the pixels on the road. I have used remote sensing software before where one could specify an operation like

img1 * img2 = img3

where img1 is the original image and img2 is a straight black-and-white mask. Essentially, the white parts of the image would evaluate to

img1 * 1 = img3

and the black parts would evaluate to

img1 * 0 = img3

And so one could take a slice of the image and let all of the non-important areas go to black.

Is there a way to do this using PIL? I can't find anything similar to image algebra like I'm used to seeing. I have experimented with the blend function but that just fades them together. I've read up a bit on numpy and it seems like it might be capable of it but I'd like to know for sure that there is no straightforward way of doing it in PIL before I go diving in.

Thank you.

2 Answers

The Image.composite method can do what you want. The first image should be a constant value representing the masked-off areas, and the second should be the original image - the third is the mask.

You can use the PIL library to mask the images. Add in the alpha parameter to img2, As you can't just paste this image over img1. Otherwise, you won't see what is underneath, you need to add an alpha value.

img2.putalpha(128) #if you put 0 it will be completly transparent, keep image opaque

Then you can mask both the imagesimg1.paste(im=img2, box=(0, 0), mask=img2)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like