【问题标题】:Detecting rectangles (sub-arrays of same element value) in 2-d list在二维列表中检测矩形(相同元素值的子数组)
【发布时间】:2016-08-08 16:50:33
【问题描述】:

矩形定义为 1 和 0 的二维数组中的任何矩形形状的零部分。典型例子:

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

在这个例子中,有三个这样的数组:

我的目标是确定每个数组的坐标(外部 3 个极端)。

我首先将二维 list 转换为 numpy 数组:

image_as_np_array = np.array(two_d_list)

然后我可以得到所有零的坐标:

np.argwhere(image_as_np_array == 0)

但这只是提供了一种通过遍历每一行并调用.index(),然后结合二维列表中该行的索引来获取索引的捷径。

我现在设想做一些事情,比如删除 np.argwhere()(或 np.where())的任何元素,其中只有一次出现 0(实际上忽略了任何 不能 构成矩形),然后尝试对齐连续坐标,但我一直在弄清楚如何处理任何行可能包含多个单个矩形的一部分的情况(如上面的第 3 行和第 4 行的情况)。是否有 numpy 函数或我可以利用的函数?

【问题讨论】:

  • 每个矩形是否必须至少有两行两列?
  • 假设我将一个 2x2 正方形贴在一个 3x3 正方形的侧面,得到一个看起来像一个 3x5 矩形的形状,其中两个角 0 被切掉,我算作前面提到的两个正方形吗?我计算它包含的更大的 2x5 矩形并“浪费”其他 3 个 0?
  • 1 x n 或 n x 1 是不是矩形?从示例中我假设没有..
  • 那么一个0的矩形一定被1完全包围?在这种情况下,您示例中最右边的矩形无效。
  • 但是右上角多了一个 0。该矩形包含在一个连续的非矩形形状内。矩形的右上角有四个 0 邻居。

标签: python list numpy multidimensional-array scipy


【解决方案1】:

我使用the Sweep line method 编写了一个简单的算法。这个想法是,您逐列遍历您数组的列,并将一系列零检测为潜在的新矩形。在每一列中,您必须检查之前检测到的矩形是否已结束,如果是,请将它们添加到结果中。

import numpy as np
from sets import Set
from collections import namedtuple

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

Rectangle = namedtuple("Rectangle", "left top bottom right")

def sweep(A):
    height = A.shape[0]
    length = A.shape[1]
    rectangles = dict()  # detected rectangles {(rowstart, rowend): col}
    result = []

    # sweep the matrix column by column
    for i in xrange(length):
        column = A[:, i]

        # for currently detected rectangles check if we should extend them or end
        for r in rectangles.keys():
            # detect non rectangles shapes like requesten in question edit and del those rectangles
            if all([x == 0 for x in column[r[0]:r[1]+1]]) and ((r[0]-1>0 and column[r[0]-1]==0) or (r[1]+1<height and column[r[1]+1]==0)):
                del rectangles[r]
            elif any([x == 0 for x in column[r[0]:r[1]+1]]) and not all([x == 0 for x in column[r[0]:r[1]+1]]):
                del rectangles[r]
            # special case in the last column - add detected rectangles
            elif i == length - 1 and all([x == 0 for x in column[r[0]:r[1]+1]]):
               result.append(Rectangle(rectangles[r], r[0], r[1], i))
            # if detected rectangle is not extended - add to result and del from list
            elif all([x == 1 for x in column[r[0]:r[1]+1]]):
                result.append(Rectangle(rectangles[r], r[0], r[1], i-1))
                del rectangles[r]

        newRectangle = False
        start = 0
        # go through the column and check if any new rectangles appear
        for j in xrange(height):
            # new rectangle in column detected
            if column[j] == 0 and not newRectangle and j+1 < height and column[j+1] == 0:
                start = j
                newRectangle = True
            # new rectangle in column ends
            elif column[j] == 1 and newRectangle:
                # check if new detected rectangle is already on the list
                if not (start, j-1) in rectangles:
                    rectangles[(start, j-1)] = i
                newRectangle = False

    # delete single column rectangles
    resultWithout1ColumnRectangles = []
    for r in result:
        if r[0] != r[3]:
            resultWithout1ColumnRectangles.append(r)
    return resultWithout1ColumnRectangles

print example
print sweep(example)

返回:

[[1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 0]
 [1 1 1 0 0 0 1 0 0]
 [1 0 1 0 0 0 1 0 0]
 [1 0 1 1 1 1 1 1 1]
 [1 0 1 0 0 1 1 1 1]
 [1 1 1 0 0 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]]
[Rectangle(left=3, top=5, bottom=6, right=4), 
 Rectangle(left=3, top=2, bottom=3, right=5)]

【讨论】:

  • 每个返回列表中的六个数字代表什么?我建议像我一样使用namedtuple。
  • 另外你应该阅读 cmets,我们得出的结论是三个矩形之一不应该被计算在内。
  • 矩形不是不能在最后一列结束,而是不能有任何突出的部分。再仔细阅读 cmets。
  • @Tony 谢谢。根据亚历克斯的正确观察,我更新了问题以显示新图像。只有两个矩形(单宽,单高)是有效的。
【解决方案2】:

我不知道 numpy,所以这里有一个简单的 Python 解决方案:

from collections import namedtuple

Rectangle = namedtuple("Rectangle", "top bottom left right")

def find_rectangles(arr):

    # Deeply copy the array so that it can be modified safely
    arr = [row[:] for row in arr]

    rectangles = []

    for top, row in enumerate(arr):
        start = 0

        # Look for rectangles whose top row is here
        while True:
            try:
                left = row.index(0, start)
            except ValueError:
                break

            # Set start to one past the last 0 in the contiguous line of 0s
            try:
                start = row.index(1, left)
            except ValueError:
                start = len(row)

            right = start - 1

            if (  # Width == 1
                  left == right or
                  # There are 0s above
                  top > 0 and not all(arr[top-1][left:right + 1])):
                continue

            bottom = top + 1
            while (bottom < len(arr) and
                   # No extra zeroes on the sides
                   (left == 0 or arr[bottom][left-1]) and
                   (right == len(row) - 1 or arr[bottom][right + 1]) and
                   # All zeroes in the row
                   not any(arr[bottom][left:right + 1])):
                bottom += 1

            # The loop ends when bottom has gone too far, so backtrack
            bottom -= 1

            if (  # Height == 1
                  bottom == top or
                  # There are 0s beneath
                  (bottom < len(arr) - 1 and
                   not all(arr[bottom + 1][left:right+1]))):
                continue

            rectangles.append(Rectangle(top, bottom, left, right))

            # Remove the rectangle so that it doesn't affect future searches
            for i in range(top, bottom+1):
                arr[i][left:right+1] = [1] * (right + 1 - left)

    return rectangles

对于给定的输入,输出为:

[Rectangle(top=2, bottom=3, left=3, right=5),
 Rectangle(top=5, bottom=6, left=3, right=4)]

这是正确的,因为 cmets 表示右侧的“矩形”不计算在内,因为有一个额外的 0 伸出。不过,我建议您添加更多测试用例。

我希望它相当快,因为​​大部分低级迭代都是通过调用 index 和 any 完成的,因此即使没有 numpy 的帮助,C 代码的使用也不错。

【讨论】:

  • 您的解决方案有多复杂?
  • 计算确切的复杂度有点困难,但我认为它非常好。可能是O(m*n),至少大约是这样。我已经消除了反复检查先前发现的矩形中是否包含的明显弱点。
  • 据我了解:当您找到0 时,您会尝试将其尽可能分散到矩形,然后用1s 将其涂黑 - 它的O(n * m)。不过,线性内存复杂性可能是更大数组的问题。
  • 如果你可以将整个数组保存在内存中,你大概可以保存两次。如果这确实是一个问题,您可以避免复制数组并在最后恢复更改:这很容易做到,因为所有的矩形都被记录了。或者只是修改数组,根据用例可能无关紧要。
  • @Wedoso 这对这个问题是正确的,宽度/长度为 1 的矩形被忽略 - 请参阅 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
相关资源
最近更新 更多