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

别等时光非礼了梦想. 提交于 2020-06-27 04:02:08

问题


I have an array consisting of 0s and 1s. Firstly, I need to find all neighbour 1. I managed to do this (the solution is in the link below).

Secondly, I need to choose those, where any element of cluster located near the top boundary.

I can find neighbours with code from here.

But I need to select only those that are in contact with the top boundary.

Here is an example with a 2D array:

Input:

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

Output:

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

回答1:


This is a connected component labeling problem. You could use scipy.ndimage to identify the connected components, check which slices of the found objects contain 0 as a starting point and use them to fill the new array:

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


来源:https://stackoverflow.com/questions/57715252/how-to-find-all-neighbour-values-near-the-edge-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!