简体   繁体   中英

How can i convert numpy array to pil image in memory?

I have heatmap which is normalized 2d numpy array

When i plot it with matplotlib:

axes_img = plt.imshow(255 * normalized_heat_map, alpha=alpha, cmap=cmap)
plt.show()

在此处输入图像描述

However when i convert it to PIL image and then plot again

heatmap_image = Image.fromarray(np.uint8(axes_img.get_cmap()(axes_img.get_array()) * 255))
plt.imshow(np.asarray(heatmap_image))
plt.show()

在此处输入图像描述

How can I get image that is same to one from Matplotlib one without saving to file ?

The function imshow adjust the limits of the color scale to the minimum and maximum of the data you are plotting. If you keep this in mind, you realize you have to normalize the image array before converting it in an 8bit array. This can be done as follow:

scaled_img = (axes_img.get_array()-axes_img.get_clim()[0])/(axes_img.get_clim()[1]-axes_img.get_clim()[0])
heatmap_image = Image.fromarray(np.uint8(axes_img.get_cmap()(scaled_img) * 255))

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