[Numpy-discussion] the neighbourhood of each element of an array

joris@ster.kuleuven.... joris@ster.kuleuven....
Fri Feb 23 10:38:19 CST 2007


Given a (possibly masked) 2d array x, is there a fast(er) way in Numpy to obtain
the same result as the following few lines?

d = 1                                  # neighbourhood 'radius'
Nrow = x.shape[0]
Ncol = x.shape[1]
y = array([[x[i-d:i+d+1,j-d:j+d+1].ravel() for j in range(d,Ncol-d)]      \
                                           for i in range(d,Nrow-d)])
What you get is an array containing all the elements in a neighbourhood for each
element, disregarding the edges to avoid out-of-range problems. The code above
becomes quite slow for e.g. a 2000x2000 array. Does anyone know a better


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm

More information about the Numpy-discussion mailing list