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:
