% CIS 601 Computer Graphics and Image Processing
% Homework 5                    Spring 2007
% Riu Baring
% ==============================================
% Main function
% ==============================================

% 
%clear all

sampleNo = 64;

% Load image file
imgOriginal = imread('hw5.jpg');

% Step 1: Image Binarization
imgBinarized = im2bw(imgOriginal);

% Step 2: Swap color between the objects and background
[row col] = size(imgBinarized);
imgTemp = ones(row, col);
imgTemp(imgBinarized) = 0;
imgBinarized = im2bw(imgTemp);

% Step 3: De-noising
imgBinarized = bwmorph(imgBinarized, 'open'); %Peforms morphological opening (erosion followed by dilation)
%imgBinarized = bwmorph(imgBinarized, 'open');
%imgBinarized = bwmorph(imgBinarized, 'close');

% Step 4: Trace boundaries of objects
imgFilled = imfill(imgBinarized, 'holes');
imgLabel = bwlabel(imgFilled);
boundaries = bwboundaries(imgLabel);

subplot(2, 2, [1 2]);
imshow(imgOriginal);
title('Collection of Objects');
hold on;

fd = cell(length(boundaries), 1);
for i = 1:length(boundaries)
    b = boundaries{i};
    fd{i} = centroidDistanceFourier(b, sampleNo);
    plot(b(:, 2), b(:, 1), 'r', 'LineWidth', 2);
end

[gearNum gearInd] = FindTheGear(fd);

for i = 1:length(gearNum)
    subplot(2, 2, 3);
    gear = boundaries{gearInd(i)};
    plot(gear(:, 2), gear(:, 1));
    title(sprintf('Number of Teeth: %d', gearNum(i)));
    
    subplot(2, 2, 4);
    centroidDistanceFourier(boundaries{gearInd(i)}, sampleNo, 1);
    
    dummy = ginput(1);
end
