[Numpy-discussion] the neighbourhood of each element of an array
Fri Feb 23 13:53:05 CST 2007
Scipy's ndimage module has a function that takes a generic callback
and calls it with the values of each neighborhood (of a given size,
and optionally with a particular "mask" footprint) centered on each
array element. That function handles boundary conditions, etc nicely.
Unfortunately, I'm not sure if it works with masked arrays, and I
think it hands a ravel'd set of pixels back to the callback function.
You could probably hack masking in there by passing it the mask
concatenated to the array, and then deal with the mask explicitly.
On Feb 23, 2007, at 11:39 AM, Bryan Cole wrote:
> On Fri, 2007-02-23 at 17:38 +0100, email@example.com wrote:
>> 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
>> Ncol = x.shape
>> 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)])
> how about something like
> er = Nrow - d
> ec = Ncol - d
> y = array([x[i:er+i, j:ec+j] for j in arange(-d,d)
> for i in arange(-d,d)])
> now you're looping over a small array and combining slices of the big
> array (as opposed to looping over the big array and combining slices
> from a small one). This should be faster for large Nrow, Ncol.
>> 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
>> Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
> Numpy-discussion mailing list
More information about the Numpy-discussion