[SciPy-user] Ignoring pixels with gaussian_filter

Thomas Robitaille thomas.robitaille@gmail....
Fri Apr 24 22:20:44 CDT 2009


Hi Zach,

>> Is there a way to get gaussian_filter to simply ignore such pixels
>> when smoothing? (apart from writing a gaussian filter algorithm from
>> scratch!)
>
> No simple way to get gaussian_filter to ignore nan pixels when doing
> the convolution.
> You could write your own convolution function in cython [snip]

I looked into this, and figured out how to write my own filter. It  
does the job, but is very slow. The code is below, and takes 11s on a  
300x300 array with a filter size of 31x31 on my computer. How could I  
use cython to speed things up? (I know that I should really pass the  
filter size and the filter sigma as arguments using e.g.  
extra_arguments, but I want to try and get it to run as fast as  
possible by computing the gaussian filter only once.)

Thanks!

Thomas

---

import numpy as np
from scipy.ndimage import generic_filter

# size of filter (in both directions)
s = 31

# center of filter (in both directions)
c = 16

# sigma of filter (in both directions)
sigma = 5.

# define gaussian function
def gaussian(cx, cy, w):
     return lambda x,y: np.exp(-(((cx-x)/w)**2+((cy-y)/w)**2)/2)

# define gaussian filter
x,y = np.mgrid[0:s,0:s]
filt = gaussian(c,c,sigma)(x,y).ravel()

# define custom filter
def custom_filter(values):
     mask = np.where(np.isnan(values) == False)
     return np.sum(values[mask]*filt[mask])/np.sum(filt[mask])

# the function to test the custom filter
def do():
     a = np.ones((300,300))
     b =  
generic_filter(a,custom_filter,size=s,mode='constant',cval=np.nan)

---


More information about the SciPy-user mailing list