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

Python 如何找到数组中边缘附近的所有相邻值?,python,numpy,numpy-ndarray,bounding-box,Python,Numpy,Numpy Ndarray,Bounding Box,我有一个由0s和1s组成的数组。 首先,我需要找到所有邻居1。我设法做到了这一点(解决方案在下面的链接中) 第二,我需要选择那些,其中任何集群元素位于顶部边界附近 我可以找到邻居的代码来自 但我只需要选择那些与顶部边界接触的 以下是二维阵列的示例: 输入: 输出: 这是一个连接组件标签问题。您可以使用来标识连接的组件,检查找到的对象的哪些切片包含0作为起点,并使用它们填充新数组: from scipy import ndimage # labels the connected componen

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

第二,我需要选择那些,其中任何集群元素位于顶部边界附近

我可以找到邻居的代码来自

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

以下是二维阵列的示例:

输入:

输出:


这是一个连接组件标签问题。您可以使用来标识连接的组件,检查找到的对象的哪些切片包含
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]


用kDTree算法试试看。
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]])
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]])