%%%%----------------------------------------------------------------%%%%%
%%%% CIS 601 HW 2 Gear and Teeth Detection                          %%%%%
%%%% Xin Li                                                         %%%%%
%%%% Feb 12, 2008                                                   %%%%%
%%%%----------------------------------------------------------------%%%%%

%%% Read me: please download 
function GearBoundary
close all;
clc;
clear;

% read the image
orig = imread('objects.jpg');
I = im2bw(orig);
imshow(I);
title('original objects');

II = 1 - double(I);
III = imfill(II,'holes');
imshow(III);
title('reverse 0 and 1; fill in holes');

% IV = 1 - III;
% figure; imshow(IV);


% trace boundary and extract the boundary coordinate
IV = imdilate(III,strel('line',2,0));
V = imerode(IV,strel('disk',1));
imshow(V);
title('After dilate and erode');
[L, num] =  bwlabel(V,8);

% figure;
% imshow(L);


RGB=label2rgb(L);
figure, imshow(RGB);
Title('RGB Image');
s = size(L);
col = s(2);
row = s(1);

for i = 3:num
    object = zeros(row,col);
    object(find(L == i)) = 1;

    [teeth] = findObject(object,i-2);
    if teeth >= 10 
        sprintf('This is gear, its teeth number: %d',teeth)
    end
    saveas(gcf, ['Object ',num2str(i),'.fig']);
    pause;
    close;
end





%%%%------------------------find object-----------------------------------
function [teeth] = findObject(object,number)


s = size(object);
col = s(2);
row = s(1);
object2 = circshift(object,[0, 5]);
% imtool(object2);
index = [];
for j = 1:row
    index = find(object2(j,:) == 1);
    if ~isempty(index)
        col_temp = index(1);
        break
    end
end
row_temp = j;
% row_temp = min(find(object2(:,col_temp)));
contour = bwtraceboundary(object2, [row_temp, col_temp], 'S');
figure;
subplot(2,2,1);
% imshow(object2);
% hold on;
plot(contour(:,1),-contour(:,2),'g','lineWidth',2);
axis equal;
title(['object',num2str(number)]);
subplot(2,2,3);
CentroidDistance(contour,1000,1);
title('CentroidDistance');
subplot(2,2,4);
cdf = CentroidDistanceFourier(contour,200,1);
title('CentroidDistanceFourier');
teeth = find(cdf == max(cdf(5:end)));
if teeth > 10
    text(teeth,cdf(teeth),[' \leftarrow Gears Teeth ', num2str(teeth)],'FontSize',10);
end
return;








