Easiest way to generate 1D Gaussian kernel
I am wondering what would be the easiest way to generate a 1D Gaussian kernel in python given the filter length. I think the idea is to estimate the normal distribution for the values of the vector [-length filter, ..., filter_length], is it correct?
I have done this so far, but I don't know why it is wrong:
result = np.zeros( filter_length ) mid = filter_length/2 result=[(1/(sigma*np.sqrt(2*np.pi)))*(1/(numpy.exp((i**2)/(2*sigma**2)))) for i in range(-mid,mid+1)] return result
where sigma
is the standard deviation, which is a parameter. filter-length
is also a parameter.
This is not correct because I am getting for example length = 3 and sigma = math.sqrt (1.0 / 2 / math.log (2))
[0.23485931967491286, 0.46971863934982572, 0.23485931967491286]
And it should be:
[0.25, 0.5, 0.25]
So is there a rounding problem? I do not know what's going on...
Edit I think I should trim somehow
Problem solved The problem is that I am not normalizing. I had to divide the vector by the sum of all its components.
source to share
I'm not very sure about the numpy syntax, but if you collapse the kernel with a dirac pulse, you get the same kernel as the output.
So, you can just use the inbuild feature scipy.ndimage.filters.gaussian_filter1d and use this array as input: [0, 0, 0, .. 0, 1, 0, ... 0, 0, 0]
The output should be a Gaussian kernel with a value of 1 at its peak. (replace 1 with the maximum desire in the core you want)
So, in essence, you get a Gaussian kernel that gaussian_filter1d will use as a result. This should be the easiest and least error prone way to generate a Gaussian kernel, and you can use the same approach to generate a 2d kernel with the corresponding scipy 2d function. Of course, if the goal is to do it from scratch, then this approach is only good as a reference
As for your equation:
to get [..., 0.5, ...] as a result with your formula, you need to solve,
(1/(sigma*np.sqrt(2*np.pi)) = 0.5
so the correct sigma must be
sigma = math.sqrt(2*1/np.pi)
source to share