【问题标题】:How to find the largest area in a given matrix and return its position/boundries如何找到给定矩阵中的最大区域并返回其位置/边界
【发布时间】:2021-05-10 06:00:38
【问题描述】:

我正在尝试实现maze generation recursive division algorithm,但在我的实现中,我陷入了上述算法的主要部分之一。

假设我有一个这样的矩阵

[
  ['0', '0', '1', '0', '0'],
  ['0', '0', '1', '0', '0'],
  ['0', '0', '1', '0', '0'],
  ['1', '1', '1', '0', '0'],
  ['0', '0', '1', '0', '0'],
]

在这里我希望能够在矩阵中找到'0' 的最大区域并返回它的起点和终点,在这种情况下将是[0][3] to [4][4],我应该有办法确定它是否是宽度方向大或长度方向大,因此我可以再次对这个特定区域使用相同的功能,例如,因为它在长度方向上很大,所以它在所述区域上创建一条随机线并将其划分并且函数重复

[
  ['0', '0', '1', '0', '0'],
  ['0', '0', '1', '1', '1'],
  ['0', '0', '1', '0', '0'],
  ['1', '1', '1', '0', '0'],
  ['0', '0', '1', '0', '0'],
]

I found a similar answer but I cant find out how to implement that to my situation

谢谢

【问题讨论】:

    标签: python arrays


    【解决方案1】:

    假设您只对 0 的正方形区域感兴趣,您可以建立在您链接的答案的基础上,如下所示:

    from scipy import ndimage
    
    label, num_label = ndimage.label(matrix == '0')
    size = np.bincount(label.ravel())
    biggest_label = size[1:].argmax() + 1
    clump_mask = label == biggest_label
    
    a, b = np.where(clump_mask)
    coordinates = (a[0], b[0]), (a[-1], b[-1])
    
    ((0, 3), (4, 4))
    

    然后,如果您想知道它是更大的长度还是宽度,您可以使用您的坐标:

    if (abs(coordinates[0][0] - coordinates[1][0]) > 
        abs(coordinates[0][1] - coordinates[1][1])):
        bigger = 'length'
    else:
        bigger = 'width'
    

    【讨论】:

    • 为此,我需要将矩阵转换为 np 数组,对吗?也感谢您的回复!
    • 是的,没错。您可以在矩阵上调用 np.array() ,这应该可以工作。
    • 好的,我会试试看是否有效,谢谢
    【解决方案2】:

    您发布的链接几乎给出了解决方案。

    你可以这样做:

    import numpy as np
    from scipy import ndimage
    
    # Your matrix
    array = np.array([
      ['0', '0', '1', '0', '0'],
      ['0', '0', '1', '0', '0'],
      ['0', '0', '1', '0', '0'],
      ['1', '1', '1', '0', '0'],
      ['0', '0', '1', '0', '0'],
    ])
    
    # Finds the contiguous locations (labels) of '0' elements
    label, num_label = ndimage.label(array == '0')
    size = np.bincount(label.ravel())
    biggest_label = size[1:].argmax() + 1
    
    # Gets the extreme point locations of the biggest area
    seq = np.arange(array.size).reshape(array.shape)
    _, _, start, stop = ndimage.extrema(seq, label, index=biggest_label)
    

    startstop 现在将保存最大补丁的极值点坐标,在本例中为 (0, 3) 和 (4, 4)。

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 2011-06-07
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多