计算块的坐标中对角线块矩阵

问题描述:

我有一个角块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

如果,在你的榜样,每列包含一个块或其他,你可以得到通过扫描每列中的第一个非零入口并保持跟踪相应的行,获得每个块的坐标:

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)] 

我假设你的矩阵确实充满了布尔值,就像你的图片一样。

每个块都是完全正方形的,因此可以通过其起始坐标和其边长来定义。还要注意,起始坐标总是位于矩阵的对角线上,所以行和列是相等的。

如果你看图片,很明显看到在每个块的开始处,紧接在上面(或向左)的单元格是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