简体   繁体   中英

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

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

在此处输入图片说明

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

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:

img_data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM