Search code examples
pythonnumpynumpy-ndarraybounding-box

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


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

Solution

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