How to convert a Numpy array to a PIL image using matplotlib colormap

I have a simple problem, but I can not find a good solution.

I want to take a multidimensional 2D array that represents a grayscale image and convert it to an RGB PIL image using some matplotlib color maps.

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

 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 (perhaps using StringIO to get a PIL image), I wonder if there is an easier way to do this, since this seems like a very natural problem of rendering an image. Let's say something like this:

 colored_PIL_image = magic_function(array, cmap) 

Thanks for reading!

+81
python numpy matplotlib python-imaging-library color-mapping
Jun 09 2018-12-12T00:
source share
2 answers

One liner is quite busy, but here it is:

  1. First, make sure your massive myarray array myarray normalized with a maximum value of 1.0 .
  2. Apply myarray colors directly to myarray .
  3. Scale to a range of 0-255 .
  4. Convert to integers using np.uint8() .
  5. Use Image.fromarray() .

And you did:

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

using plt.savefig() :

enter image description here

with im.save() :

enter image description here

+157
Jun 10 2018-12-12T00:
source share

The method described in the accepted answer did not work for me even after applying the changes mentioned in his comments. But below simple code worked

 import matplotlib.pyplot as plt plt.imsave(filename, np_array, cmap='Greys') 

np_array can be either a 2D array with values ​​from 0..1 float o2 0..255 uint8, in which case it needs cmap. For 3D arrays, cmap will be ignored.

+2
Apr 16 '19 at 9:58 am
source share



All Articles