2017-09-14 106 views
1

在處理圖像時,我想忽略所有白色像素。我認爲最好的方法是設置遮罩陣列,以便在初始化它時立即更改遮罩陣列,其中有白色像素。爲此,我使用以下代碼的最後一行中描述的方法。使用numpy爲特定值的像素製作遮罩陣列

with PIL.Image.open(picture) as im: 
    pix = numpy.array(im, dtype=numpy.float) 
[height, width, _] = pix.shape 
mask = numpy.zeros((height,width)) 
mask[numpy.argwhere(pix == [255,255,255])] = 1 

不過,此行生成以下錯誤:

File "C:\Users\Alec\zone_map.py", line 19, in zone_map 
    mask[numpy.argwhere(pix == [255,255,255])] = 1 

IndexError: index 5376 is out of bounds for axis 0 with size 4000 

我怎樣才能改變這種實現期望的結果?

+1

你這是什麼意思是「不起作用」?它會拋出一個錯誤嗎?給出意想不到的結果? –

回答

1

使用的ALL-reduced口罩沿最後軸和簡單的索引輸入數組賦值(S)以下boolean-indexing,像這樣 -

mask = (pix==255).all(axis=-1) 
pix[mask] = 1 

採樣運行 -

In [18]: pix 
Out[18]: 
array([[[ 5, 11, 10], 
     [ 9, 5, 11], 
     [ 11, 10, 9], 
     [255, 255, 255]], 

     [[ 9, 8, 8], 
     [ 10, 8, 9], 
     [255, 255, 255], 
     [ 5, 8, 10]]]) 

In [19]: mask = (pix==255).all(-1) 

In [21]: pix[mask] = 1 

In [22]: pix 
Out[22]: 
array([[[ 5, 11, 10], 
     [ 9, 5, 11], 
     [11, 10, 9], 
     [ 1, 1, 1]], 

     [[ 9, 8, 8], 
     [10, 8, 9], 
     [ 1, 1, 1], 
     [ 5, 8, 10]]])