%=====================================================
% Demo program for chain-coding
% Image processing course, Ghent University, TELIN
%
% Aleksandra Pizurica, Ghent University, TELIN, 2003.
%======================================================


clear all;
A=zeros(10,10);
A(4:9,3:6)=1;
A(6:8,2)=1;

% Input contour
C=bwperim(A,8);
figure
imagesc(C);
grid on;



CONTOUR(1,:)=input('Coordinates of the first point [x y]');
CONTOUR(2,:)=input('Coordinates of the second point [x y]');
Dir=input('Direction between the first two points: ');

Count=1;
CHAIN_CODE(1)=Dir
istart=CONTOUR(1,1);
jstart=CONTOUR(1,2);

i=CONTOUR(2,1);
j=CONTOUR(2,2);
while(i~=istart | j~=jstart)
    
ForbiddenDir=mod(Dir+2,4)

if(ForbiddenDir~=0 & C(i,j+1)==1)
        Dir=0;
        j=j+1;
        
elseif(ForbiddenDir~=1 & C(i-1,j)==1)
        Dir=1;
        i=i-1;
        
elseif(ForbiddenDir~=2 & C(i,j-1)==1)
        Dir=2;
        j=j-1;
        
elseif(ForbiddenDir~=3 & C(i+1,j)==1)
        Dir=3;
        i=i+1;
        
end;
Count=Count+1
CONTOUR(Count+1,1)=i;
CONTOUR(Count+1,2)=j;
CONTOUR(Count+1,:)
CHAIN_CODE(Count)=Dir;
%ContCalc=input('Continue (y/n)? ','s');
%if(ContCalc=='n')
%    break;
%end
end

CONTOUR
CHAIN_CODE