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

clear all;
x=imread('Contour.tif');
C=bwperim(x,8);
subplot(2,1,1),imagesc(C)
title('Input Contour');
grid on;



CONTOUR(1,:)=input('Coordinates of the first point (try: [27 57]) or [27,59])');
CONTOUR(2,:)=input('Coordinates of the second point (try: [27 58])');
Dir=input('Direction between the first two points: ');

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

i=CONTOUR(2,1);
j=CONTOUR(2,2);
Stuck=0;
while((i~=istart | j~=jstart) & Stuck==0)
    
ForbiddenDir=mod(Dir+2,4);
NewPointFoud=0;
if(ForbiddenDir~=0 & C(i,j+1)==1)
        Dir=0;
        j=j+1;
        NewPointFoud=1;
elseif(ForbiddenDir~=1 & C(i-1,j)==1)
        Dir=1;
        i=i-1;
        NewPointFoud=1;
elseif(ForbiddenDir~=2 & C(i,j-1)==1)
        Dir=2;
        j=j-1;
        NewPointFoud=1;
elseif(ForbiddenDir~=3 & C(i+1,j)==1)
        Dir=3;
        i=i+1;
        NewPointFoud=1;
end;
Count=Count+1
CONTOUR(Count+1,1)=i;
CONTOUR(Count+1,2)=j;
DIR(Count)=Dir;

if(NewPointFoud==0)
    Stuck=1;
    Stuck_in_the_point=[i,j]
end
end



%Plot the calculated contour points
[M,N]=size(x);
A=zeros(M,N);
for i=1:(Count+1)
    A(CONTOUR(i,1),CONTOUR(i,2))=1;
end
subplot(2,1,2)
imagesc(A);
title('Stored contour points');



