I have a 2D numpy array filled with 0 and 1, and I would like to transform it so that every value neighboring a 1 is transformed to a 1 (hence the "contamination" in the title).
For example :
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 1 0 0 0
0 0 0 0 0 0
Becomes :
0 0 0 0 0 0
0 0 1 1 1 0
0 0 1 1 1 1
0 1 1 1 1 1
0 1 1 1 1 1
0 1 1 1 0 0
I can achieve this by looping through all the values, finding the 1s, and then replacing the adjacent values :
import numpy as np
ones = []
ar = np.array([[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,1,0,0],
[0,0,0,0,1,0],
[0,0,1,0,0,0],
[0,0,0,0,0,0]])
n_row, n_col = ar.shape
for i in range(n_row):
for j in range(n_col):
if ar[i][j] == 1:
ones.append((i, j))
for x,y in ones:
# Replace neighboring values
But this seems overkill (especially because I'm planning to deal with really large arrays).
Is there a way to achieve this without having to loop through all the values ?