%%%%%%% distance transform function
function d=disttrans(x,w)
%
bw=rot90(rot90(w)); % backward mask
[a,b]=size(w); % size of the mask
[r,c]=size(x); % size of the image
xz=zeros(r+a-1,c+b-1);
a=(a-1)/2; b=(b-1)/2;
xz(a+1:r+a,b+1:c+b)=x; % zero-padded image
%
xz(find(xz==0))=Inf; % zeros replaced by infinity
xz(find(xz==1))=0;% 1s replaced by zero
% 
for m=a+1:r+a % forward pass
  for n=b+1:c+b
    xz(m,n)=min(min(xz(m-a:m+a,n-b:n+b)+w));
  end;
end;
%
for m=r+a:-1:a+1 % backward pass
  for n=c+b:-1:b+1
    xz(m,n)=min(min(xz(m-a:m+a,n-b:n+b)+bw));
  end;
end;
d=xz(a+1:r+a,b+1:c+b);


