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

% show image
figure;imshow(i);

% get image size
siz = size(i);

% dilate image
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) = max(mat);
    end
end

% show dilated image
figure;imshow(im);

% do erosion
for j=[2:siz(2)-1] 
    for k=[2:siz(1)-1]
        mat = [im(j-1,k-1),im(j-1,k),i(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) = min(mat);
    end
end

% show dilated and erosion image
figure;imshow(im2);