2017-08-28 162 views
0

我有一張尺寸爲128x128x64的3D圖像,其中有64圖像,每張圖像的尺寸爲128x128。圖像呈現三個類,標籤爲0-背景,1--第一個對象,2-second對象。我正在使用matplotlib來顯示圖像。如何顯示灰色圖像的顏色圖?

import matplotlib.pyplot as plt 
fig = plt.figure(figsize=(32,32)) 
ax1 = plt.add_subplot(111) 
ax1.imshow(image[:, :, 32]) 

我想在彩色圖中顯示它。其中,背景應爲黑色,對象1爲紅色,對象2爲綠色。我應該如何修改代碼?謝謝 預期結果喜歡圖左下角 enter image description here

回答

2

你的問題不是很清楚。你說你想獲得像圖左下方的結果一樣的結果,但是這個圖像具有陰影和各種級別的綠色和紅色。

從你的問題,我明白你有一個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]) 

enter image description here

+0

權。你做到了我的預期。我找不到一個好例子,所以我只是谷歌並將其附加在問題中。但是你做到了我的期望。謝謝 – user8264

+0

謝謝Diziet。我用你的代碼,它運行良好。我只想問一個關於調整顏色的問題。我們可以有任何選項來調整黃色的顏色,以更大膽,藍色更亮。我問,因爲如果你一起使用紅色,藍色和藍色,那麼我看到藍色太粗了,而紅色和黃色太亮 – user8264

+1

你可以使用任何你想要的顏色,通過在(R,G,B, alpha)格式。例如:'cmap = LinearSegmentedColormap.from_list(「3colors」,[(r,g,b),(r,g,b),(r,g,b)],N = 3) –