Python, Numpy. Find values in 2d array and replace neighbors with 1

Viewed 166

I have a 10x10 array with zeros and ones.

I would like to:

  1. find the position of each cell with a value of 1.

  2. replace all the neighbors with 1. neighbors= any cell to a n=1 distance (also diagonal). Example:

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

output:

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

I am trying finding indexes but It does not work:

a=np.where(a==1)+1

From other post I also try getting the neighbors with this function:

def n_closest(x,n,d=1):
    return x[n[0]-d:n[0]+d+1,n[1]-d:n[1]+d+1] 

But this does not work for the edges

Thanks

1 Answers

If you don't mind using scipy, a 2D convolution will solve the problem quickly:

import numpy as np
from scipy import signal

# Input array
X = np.array([[0, 1, 0, 0, 0],
              [0, 0, 0, 0, 0],
              [0, 0, 1, 0, 0],
              [1, 0, 0, 0, 0],
              [0, 0, 0, 1, 1]])

# We apply a 2D convolution with a 3x3 kernel and we check which value are bigger than 0.
R = (signal.convolve2d(X,np.ones((3,3)),mode='same')>0).astype(int)
# R = array([[1, 1, 1, 0, 0],
#            [1, 1, 1, 1, 0],
#            [1, 1, 1, 1, 0],
#            [1, 1, 1, 1, 1],
#            [1, 1, 1, 1, 1]])  

# Finally we extract the index 
x,y = np.where(R)
Related