%READ THE IMAGE AND TRANSFORM IT TO BW IMAGE
A=imread('objects.jpg');
A=im2bw(A);
A=not(A);

%MORFOLOGICAL FUNCTIONS FOR GETTING RID OF NOISE
%CLOSING WILL GET RID OF SMALL OBJECTS AND KEEP BIG OBJECTS
%WE WILL DO IT 10 TIMES, EVEN THOUGH 2-3 IS ENOUGH AND AFTER THAT NOTHING
%WILL CHANGE ANYMORE
j=10;
se = strel('disk',1);
for i=1:j
    B{i}=imdilate(A,se);
    C{i}=imerode(B{i},se);
end

subplot(6,3,1:3);
imshow(C{j});

%LABELING THE DISTINCT OBJECTS WITH DIFFERENT PIXEL VALUES

[Labeled,number] = bwlabel(C{j},4); %number will contain the number of obj
FINALIMAGE=C{j};

j=0;

%FOR EACH OBJECT MAKE ITS OWN IMAGE

for i=1:number
    
    [Row,Col]=find(Labeled(:,:)==i);
    if (size(Row,1)<200) continue;
    end
    j=j+1;
    OBJECT{j}=Labeled(min(Row):max(Row),min(Col):max(Col));
    X=find((OBJECT{j}(:,:)~=0)&(OBJECT{j}(:,:)~=i));
    OBJECT{j}(X)=0;
    subplot(6,3,j+3);
    imshow(OBJECT{j});
    
    center(j,1)=round((max(Row)-min(Row))/2);
    center(j,2)=round((max(Col)-min(Col))/2);
    
end

%FOR EACH OBJECT

for i=1:j
    
    %TRACE THE BOUNDARY STARTING FROM MOST TOP LEFT POINT
    [x y]=find(OBJECT{i}(1,:)~=0);
    boundary=bwtraceboundary(OBJECT{i},[1 y(size(y,2))],'W');
    
    %CENTER OF THE OBJECT WILL BE THE CENTER OF THE BOX
    CENT(:,1)=center(i,1);
    CENT(:,2)=center(i,2);
    
    %CALCULATING THE DISTANCE OF EACH PIXEL FROM CENTER
    DistFromCenter{i}=dist(CENT,boundary');
   
    DistFromCenter{i}=DistFromCenter{i}-mean(DistFromCenter{i});
    
    FT{i}=abs(fft(DistFromCenter{i}));
    
    [a b]=max(FT{i});
    NumberOfTeeth(i)=b-1;
    
    %IF THE NUMBER OF TEETH IS MORE THAN 10 ONLY THAN THE OBJECT IS THE WEEL
    
    if (NumberOfTeeth(i)>6)
     
        figure
        subplot(2,2,1)
        imshow(OBJECT{i});
        title('This is a WEEL');
        subplot(2,2,2)
        plot(DistFromCenter{i}); %plot the distance
        subplot(2,2,3)   
        plot(FT{i}(1:50)); %plot the FFT
        str = num2str(NumberOfTeeth(i));
        t = strcat('The number of teeth is: ',str);
        title(t);
        pause(4);
    
    end
    
end