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

Question:

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()?

Asked By: GuokLiu

||

Answers:

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

Answered By: swatchai
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.