6

I have a n-dimensional vector (1xn dataset, and it is not image data), and I want to apply a Gaussian filter to it. I have the Image Processing Toolkit, and a few others (ask if you need a list).

Presumably I can make the hsize parameter of the fspecial function something like [1 n]. Can I still use imfilter to apply it to my vector as the next step, or should I be using something else?

I've seen quite a few examples on how to apply a Gaussian filter to two dimensional image data in Matlab, but I'm still relatively new to Matlab as a platform so an example would be really good.

Note: I'm not currently in a position to just try it and see what happens (not currently on a machine with Matlab installed), otherwise I would have tried it first and only asked if I ran into problems using fspecial and imfilter.

Iskar Jarak
  • 5,136
  • 4
  • 38
  • 60

1 Answers1

21

Why not create the Gaussian filter yourself? You can look at the formula in fspecial (or any other definition of a Gaussian):

sigma = 5;
sz = 30;    % length of gaussFilter vector
x = linspace(-sz / 2, sz / 2, sz);
gaussFilter = exp(-x .^ 2 / (2 * sigma ^ 2));
gaussFilter = gaussFilter / sum (gaussFilter); % normalize

and in order to apply it you can use filter:

y = rand(500,1);
yfilt = filter (gaussFilter,1, y);

and don't forget the filter has latency, which means the filtered signal is shifted as compared to the input signal. Since this filter is symmetric, you can get a non-shifted output by using conv instead of filter, and use the same option:

yfilt = conv (y, gaussFilter, 'same');
honi
  • 946
  • 1
  • 7
  • 18
Itamar Katz
  • 9,544
  • 5
  • 42
  • 74
  • 3
    Well, I don't really see a need to write my own function if other existing functions will do the job just as well, but yes, creating the filter myself does solve the problem. Thanks. By the way, am I correct in believing that commonly the size is 6 (plus-minus 3) times the sigma value? – Iskar Jarak Aug 09 '11 at 10:00
  • 1
    It really depends on the application - but generally you do want the Gaussian tails to die out so that truncating the filter does not have a significant effect (since the tails go to 0 at +-infinity, you must truncate to have a finite length filter). So yes, going 4 or more sigmas to each side guarantees it. – Itamar Katz Aug 09 '11 at 10:53
  • 2
    Of course, there is a need to write your own function, especially when it is part of a costly toolbox! What if the number of Matlab Image Toolbox licenses were finite in your company or university? It happens! – Wok Jul 31 '14 at 16:43
  • 3
    if you are using this piece of code, don't forget to replace size with something else, you may spend a lot of time debugging – Bharat Aug 25 '15 at 12:37