Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Gaussian filter of required length in python

Tags:

python

scipy

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)
like image 880
user1482980 Avatar asked Jun 26 '12 14:06

user1482980


2 Answers

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])
like image 60
quazgar Avatar answered Oct 27 '22 01:10

quazgar


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
like image 28
Junuxx Avatar answered Oct 27 '22 00:10

Junuxx