Skip to content
Snippets Groups Projects
gtMask2Poly.m 2.1 KiB
Newer Older
Andrew King's avatar
Andrew King committed
function [x,y]=gtMask2Poly(mask)
% GTMASK2POLY.M Converts a black and white outline to a series of points.
% Usage:
%    [x,y]=gtMask2Poly(mask);
%
% Example:
% %create a simple outline image
% im=zeros(10,10);
% im(3,3:7)=1;im(7,3:7)=1; im(3:7,3)=1;im(3:7,7)=1;
% im = not(im);
% % convert to polygon
% [x,y]=gtMask2Poly(im);
% % display results
% figure
% imagesc(im)
% colormap(gray)
% hold on
% plot(x,y,'ro');
% hold off
%
%
% THIS CODE IS NOT ROBUST!
debug=false;

% some details
fprintf('Image size: %d x %d\n',size(mask)')
% put 10% padding around it
pad=max(1,round(0.1*max(size(mask))));
mask_padded=gtPlaceSubImage(mask,zeros(size(mask)+(2*pad)),pad,pad);
if debug
  imagesc(mask_padded);colormap(gray),axis image
end
[fx,fy]=gradient(double(mask_padded));
fmag=sqrt(fx.^2+fy.^2);

[u,v]=GVF(fmag,0.2,15);
gvfmag=sqrt(u.^2+v.^2);
% normalise gvf
unorm=u./(gvfmag+eps);
vnorm=v./(gvfmag+eps);

% for image with area 5000
defaultmaskarea=5000;
defaultsnakeoptions.elasticity=5;
defaultsnakeoptions.rigidity=0.1;
defaultsnakeoptions.viscosity=1;
defaultsnakeoptions.forcefactor=1;
defaultsnakeoptions.iterations=5;
% perhaps make variation here?

maskarea=prod(size(mask))
arearatio=maskarea/defaultmaskarea;

snakeoptions=defaultsnakeoptions;
%fprintf('Scaling parameters to take account of image size (area ratio: %d)\n',round(arearatio));

%snakeoptions.forcefactor=snakeoptions.forcefactor*arearatio;
%snakeoptions.elasticity=snakeoptions.elasticity*arearatio;
%snakeoptions.viscosity=snakeoptions.viscosity/arearatio;
snakeoptions.iterations=snakeoptions.iterations*arearatio;
snakeforcefield.x=unorm;
snakeforcefield.y=vnorm;


x=[5 size(fmag,2)-5 size(fmag,2)-5 5];
y=[5 5 size(fmag,1)-5 size(fmag,1)-5];

[x,y]=snakeinterp(x,y,2,1);
if debug
  figure(99)
  imagesc(mask_padded),colormap(gray),axis image
  hold on
  quiver(u,v)
  drawnow
end
for i=1:10,
  if debug
    hp=snakedisp(x,y,'g.-');
    title(['Deformation in progress,  iter = ' num2str(i*snakeoptions.iterations)])
    drawnow
  end
  [x,y]=snakedeform(x,y,snakeforcefield,snakeoptions);
  [x,y]=snakeinterp(x,y,2,1);
end
if debug
  snakedisp(x,y,'r-')
end
x=x-pad;
y=y-pad;