% ==================================================================================================
% Module:   median.m
%
% Usage:    Median filter an image
%
% Purpose: 
%     Performs the median filter on an image of a specified window size.
%
%     
% Input Variables:
%     fxy     input image (binary data)
%     A       median window
%     
% Returned Results:
%     The image, median filtered with a window of size A.
%     
% Restrictions/Notes:
%     This function is geared for binary images. 
%
% See Also:
% 
% References:
% 
% Author:       Justin Ford
% Date:         2/1/04
% Revisions:    none
% ==================================================================================================


function result = med(fxy, A)

	result=zeros(size(fxy,1),size(fxy,2));
	
	A_row_dim = size(A,1);
	A_col_dim = size(A,2);
	
	if (A_row_dim > 1)
        row_diff = (A_row_dim - 1)/2;
	else
        row_diff = 0;
	end
	
	if (A_col_dim > 1)
        col_diff = (A_col_dim - 1)/2;
	else
        col_diff = 0;
	end
	
	for i=1:1:size(fxy,1)
        for j=1:1:size(fxy,2)
            if ( (i > row_diff) & (i < ( size(fxy,1) - row_diff )) & (j > col_diff) & (j < ( size(fxy,1) - col_diff )) )         
                result(i,j) = med( fxy((i-row_diff):(i+row_diff),(j-col_diff):(j+col_diff)) );
            end
        end
	end

function median = med(x)
	
	x_row_dim = size(x,1);
	x_col_dim = size(x,2);
	
	% If x is a matrix use rowcat() to make it a vector
	if ( (x_row_dim>1) & (x_col_dim>1) )
        x = rowcat(x);
        x_row_dim = 1;
        x_col_dim = size(x,2);
	end
	
	if (x_row_dim>1)
        sorted = zeros(x_row_dim,1);
        x_dim = x_row_dim;
	else
        sorted = zeros(1,x_col_dim);
        x_dim = x_col_dim;
	end
	
	sorted = sort(x);
	
	if (mod(x_dim,2)==0)
        median = (sorted(x_dim/2) + sorted(x_dim/2+1))/2;
	else
        median = sorted(x_dim/2+1/2);
	end
    
function row_vector = rowcat( M )

	M_row_dim = size(M,1);
	M_col_dim = size(M,2);
	
	row_vector = M(1,:);
	
	for i = (2:M_row_dim)
        row_vector = [row_vector M(i,:)];
	end