I need to test some basic image processing techniques in Matlab. I need to test and compare especially two types of filters: mean filter and median filter.
To smooth
h = fspecial('average', n);
filter2(h, img);
See doc fspecial
:
h = fspecial('average', n)
returns an averaging filter. n
is a 1-by-2 vector specifying the number of rows and columns in h
.
I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:
I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I
Note that for colour images you would have to apply this to each of the channels in the image.
and the convolution is defined through a multiplication in transform domain:
conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))
if one channel is considered... for more channels this has to be done every channel
I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);
imshow(I)
Note that filters can be applied to intensity images (2D matrices) using filter2
, while on multi-dimensional images (RGB images or 3D matrices) imfilter
is used.
Also on Intel processors, imfilter
can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.
f=imread(...);
h=fspecial('average', [3 3]);
g= imfilter(f, h);
imshow(g);