简体   繁体   English

如何将 numpy 数组转换为内存中的 pil 图像?

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

I have heatmap which is normalized 2d numpy array我有热图,它是标准化的 2d numpy 数组

When i plot it with matplotlib:当我用 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然而,当我将它转换为 PIL 图像然后再次绘制时

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 ?如何在不保存到文件的情况下从 Matplotlib 获取与一张相同的图像?

The function imshow adjust the limits of the color scale to the minimum and maximum of the data you are plotting.函数imshow将色标的限制调整为您正在绘制的数据的最小值和最大值。 If you keep this in mind, you realize you have to normalize the image array before converting it in an 8bit array.如果记住这一点,就会意识到在将图像数组转换为 8 位数组之前必须对其进行归一化。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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