[SciPy-User] Convolving an ndarray by a function

David Baddeley david_baddeley@yahoo.com...
Wed Sep 26 23:17:29 CDT 2012


Hi Jeremy,

what you are after is scipy.ndimage.generic_filter. For your particular case (std. deviation), there is also a neat approximate solution using just standard uniform filters, which, although not strictly accurate, might be close enough for many applications and is considerably faster (a quick test gives a speedup of ~ 300x). Assuming your data array is called x:

from scipy import ndimage

#calculate the mean of a 3x3 ROI round each point
xm = ndimage.uniform_filter(x, 3)

#the standard deviation is the mean of the sum of squared differences to the mean
#note that here we are subtracting the mean of the local neighbourhood of each pixel, rather than that of the central pixel
sigma = np.sqrt(ndimage.uniform_filter((x - xm)**2, 3)

cheers,
David


________________________________
 From: "Solbrig, Mr. Jeremy" <Jeremy.Solbrig@nrlmry.navy.mil>
To: "'scipy-user@scipy.org'" <scipy-user@scipy.org> 
Sent: Thursday, 27 September 2012 8:25 AM
Subject: [SciPy-User] Convolving an ndarray by a function
 
Hi all,

I have run into a situation where I need to calculate the standard deviation for each NxM box within an ndarray.  I am wondering if there is a function available that would allow me to convolve (may not be the correct word here) an ndarray by a function and return an array of the same size as the original array.  Something like this:

>>> foo = np.arange(10000).reshape([100,100])
>>> stddev_arr = foo.funcconvolve([3, 3], np.std) 
>>> stddev_arr.shape == foo.shape
True

Such that each point within stddev_arr is the standard deviation of a 3x3 box around each point in foo.  

I'm sure I could code this in a loop, but I expect that there is a better solution.

Thanks for your help,
Jeremy

Jeremy Solbrig
NRL Monterey
jeremy.solbrig@nrlmry.navy.mil
(831) 656-4885 

_______________________________________________
SciPy-User mailing list
SciPy-User@scipy.org
http://mail.scipy.org/mailman/listinfo/scipy-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120926/ad3effec/attachment.html 


More information about the SciPy-User mailing list