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()
print(ccmap.name) # 'viridis_r'
# get the image data ***YOU ASK FOR THIS***
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:
Amazing! This is exactly what I need! Hi swatchai, I really appreciate your help : )
@brucelau The correct way of appreciation is accepting my answer. :)
Sure. I'm glad about that : )
@brucelau To save
minimum
data to file you can save onlydata
and the colormap name. The RGBA can be reconstructed from them.you mean that we can define a function f, then reconstruct rbga = f(data) to get the values, right?