Search code examples
pythonmatplotlibcolorspngpython-imaging-library

How to change grayscale to colour in python?


I have found the following link: Python colour to greyscale

I would however like to do the opposite. Is this possible with Pyython (preferably with PIL, but other options are welcome as well like matplotlib)?

I need to read in a greyscale png image, which I would like to convert to a rainbow scale (preferably desaturated rainbow, but not necessary). The images originally come from c-code that generates numbers between 0 and 256 and converts those to grey tones. I would like to map those values now linearly to a colour-map (but I currently only have access to the png-image, not the c-code any more). So is there a way to map white to blue, and black to red, with all colours of the rainbow in between?


Solution

  • The mapping from color to grey is not invertable. So you need to indeed define some colormapping like the matplotlib colormaps do.

    import matplotlib.pyplot as plt
    
    # generate gray scale image
    import scipy.misc
    face = scipy.misc.face()
    plt.imsave("face.png", face.mean(2), cmap="gray")
    
    # read in image
    im = plt.imread("face.png")
    # plot image in color
    plt.imshow(im.mean(2), cmap="jet_r")
    #save image in color
    plt.imsave("color.png", im.mean(2), cmap="jet_r")
    plt.show()
    

    enter image description here