2015-04-08 31 views
1

我有一個NumPy的陣列僅由0和1的元素如下:提取索引

import numpy as np 
data = np.array([[1, 1 , 0 , 0 , 0 , 0 , 1 , 0], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [0, 0 , 1 , 1 , **1** , 1 , 1 , 0], 
       [0, 0 , 1 , 1 , 1 , 1 , 1 , 1], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [1, 1 , 0 , 0 , 0 , 0 , 0 , 0]]) 

我必須找出被1中2所包圍的元件1的索引在每個方向上2個像素。

預期答案的位置以粗體顯示。

我在尋找更簡單快捷的方法。

回答

2

這是很容易與basic morphological operation

import numpy as np 
from scipy.ndimage.morphology import binary_erosion 


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

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

# otherwise known as np.ones((5, 5)) 
structuring_element = np.array([[1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1]]) 

# will be of dtype np.bool but you can convert with .astype(np.int) 
# if you really need 
result = binary_erosion(data, structuring_element) 

print(result) 

print(np.allclose(result, expected)) 
3

你可以使用一些signal processing -

import numpy as np 
from scipy import signal 

# Input 
data = np.array([[1, 1 , 0 , 0 , 0 , 0 , 1 , 0], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [0, 0 , 1 , 1 , 1 , 1 , 1 , 0], 
       [0, 0 , 1 , 1 , 1 , 1 , 1 , 1], 
       [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], 
       [1, 1 , 0 , 0 , 0 , 0 , 0 , 0]]) 

# Extent of the search   
extent = 2; 

# Kernel to be used with 2D convolution     
kernel = np.ones((2*extent+1,2*extent+1)) 

# Perform 2D convolution with input data and kernel 
filt_out = signal.convolve2d(data, kernel, boundary='symm', mode='same') 

# Find where the convolution resulted in a perfect score, 
# i.e is equal to the number of elements in kernel 
R,C = np.where(filt_out == kernel.size) 

輸出 -

In [66]: print(R,C) 
[3] [4] 

列在此節是一種替代方法與ndimage執行相同的卷積與之前的做法,保持其餘步驟相同。下面的代碼,以獲得卷積輸出filt_out -

import scipy.ndimage 
filt_out = scipy.ndimage.convolve(data,kernel) 
+0

感謝您的嘗試。我有upvoted。不過,我正在考慮使用scipy.ndimage來做這件事。你能否提出一種替代方法? –

+0

like maximum_filter,minimum_filter? –

+1

@EricBal我不認爲max或min過濾器可以在這裏工作,但那些過濾器會在該窗口內尋找最大值。我們想要的是該窗口中的所有元素都是「ones」。所以我們需要的是在該窗口內的所有元素的總和,所以卷積適合這裏。 – Divakar