% ==================================================================================================
% Module:   dilation.m
%
% Usage:    Dilate binary image by a structuring element.
%
% Purpose: 
%     Dilates the input image by the input structuring element. This code
%     also adds a 'conservative' boundry to the image in order to allow the
%     repetitve dialtion of a structuring element with itself or other
%     structuring elements.
%
%     
% Input Variables:
%     I     input image
%     s     structuring element
%     
% Returned Results:
%     The dilated image with an added all-around border of radius(s).
%     
% Restrictions/Notes:
%     This function is geared for binary images.
%     
% See Also:
% 
% References:
% 
% Author:       Isaac Gerg
% Date:         1/15/04
% Revisions:    none
% ==================================================================================================

function O = dilation(I,s);

% x and y are switched in MATLAB and so are width and height.
sx = floor(size(s,1)/2);
sy = floor(size(s,2)/2);
fx = false;
fy = false;
if (sx*2 == size(s,1))
    fx = true;
end
if (sy*2 == size(s,2))
    fy = true;
end

iwidth = size(I,1);
iheight = size(I,2);
swidth = size(s,1);
sheight = size(s,2);

O = zeros(iwidth + 2*sx, iheight + 2*sy);

for x = 1:size(O,1),
    for y = 1:size(O,2),
        flag = false;
        for m = -sx:sx,
            for n = -sy:sy,
                if x+m-sx < 1 | x+m-sx > iwidth | y+n-sy < 1 | y+n-sy > iheight
                    continue;
                else
% The commented code is the start of a a process which allows the use of
% even sized masked in eighter dimension.
%                     if fx & ~fy
%                         flag = flag | (I(x+m-sx, y+n-sy) & s(m+sx, n+sy+1));
%                     elseif fy & ~fx
%                         flag = flag | (I(x+m-sx, y+n-sy) & s(m+sx+1, n+sy));
%                     elseif fx & fy
%                         flag = flag | (I(x+m-sx, y+n-sy) & s(m+sx, n+sy));
%                     else
                        flag = flag | (I(x+m-sx, y+n-sy) & s(m+sx+1, n+sy+1));
%                     end
                end
            end
        end
        O(x, y) = flag;
    end
end

        