gpt4 book ai didi

python - 使用 Matplotlib.image 自定义颜色图

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:51 25 4
gpt4 key购买 nike

我正在使用 matplotlib.image.imsave('file.png',file,cmap=cmap) 保存二维 Numpy 数组的 .png,其中数组只能有 0、1 或 10 的值。我希望 0 为白色,1 为绿色,10 为红色。我在这个问题上看到了类似的东西:Matplotlib: Custom colormap with three colors .问题是 imsave 不将 norm 作为参数,但使用 pyplot 对我的应用程序来说太慢了。如有任何帮助,我们将不胜感激!

最佳答案

由值 [0,1,10] 组成的输入数组并不是真正的图像数组。图像数组将从 0255 或从 0.1.

一个。使用 LinearSegmentedColormap

一个想法是将数组 im 标准化为 1:im = im/im.max()。然后可以使用这些值创建颜色图0 -> 白色,0.1 -> 绿色,1 -> 红色 使用 matplotlib.colors.LinearSegmentedColormap.from_list

import matplotlib.image
import numpy as np

im = np.random.choice([0,1,10], size=(90, 90), p=[0.5,0.3,0.2])

im2 = im/10.
clist = [(0,"white"), (1./10.,"green"), (1, "red")]
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("name", clist)
matplotlib.image.imsave(__file__+'.png', im, cmap=cmap)

enter image description here

对应的pyplot图

import matplotlib.pyplot as plt
plt.imshow(im, cmap=cmap)
plt.colorbar(ticks=[0,1,10])
plt.show()

看起来像这样

enter image description here

b。使用 ListedColormap

ListedColormap 可用于生成白色、绿色和红色三种颜色的颜色图。在此颜色图中,颜色是等间距的,因此还需要将图像数组映射到等间距的值。这可以使用 np.unique(im,return_inverse=True)[1].reshape(im.shape) 来完成,它返回一个仅包含值 [0,1,2 ]。我们再次需要归一化为 1。

im = np.random.choice([0,1,10], size=(90, 90), p=[0.5,0.3,0.2])

im2 = np.unique(im,return_inverse=True)[1].reshape(im.shape)
im3 = im2/float(im2.max())

clist = ["white", "green","red"]
cmap = matplotlib.colors.ListedColormap(clist)
matplotlib.image.imsave(__file__+'2.png',im3, cmap=cmap)

enter image description here

虽然输出图像看起来与上面完全相同,但相应的 matplotlib 图会有不同的颜色条。

import matplotlib.pyplot as plt
plt.imshow(im2, cmap=cmap)
cb = plt.colorbar(ticks=[0,1,2])
cb.ax.set_yticklabels([0,1,10])
plt.show()

enter image description here

关于python - 使用 Matplotlib.image 自定义颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com