1
import numpy as np
import matplotlib.pyplot as plt 

data = np.random.random((10,10))
im = plt.imshow(data)
plt.axis('off')
plt.savefig("question2.png",bbox_inches='tight',pad_inches=0)
plt.show()

enter image description here

How to extract data from plt.imshow() or plt.matshow()?

GuokLiu
  • 65
  • 1
  • 9
  • What do you mean by "extract data". You are defining the data yourself. `data = np.random.random((10,10))` – Akshay Sehgal Nov 21 '20 at 23:46
  • 1
    A similar question: https://stackoverflow.com/questions/8938449/how-to-extract-data-from-matplotlib-plot Currenly, I have a float 2-D array, which is mapped to a 3-channel image through plt.matshow(). I want to get the data in the 3 channels. Thank you. – GuokLiu Nov 21 '20 at 23:52

1 Answers1

3

To get RGBA array of the image you plotted on a matplotlib axes, firstly, you grab the image object (here im3). Secondly, get its colormap (here ccmap). And the final step, pass the data array, im3._A, to ccmap.

import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt 

data = np.random.random((10,10))
# imshow or matshow is OK
#im3 = plt.imshow(data, cmap="viridis_r")  #any colormap will do
im3 = plt.matshow(data, cmap="viridis_r")
plt.axis('off')
#plt.savefig("question2.png",bbox_inches='tight',pad_inches=0)
plt.show()

# get the colormap used by the previous imshow()
ccmap = im3.get_cmap() #it is a function
print(ccmap.name)  # 'viridis_r'

# get the image data ***YOU ASK FOR THIS***
# the data is passed to the colormap function to get its original state
img_rgba_array = ccmap(im3._A)

# plot the image data
ax = plt.subplot(111)
ax.imshow(img_rgba_array);  #dont need any cmap to plot

Sample output plots:

img_data

swatchai
  • 17,400
  • 3
  • 39
  • 58