Is there a way to convert pyplot.imshow() object to numpy array? Is there a way to convert pyplot.imshow() object to numpy array? numpy numpy

Is there a way to convert pyplot.imshow() object to numpy array?


Unless you really need the marker ticks and such,

im._rgba_cache

gives you direct access to the MxNx4 numpy array that is the color mapped data.

If you just want the color mapped data, you can by pass imshow entirely and directly color-map the data your self (see guide for picking your color map)

my_cm = maplotlib.cm.get_cmap('Reds')normed_data = (data - np.min(data)) / (np.max(data) - np.min(data))mapped_data = my_cm(normed_data)

which will give you back a MxNx4 array mapped between 0 and 1,

mapped_datau8 = (255 * my_cm(normed_data)).astype('uint8')

or

mapped_data = my_cm(normed_data, bytes=True)

will convert it to unsigned ints.

matplotlib includes a range of normalization code, see here.

get_cmap doc and colormap gallery

edit: fixed oversight pointed out at https://stackoverflow.com/a/14880947/380231


Ar you sure you want to convert the return value of the method or the whole plot?

For the latter, you should try:

  • Save the plot to a StringIO-buffer image using savefig
  • Load the image from this buffer, using PIL or opencv
  • Convert it to a numpy array

See sample below:

import numpy as npimport matplotlib.pyplot as pltimport PILfrom cStringIO import StringIOplt.imshow(np.random.random((20,20)))buffer_ = StringIO()plt.savefig(buffer_, format = "png")buffer_.seek(0)image = PIL.Image.open(buffer_)ar = np.asarray(image)buffer_.close()

Look into savefig-*args and **kwargs for more options, e.g., dpi, background color, transparency, padding etc.

If you jsut want the color coded image, without axes, labels, etc., I'd still do the same, just use

plt.subplots_adjust(0,0,1,1)

to extend the axes over the whole figure. Take care of the aspect of you plot, otherwise mpl might shrink your axes again.


Updated answer inspired from @Thorsten Kranz

import numpy as npimport matplotlib.pyplot as pltfrom PIL import Imageimport ioplt.imshow(np.random.random((20,20)))with io.BytesIO() as buffer:    plt.savefig(buffer, format = "png")    buffer.seek(0)    image = Image.open(buffer)    ar = np.asarray(image)print(ar.shape)