Search code examples
pythonnumpyimage-processingpython-imaging-librarycolormap

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


Solution

  • from PIL import Image
    
    gray, alpha = Image.open(source_fn).convert('LA').split()
    gradient = Image.open(gradient_fn).convert('RGB').resize((256, 1))
    lut = []
    for band in gradient.split():
        lut += list(band.getdata())
    
    out = gray.point(lut, 'RGB')
    out.putalpha(alpha)
    out.save(out_fn, '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