Is it possible to mask an image in Python Imaging Library (PIL)?
Solution 1
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.
Solution 2
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 images
img1.paste(im=img2, box=(0, 0), mask=img2)
wfgeo
Developer with geospatial focus. Stuff I like to use is: QGIS Geoserver Leaflet PostGIS pgRouting Python And whatever else gets the job done...
Updated on June 04, 2022Comments
-
wfgeo almost 2 years
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.