The Python Oracle

How to convert a NumPy array to PIL image applying matplotlib colormap

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle

--

Chapters
00:00 Question
01:04 Accepted answer (Score 361)
01:47 Answer 2 (Score 78)
02:14 Answer 3 (Score 12)
02:49 Thank you

--

Full question
https://stackoverflow.com/questions/1096...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #matplotlib #pythonimaginglibrary #colormapping

#avk47



ACCEPTED ANSWER

Score 392


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
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here




ANSWER 2

Score 90


  • input = numpy_image

  • np.uint8 -> converts to integers

  • convert('RGB') -> converts to RGB

  • Image.fromarray -> returns an image object

      from PIL import Image
      import numpy as np
    
      PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
      PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    



ANSWER 3

Score 12


The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

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

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.