Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gaussian filter in scipy

I want to apply a Gaussian filter of dimension 5x5 pixels on an image of 512x512 pixels. I found a scipy function to do that:

scipy.ndimage.filters.gaussian_filter(input, sigma, truncate=3.0)

How I choose the parameter of sigma to make sure that my Gaussian window is 5x5 pixels?

like image 995
user2863620 Avatar asked Aug 09 '14 07:08

user2863620


2 Answers

Check out the source code here: https://github.com/scipy/scipy/blob/master/scipy/ndimage/filters.py

You'll see that gaussian_filter calls gaussian_filter1d for each axis. In gaussian_filter1d, the width of the filter is determined implicitly by the values of sigma and truncate. In effect, the width w is

w = 2*int(truncate*sigma + 0.5) + 1 

So

(w - 1)/2 = int(truncate*sigma + 0.5) 

For w = 5, the left side is 2. The right side is 2 if

2 <= truncate*sigma + 0.5 < 3 

or

1.5 <= truncate*sigma < 2.5 

If you choose truncate = 3 (overriding the default of 4), you get

0.5 <= sigma < 0.83333... 

We can check this by filtering an input that is all 0 except for a single 1 (i.e. find the impulse response of the filter) and counting the number of nonzero values in the filtered output. (In the following, np is numpy.)

First create an input with a single 1:

In [248]: x = np.zeros(9)  In [249]: x[4] = 1 

Check the change in the size at sigma = 0.5...

In [250]: np.count_nonzero(gaussian_filter1d(x, 0.49, truncate=3)) Out[250]: 3  In [251]: np.count_nonzero(gaussian_filter1d(x, 0.5, truncate=3)) Out[251]: 5 

... and at sigma = 0.8333...:

In [252]: np.count_nonzero(gaussian_filter1d(x, 0.8333, truncate=3)) Out[252]: 5  In [253]: np.count_nonzero(gaussian_filter1d(x, 0.8334, truncate=3)) Out[253]: 7 
like image 77
Warren Weckesser Avatar answered Oct 01 '22 20:10

Warren Weckesser


Following the excellent previous answer:

  1. set sigma s = 2
  2. set window size w = 5
  3. evaluate the 'truncate' value: t = (((w - 1)/2)-0.5)/s
  4. filtering: filtered_data = scipy.ndimage.filters.gaussian_filter(data, sigma=s, truncate=t)
like image 39
Gustavo Ortiz Avatar answered Oct 01 '22 21:10

Gustavo Ortiz