www.gusucode.com > images 案例代码 matlab源码程序 > images/CompareResultsOfAveragingFilterAndMedianFilterExample.m

    %% Remove Noise Using an Averaging Filter and a Median Filter
% This example shows how to remove salt and pepper noise from an image
% using an averaging filter and a median filter to allow comparison of the
% results. These two types of filtering both set the value of the output
% pixel to the average of the pixel values in the neighborhood around the
% corresponding input pixel. However, with median filtering, the value of
% an output pixel is determined by the median of the neighborhood pixels,
% rather than the mean. The median is much less sensitive than the mean to
% extreme values (called outliers). Median filtering is therefore better
% able to remove these outliers without reducing the sharpness of the
% image.
%
% Note: Median filtering is a specific case of order-statistic
% filtering, also known as rank filtering. For information about
% order-statistic filtering, see the reference page for the |ordfilt2|
% function.
%%
% Read image into the workspace and display it. 
I = imread('eight.tif');
figure
imshow(I)
%%
% For this example, add salt and pepper noise to the image. This type of
% noise consists of random pixels being set to black or white (the extremes
% of the data range).
J = imnoise(I,'salt & pepper',0.02);
figure
imshow(J)
%%
% Filter the noisy image, |J|, with an averaging filter and display the
% results. The example uses a 3-by-3 neighborhood.
Kaverage = filter2(fspecial('average',3),J)/255;
figure
imshow(Kaverage)
%%
% Now use a median filter to filter the noisy image, |J|. The example also
% uses a 3-by-3 neighborhood. Display the two filtered images side-by-side
% for comparison. Notice that |medfilt2| does a better job of removing
% noise, with less blurring of edges of the coins.
Kmedian = medfilt2(J);
imshowpair(Kaverage,Kmedian,'montage')