【问题标题】:How to find all neighbour values near the edge in array?如何在数组中找到边缘附近的所有邻居值?
【发布时间】:2026-01-20 14:40:01
【问题描述】:

我有一个由0s 和1s 组成的数组。 首先,我需要找到所有邻居1。我设法做到了(解决方案在下面的链接中)。

其次,我需要选择那些,集群的任何元素位于顶部边界附近。

我可以使用here 的代码找到邻居。

但我只需要选择与顶部边界接触的那些。

这是一个二维数组的例子:

输入:

array([[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [1, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])

输出:

array([[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

【问题讨论】:

标签: python numpy numpy-ndarray bounding-box


【解决方案1】:

这是一个连通分量标注问题。您可以使用scipy.ndimage 来识别连接的组件,检查找到的对象的哪些切片包含0 作为起点,并使用它们来填充新数组:

from scipy import ndimage

# labels the connected components with a different digit
x_components, _ = ndimage.measurements.label(a, np.ones((3, 3)))
# returns slices with the bounding boxes
bboxes = ndimage.measurements.find_objects(x_components)
# fills a new array with 1 on those slices
b = np.zeros_like(a)
for bbox in s:
    if bbox[0].start == 0:
        b[bbox] = a[bbox]

print(b)

array([[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

【讨论】: