Basically, I’m trying to make a function that will take a given image and a color. for each pixel in the image, it will keep the original alpha value but will change the color to the given one.
for example, if the function gets the arrow image below and the color red,
It will output the following image:
In Photoshop and other image editors, this effect called “color overlay”. Is there any quick and easy way of achieving the same result in PIL? Thanks in advance! (;
3
Answers
One way of doing it is to create a solid red image the same size as the original and then copy the alpha channel from the original image across to it:
Here is a second method using Numpy:
A third way is to composite with a similarly-sized red copy and use the original alpha mask:
Keywords: Image, image processing, Python, Pillow, PIL, Numpy, extract alpha, alpha channel, transparency, replace transparency, copy transparency, copy alpha, transplant alpha, transplant transparency.
Let us consider the following image – http://www.libpng.org/pub/png/img_png/globe-scene-fish-bowl-pngcrush.png
Try:
INPUT:-
OUTPUT:-
EXPLANATION FOR THE FIRST LOOP:-
If the first loop doesn’t flat out, the
alpha
values by a threshold, then a lot of error gets produced in the output image. i.e. Pixel values near the edge of a object tends to havealpha
pixel values a little lesser than255
(total opacity) to enable smooth anti-aliasing. If these pixels are discarded then output image may look something like this:-P.S.:- Even though OpenCV would be the preferred choice for most Image Analysts/Experts, I would definitely advice you to stick with PIL/Pillow at the beginning, as it allows you to get the grasp the fundamentals of imaging in a really friendly way. There is no denying that OpenCV far outweighs PIL in almost every aspect, but still if you learn PIL in the beginning, transitioning from PIL to OpenCV would be alot easier for you to do later on.