2015-04-04 75 views
1

我有一個角塊matrix,我想每個塊計算塊的座標中對角線塊矩陣

a = np.zeros((25,18), dtype=int)  
a[2:8,:6]=1 

a[8:13,6:12]=1 

a[13:15,12:14]=1 

a[15:20,14:]=1 

和輸出

[(2, 0), (8, 6), (13, 12), (15, 14)] 

感謝的座標(行,列)!

+3

您能給出一些樣本輸入和預期輸出嗎?看到這個問題http://stackoverflow.com/q/29447164/553404 – YXD 2015-04-04 21:55:27

回答

0

如果,在你的榜樣,每列包含一個塊或其他,你可以得到通過掃描每列中的第一個非零入口並保持跟蹤相應的行,獲得每個塊的座標:

In [1]: import numpy as np 
In [2]: a = np.zeros((25,18), dtype=int)  
In [3]: a[2:8,:6]=1 
In [4]: a[8:13,6:12]=1 
In [5]: a[13:15,12:14]=1 
In [6]: a[15:20,14:]=1 
In [7]: rows = set() 
In [8]: blocks = [] 
In [9]: for col in range(a.shape[1]): 
      row = np.argmax(a[:,col]) 
      if row not in rows: 
       rows.add(row) 
       blocks.append((row, col)) 
....:   

In [10]: blocks 
Out[10]: [(2, 0), (8, 6), (13, 12), (15, 14)] 
0

我假設你的矩陣確實充滿了布爾值,就像你的圖片一樣。

每個塊都是完全正方形的,因此可以通過其起始座標和其邊長來定義。還要注意,起始座標總是位於矩陣的對角線上,所以行和列是相等的。

如果你看圖片,很明顯看到在每個塊的開始處,緊接在上面(或向左)的單元格是False。因此,我們可以創建塊的列表,[(座標,長度),...],具體如下:

# Find the coordinates where each block starts 
starts = [] 
for i in range(len(myMatrix)): 
    if i==0: 
     starts.append(i) 
    elif not myMatrix[i,i-1]: # i.e., if the cell to the left is False 
     starts.append(i) 
# Get the length of each block 
blocks = [] 
for i in range(len(starts)): 
    thisStart = starts[i] 
    if i == len(starts)-1: 
     nextStart = len(myMatrix) 
    else: 
     nextStart = starts[i+1] 
    length = nextStart - thisStart 
    blocks.append((thisStart, length)) 
+0

格雷格,開始的座標工作正常,但第二部分有一個問題。謝謝! 回溯(最近呼叫的最後一個): 文件「」,第8行,在 TypeError:不支持的操作數類型爲 - :'int'和'list' – 2015-04-04 22:49:15

+0

再試一次 - 我修復了最後一行錯誤。如果不是這樣,你能澄清你發現錯誤的哪一行嗎? – 2015-04-05 02:16:55