2015-07-12 130 views
2

我有一個圖像我加載到python使用matplotlib.pyplot.imread其結果作爲numpy數組包含rgb值的數組。這裏是除了兩個像素的白色啞片段:將RGB白色設置爲透明?

>>> test 
array([[[255, 255, 255], 
     [255, 255, 255]], 

     [[ 1, 255, 255], 
     [255, 255, 255]], 

     [[255, 255, 255], 
     [255, 6, 255]]], dtype=uint8) 

我想創建一個屏蔽掉所有的白色像素。我想我可以做一些類似

>>> mask = (test != [255, 255, 255]) 

的東西,這將使:

array([[[False, False, False], 
     [False, False, False]], 

     [[ True, True, True], 
     [False, False, False]], 

     [[False, False, False], 
     [ True, True, True]]], dtype=bool) 

我該怎麼辦呢?

或者,我認爲有一個輸入參數爲imshow這是做到這一點,但文件不清楚如何。看來alpha會改變整個圖像,並且vmax接受一個與RGB顏色不兼容的縮放器。

回答

0

以獲得所需的面具輸出,你可以做這樣的事情 -

wpix = np.array([255,255,255])   
out = np.tile(np.atleast_3d(np.any(test != wpix,axis=2)),(1,1,test.shape[2])) 

另外,由於白色像素是所有255's,你也可以這樣做 -

out = np.tile(np.atleast_3d(np.any(test != 255,axis=2)),(1,1,test.shape[2])) 
+0

這會生成我想要的遮罩陣列,但是當我嘗試使用'ax.imshow(np.ma.masked_where(out,test))繪製圖像時,它仍然顯示爲白色。 –

+0

@ stvn66是的,在做了一些研究後,我傾向於這個結論,即imsh​​ow的這個透明選項與RGB圖像不兼容,如果不是直接使用'np.ma.masked_where'進行掩碼的話。 – Divakar

-2

我認爲,要走的路是創建一個RGBA數組並將其輸入到imgshow。

你想獲得

mask = array([[[False],[False]],[[True],[False]],[[False],[True]]]] 

然後:

alphaChannel = 255*mask; 
img = np.concatenate((test,alphaChannel), axis=2); 
plt.imshow(img); 

對不起,不測試它,而不是讓計算面具的方式。

[注:對我來說,matplotlib總是0和1,而不是整數之間浮動的作品,但我想都是有效]

0

一種辦法是建立一個masked array然後imshow它:

import numpy as np 
from matplotlib import pyplot as plt 

x = np.array([[[255, 255, 255], 
       [255, 255, 255]], 
       [[ 1, 255, 255], 
       [255, 255, 255]], 
       [[255, 255, 255], 
       [255, 6, 255]]], dtype=np.uint8) 

mask = np.all(x == 255, axis=2, keepdims=True) 

# broadcast the mask against the array to make the dimensions the same 
x, mask = np.broadcast_arrays(x, mask) 

# construct a masked array 
mx = np.ma.masked_array(x, mask) 

plt.imshow(mx) 

屏蔽值將呈現透明。

另一種選擇是你的RGB數組轉換爲一個RGBA數組,alpha通道設置爲零的地方,紅色,綠色和藍色通道的值都爲255

alpha = ~np.all(x == 255, axis=2) * 255 
rgba = np.dstack((x, alpha)).astype(np.uint8) 

plt.imshow(rgba) 

請注意,我有在連接之後將rgba轉換回uint8,因爲imshow預期RGBA數組要麼是uint8或float。