Applying a gradient map from image to another image with transparency in Python (PIL, numpy, etc)


I’ve been struggling with trying to apply a gradient map which is sourced from an image file to a grayscale image which includes alpha/transparency. The following includes the source image and the gradient map image. I first attempted this with numpy and was unsuccessful. The purpose of this is to be able to programmatically color image layers using gradient maps. Any help would be appreciated. Thank you!

Sample Source Image

Sample Colormap / Gradient to Apply

Sample Intended Result


from PIL import Image

gray, alpha ='LA').split()
gradient ='RGB').resize((256, 1))
lut = []
for band in gradient.split():
    lut += list(band.getdata())

out = gray.point(lut, 'RGB')
out.putalpha(alpha), 'PNG')

Here’s the result. It doesn’t quite match the example you provided as the intended result, but I think that’s just a misunderstanding of how the range of inputs were supposed to map to the gradient. I’m sure you could fix that yourself.

enter image description here

Answered By – Mark Ransom

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.