2017-07-29 13 views
1

我正在使用scipy.ndimage.label的大陣列(3000 x 3000)。返回是3403個標籤和標籤數組。我想知道這些標籤的索引。對於標籤1,我應該知道標籤數組中的行和列。 所以基本上是這樣的除了np以外,Scipy標籤陣列的索引計算更快。其中

a[0] = array([[1, 1, 0, 0], 
       [1, 1, 0, 2], 
       [0, 0, 0, 2], 
       [3, 3, 0, 0]]) 


indices = [np.where(a[0]==t+1) for t in range(a[1])] #where a[1] = 3 is number of labels. 

print indices 
[(array([0, 0, 1, 1]), array([0, 1, 0, 1])), (array([1, 2]), array([3, 3])), (array([3, 3]), array([0, 1]))] 

而且我想創建索引的列表中的所有標籤3403像上面。上述方法似乎很慢。我嘗試過使用生成器,它看起來不像有改進。

有什麼有效的方法嗎?

+0

向我們展示您的工作loopy解決方案。 – Divakar

+0

@Divakar indices = [np.where(m [0] == t + 1)for range in(m [1])]其中m [0]是標記數組,m [1]是標記計數(3403這裏)。 – Gargantua89

+0

請將這些添加到問題中。很高興看到示例數據。 – Divakar

回答

0

那麼獲得效率的想法是儘量減少循環內的工作。矢量化方法是不可能的,因爲每個標籤的元素數量是可變的。因此,在考慮到這些因素,這裏有一個解決方案 -

a_flattened = a[0].ravel() 
sidx = np.argsort(a_flattened) 
afs = a_flattened[sidx] 
cut_idx = np.r_[0,np.flatnonzero(afs[1:] != afs[:-1])+1,a_flattened.size] 
row, col = np.unravel_index(sidx, a[0].shape) 
row_indices = [row[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])] 
col_indices = [col[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])] 

樣品輸入,輸出 -

In [59]: a[0] 
Out[59]: 
array([[1, 1, 0, 0], 
     [1, 1, 0, 2], 
     [0, 0, 0, 2], 
     [3, 3, 0, 0]]) 

In [60]: a[1] 
Out[60]: 3 

In [62]: row_indices # row indices 
Out[62]: 
[array([0, 0, 1, 2, 2, 2, 3, 3]), # for label-0 
array([0, 0, 1, 1]),    # for label-1 
array([1, 2]),     # for label-2  
array([3, 3])]     # for label-3 

In [63]: col_indices # column indices 
Out[63]: 
[array([2, 3, 2, 0, 1, 2, 2, 3]), # for label-0 
array([0, 1, 0, 1]),    # for label-1 
array([3, 3]),     # for label-2 
array([0, 1])]     # for label-3 

的第一要素關閉row_indicescol_indices是預期的輸出。每個組的第一組代表0-th區域,因此您可能想跳過這些區域。