2010-01-30 54 views
14

我使用numpy來構建像素數組。 800x600圖像是uint8,800x600x3的三維陣列。我也有一個固定模式的類似陣列(棋盤,見here)。我有另一個數組,掩碼值爲800x600。在掩碼爲零的情況下,我想將圖案像素複製到圖像像素。在掩碼不爲零的情況下,我想單獨保留圖像像素。使用numpy來掩蓋圖案的圖像?

>>> image.shape 
(800, 600, 3) 
>>> chex.shape 
(800, 600, 3) 
>>> mask.shape 
(800, 600) 

這感覺就像它應該工作:

image[mask == 0,...] = chex 

,但給 「ValueError異常:數組不broadcastable到正確的形狀」。

我該如何將chex像素複製到掩碼爲零的圖像像素?

回答

12
idx=(mask==0) 
image[idx]=chex[idx] 

注意image具有形狀(800,600,3),而idx具有形狀(800,600)。 The rules用於索引狀態

if the selection tuple is smaller than n, then as many : objects as needed are added to the end of the selection tuple so that the modified selection tuple has length N.

因此索引數組具有它們自己的一種廣播能力。 idx的形狀被提升爲(800,600,:)

0

嘗試:

image[mask[:] == 0,...] = chex[mask[:] == 0,...] 
+0

「ValueError異常:陣列不是broadcastable糾正形狀」 – 2010-01-30 22:40:57

0

我使用8x6x3,8x6x3和8x6的數組分別表示圖像數組,檢查數組和掩碼數組。

# first create mini-versions of your arrays: 
mask = NP.random.random_integers(0, 1, 48).reshape(8, 6) 
img = NP.random.random_integers(3, 9, 8*6*3).reshape(8, 6, 3) 
chk = NP.ones((8, 6, 3)) 

# all the work done in these two lines 
mask = mask[:,:,NP.newaxis] 
res = NP.where(mask==0, chk, img) 
+0

三個圖像的形狀,'mask.shape(8,6),chk.shape(8,6,3)和img.shape( 8,6,3)'似乎不符合'np.where.'的要求 – Gathide 2017-05-20 05:05:28