How to convert Numpy array to PIL image applying matplotlib colormap

I have a simple problem but cannot find a good solution to it.

I want to take a numpy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.

I can get a reasonable PNG output by using the pyplot.figure.figimage command:

    dpi = 100.0
    w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
    fig = plt.figure(figsize=(w,h), dpi=dpi)
    fig.figimage(sub, cmap=cm.gist_earth)
    plt.savefig('out.png')

Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:

    colored_PIL_image = magic_function(array, cmap)

Thanks for reading!

Quite a busy one liner, but here it is:

  1. First ensure your numpy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

    from PIL import Image
    im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

enter image description here

with im.save():

enter image description here

From: stackoverflow.com/q/10965417