你的問題不是很清楚。你說你想獲得像圖左下方的結果一樣的結果,但是這個圖像具有陰影和各種級別的綠色和紅色。
從你的問題,我明白你有一個128×128陣列,只有3種可能的值:0.
(背景),1.
(第一目標)和2.
(第二對象)。那是對的嗎?如果是這樣,實質上你的問題歸結爲如何創建一個具有3個級別和黑色,紅色,綠色顏色的Discret色彩映射。
這裏是我會做什麼:
# Generate some fake data for testing
img = np.zeros((128,128)) # Background
img[:50,:50] = np.ones((50,50)) # Object 1
img[-50:,-50:] = np.ones((50,50))*2 # Object 2
#>img
#>array([[ 1., 1., 1., ..., 0., 0., 0.],
# [ 1., 1., 1., ..., 0., 0., 0.],
# [ 1., 1., 1., ..., 0., 0., 0.],
# ...,
# [ 0., 0., 0., ..., 2., 2., 2.],
# [ 0., 0., 0., ..., 2., 2., 2.],
# [ 0., 0., 0., ..., 2., 2., 2.]])
# Create a custom discret colormap
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("3colors", ['k','r','g'], N=3)
# Plot
# Don't forget to includes the bounds of your data (vmin/vmax)
# to scale the colormap accordingly
fig,ax = plt.subplots()
im = ax.imshow(img, cmap=cmap, vmin=0, vmax=2)
ax.grid(False)
cax = fig.colorbar(im)
cax.set_ticks([0,1,2])
權。你做到了我的預期。我找不到一個好例子,所以我只是谷歌並將其附加在問題中。但是你做到了我的期望。謝謝 – user8264
謝謝Diziet。我用你的代碼,它運行良好。我只想問一個關於調整顏色的問題。我們可以有任何選項來調整黃色的顏色,以更大膽,藍色更亮。我問,因爲如果你一起使用紅色,藍色和藍色,那麼我看到藍色太粗了,而紅色和黃色太亮 – user8264
你可以使用任何你想要的顏色,通過在(R,G,B, alpha)格式。例如:'cmap = LinearSegmentedColormap.from_list(「3colors」,[(r,g,b),(r,g,b),(r,g,b)],N = 3) –