I am trying to write a function that returns a one dimentional gauss filter. the function took sigma as a parameter. The problem is that the function returns the same array for all sigmas.
function gaussFilter=gauss(sigma)
width = 3 * sigma;
support = (-width :sigma: width);
gaussFilter= exp( - (support).^2 / (2*sigma^2));
gaussFilter = gaussFilter/ sum(gaussFilter);
Note that support array is calculated correctly but the problem arise when applying the exp.
解决方案
The idea is that the filter needs to be wide enough to represent the Gaussian function. The rule of thumb is to use filter size of at least 6*sigma.
Since the support needs to be centered around zero, that would give you the range of -3*sigma to +3*sigma (to be more accurate, it is -/+ round(6*sigma - 1)/2 to account for the zero in the middle). Hence:
function gaussFilter = gauss(sigma)
width = round((6*sigma - 1)/2);
support = (-width:width);
gaussFilter = exp( -(support).^2 ./ (2*sigma^2) );
gaussFilter = gaussFilter/ sum(gaussFilter);
Example: (all the following are equivalent)
sigma = 1.2;
width = round((6*sigma - 1)/2);
gauss(sigma)
normpdf( -width:width, 0, sigma )
fspecial('gaussian', [1 2*width+1], sigma)
h = gausswin(2*width+1)';
h = h / sum(h)