2016-06-13 100 views
1

我有一個2D numpy數組,填充0和1,我想對它進行轉換,以便將鄰近1的每個值轉換爲1(因此標題中的「污染」) 。Numpy數組值「污染」

例如:

0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 1 0 0 
0 0 0 0 1 0 
0 0 1 0 0 0 
0 0 0 0 0 0 

變爲:

0 0 0 0 0 0 
0 0 1 1 1 0 
0 0 1 1 1 1 
0 1 1 1 1 1 
0 1 1 1 1 1 
0 1 1 1 0 0 

我可以通過所有的值循環,找到1S,然後更換相鄰值實現這一點:

import numpy as np 

ones = [] 

ar = np.array([[0,0,0,0,0,0], 
     [0,0,0,0,0,0], 
     [0,0,0,1,0,0], 
     [0,0,0,0,1,0], 
     [0,0,1,0,0,0], 
     [0,0,0,0,0,0]]) 

n_row, n_col = ar.shape 

for i in range(n_row): 
    for j in range(n_col): 

     if ar[i][j] == 1: 
      ones.append((i, j)) 

for x,y in ones: 
    # Replace neighboring values 

但這似乎矯枉過正(特別是因爲我打算處理真正的大型數組)。

有沒有辦法實現這一點,而不必循環所有的值?

回答

2

這基本上是dilation operation in Image-processing domain。所以,你可以使用Scipy's binary dilation -

from scipy.ndimage import binary_dilation 
out = binary_dilation(arr, structure=np.ones((3,3))).astype(int) 

採樣運行 -

In [21]: arr 
Out[21]: 
array([[0, 0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0, 0], 
     [0, 0, 0, 1, 0, 0], 
     [0, 0, 0, 0, 1, 0], 
     [0, 0, 1, 0, 0, 0], 
     [0, 0, 0, 0, 0, 0]]) 

In [22]: binary_dilation(arr, structure=np.ones((3,3))).astype(int) 
Out[22]: 
array([[0, 0, 0, 0, 0, 0], 
     [0, 0, 1, 1, 1, 0], 
     [0, 0, 1, 1, 1, 1], 
     [0, 1, 1, 1, 1, 1], 
     [0, 1, 1, 1, 1, 1], 
     [0, 1, 1, 1, 0, 0]]) 
+0

這正是我一直在尋找的,謝謝! – 3kt

0

,你描述的被稱爲 「二元擴張」 的操作。在scipy.ndimage有一個實現。例如,

In [369]: a 
Out[369]: 
array([[0, 0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0, 0], 
     [0, 0, 0, 1, 0, 0], 
     [0, 0, 0, 0, 1, 0], 
     [0, 0, 1, 0, 0, 0], 
     [0, 0, 0, 0, 0, 0]]) 

In [370]: from scipy.ndimage import binary_dilation 

In [371]: binary_dilation(a, structure=np.ones((3, 3))) 
Out[371]: 
array([[False, False, False, False, False, False], 
     [False, False, True, True, True, False], 
     [False, False, True, True, True, True], 
     [False, True, True, True, True, True], 
     [False, True, True, True, True, True], 
     [False, True, True, True, False, False]], dtype=bool) 

In [372]: binary_dilation(a, structure=np.ones((3, 3))).astype(int) 
Out[372]: 
array([[0, 0, 0, 0, 0, 0], 
     [0, 0, 1, 1, 1, 0], 
     [0, 0, 1, 1, 1, 1], 
     [0, 1, 1, 1, 1, 1], 
     [0, 1, 1, 1, 1, 1], 
     [0, 1, 1, 1, 0, 0]])