如何找到数组边缘附近的所有邻居值?

How to find all neighbour values near the edge in array?

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

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

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

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

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

输入:

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

这是一个连通分量标记问题。您可以使用 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]])