![](/img/trans.png)
[英]How to find the largest blank(white) square area in the doc and return its coordinates and area?
[英]How to find the largest area in a given matrix and return its position/boundries
我試圖實現迷宮生成遞歸除法算法,在我的實現中我陷入了所述算法的主要部分之一。
假設我有一個這樣的矩陣
[
['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]
,我應該有一個確定它是橫向大還是縱向大的方法,例如,我可以再次對這個特定區域使用相同的 function,因為它在縱向上很大,它在所述區域上生成一條隨機線並將其划分並function 重復
[
['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'],
]
謝謝
假設您只對 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'
您發布的鏈接幾乎給出了解決方案。
這是您可以執行的操作:
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)
start
和stop
現在將保存最大補丁的極值點的坐標,在本例中為 (0, 3) 和 (4, 4)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.