%Find the Gear in the given image and show the number of teeth.

image=imread('objects.jpg');

figure
%find the clear boundary of all the sub images
se = strel('disk',1);
cc = imopen(image,se);
cc=rgb2gray(image);
cc=cc>200;
L=bwlabel(cc);
l=L;
index2=find(L==1);
l(:)=1;
l(index2)=0;
subplot(2,1,1);
imshow(l)
dummy=ginput(1);

%put all the sub images into 'sub'
[ll num]=bwlabel(l);
n=1;
for j=1:num
s=ll;
index=find(ll==j);
ms=size(index);
if ms(1)>50
   s(:)=0;
   s(index)=1;
   sub{n}=s;
   n=n+1;
end;
end;

num=n-1; %the number of those images

result_num=0; % the number of the Gears

for target=1:num

BW=sub{target};

%Calculate the center point of the target image
i1=find(max(BW)==1);
i2=find(max(BW')==1);
center=[round((max(i2)-min(i2))/2+min(i2)) round((max(i1)-min(i1))/2+min(i1))];

s=size(BW);

%Calculate the boundary of the target image
boundary =[];
for row = 1:s(1)
   for col=1:s(2)
      if BW(row,col), 
          break;
      end
   end
   contour = bwtraceboundary(BW, [row, col], 'W', 8, Inf, 'counterclockwise');
                   
   if(~isempty(contour))
      boundary = [boundary'  contour']';  
   end
end
boundary(:,1)=center(1)-boundary(:,1);
boundary(:,2)=boundary(:,2)-center(2);

subplot(2,1,1);
imshow(BW)
hold on;
plot(center(2), center(1), 'rx','LineWidth',1)
subplot(2,2,3,'replace');
plot(boundary(:,2),boundary(:,1));

clear BB;
sz=size(boundary);
m=round(sz(1)/2000)+1;
i=1:m:sz(1);
BB=boundary(i,:);

n=80;
cd=CentroidDistance(BB,n); %the distance from the center to the boundary
standard=std(cd) %Standard deviation value of the distance
    
%FFT and show the frequency
fourier=abs(fft(cd,n));
cdf=fourier(2: floor(n/2)) ./ fourier(1);
subplot(2,2,4,'replace');
stairs(cdf);

number=find(cdf==max(cdf)) %the frequency with highest energy, and the number of teeth

%see whether the target image is gear or not
if standard<5 && standard>1 && number>10
    result_num=result_num+1;
    result(result_num,1)=target;
    result(result_num,2)=number;
end;

dummy=ginput(1);
grid on

end;

%Show the results
for i=1:result_num
    subplot(result_num,1,i);
    imshow(sub{result(i,1)})
    title(['Number of Teeth = ', int2str(result(i,2))]); 
end;
   
