%
% close filter -- erode then dilate
%
close all;
clear all;
i=imread('noise_2.gif');
im = i;
im2 = im;

% show original image
figure;imshow(i);

% get image size
siz = size(i);

% do erosion first
for j=[2:siz(2)-1]
    for k=[2:siz(1)-1]
        mat = [i(j-1,k-1),i(j-1,k),i(j-1,k+1), i(j,k-1),i(j,k),i(j,k+1),i(j+1,k-1),i(j+1,k),i(j+1,k+1)];
        im(j,k) = min(mat);
    end
end

% show erosion image
figure;imshow(im);

% dilate the eroded image
for j=[2:siz(2)-1]
    for k=[2:siz(1)-1]
        mat = [im(j-1,k-1),im(j-1,k),im(j-1,k+1), im(j,k-1),im(j,k),im(j,k+1),im(j+1,k-1),im(j+1,k),im(j+1,k+1)];
        im2(j,k) = max(mat);
    end
end

% show processed image
figure;imshow(im2);