11

Could anyone suggest which library supports creation of a gaussian filter of required length and sigma?I basically need an equivalent function for the below matlab function:

fltr = fspecial('gaussian',[1 n],sd)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
user1482980
  • 167
  • 2
  • 3
  • 9

4 Answers4

14

You don't need a library for a simple 1D gaussian.

from math import pi, sqrt, exp

def gauss(n=11,sigma=1):
    r = range(-int(n/2),int(n/2)+1)
    return [1 / (sigma * sqrt(2*pi)) * exp(-float(x)**2/(2*sigma**2)) for x in r]

Note: This will always return an odd-length list centered around 0. I suppose there may be situations where you would want an even-length Gaussian with values for x = [..., -1.5, -0.5, 0.5, 1.5, ...], but in that case, you would need a slightly different formula and I'll leave that to you ;)

Output example with default values n = 11, sigma = 1:

>>> g = gauss()
1.48671951473e-06
0.000133830225765
0.00443184841194
0.0539909665132
0.241970724519
0.398942280401
0.241970724519
0.0539909665132
0.00443184841194
0.000133830225765
1.48671951473e-06

>>> sum(g)
0.99999999318053079
Junuxx
  • 14,011
  • 5
  • 41
  • 71
  • I was expecting it returns something like guassian curve after plt.hist(g) but it's a half guess – Moj Dec 12 '12 at 00:50
  • 1
    Great, simple answer! It's always preferable to avoid using libraries, when it's possible, so you actually understand what's going on in your code :). For the case of an even `n`, the only thing to change is `r = np.linspace(-int(n/2)+0.5,int(n/2)-0.5, n) `. – Tropilio Jul 05 '19 at 09:31
6

Perhaps scipy.ndimage.filters.gaussian_filter? I've never used it, but the documentation is at: https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.filters.gaussian_filter.html

sv_jan5
  • 1,543
  • 16
  • 42
IanVS
  • 3,497
  • 1
  • 20
  • 23
4

Try scipy.ndimage.gaussian_filter, but do you really want the kernel or do you also want to apply it? (In which case you can just use this function.) In the former case, apply the filter on an array which is 0 everywhere but with a 1 in the center. For the easier-to-write 1d case, this would be for example:

>>> ndimage.gaussian_filter1d(np.float_([0,0,0,0,1,0,0,0,0]), 1)
array([  1.33830625e-04,   4.43186162e-03,   5.39911274e-02,
         2.41971446e-01,   3.98943469e-01,   2.41971446e-01,
         5.39911274e-02,   4.43186162e-03,   1.33830625e-04])
quazgar
  • 4,304
  • 2
  • 29
  • 41
0

If run-time speed is of importance I highly recommend creating the filter once and then using it on every iteration. Optimizations are constantly made but a couple of years ago this significantly sped some code I wrote. ( The above answers show how to create the filter ).

Dan Erez
  • 1,364
  • 15
  • 16