% Erickson Miranda
% HW 5

close all;
img = imread('objects.jpg');
bwImg = im2bw(img);
imgRev = xor(bwImg,1);
L = bwlabel(imgRev,8);
figure;
subplot(3,1,1), imshow(bwImg), title 'Original image';
subplot(3,1,2), imshow(imgRev), title 'Image in reverse';
subplot(3,1,3), imshow(label2rgb(L)), title 'Objects found in different colors';
nobjs = max(L(:));

% find boundaries of objects 
nobjsFilt = 0;
for i=1:nobjs
    [r,c] = find(L==i);
    rc = [r c];
    % filter out small objects
    if max(r)-min(r) > 6 & max(c)-min(c) > 6
        nobjsFilt = nobjsFilt+1;
        imgObj(nobjsFilt,:) = [min(c) max(c) min(r) max(r)];
        imgObjSeed(nobjsFilt,:) = rc(1,:);
    else
        L(rc) = 0;
    end
end

%identify potential objects
figure;
for i=1:nobjsFilt
    obj = bwtraceboundary(L,imgObjSeed(i,:),'SE');
    cdf = centroidDistanceFourier(obj,64);
    % check general shape (circle, ellipse or otherwise)
    [m,gen_shape] = max(cdf(1:5));
    if gen_shape == 1
        % potential while, has circular shape
        % check for spokes of gears
        [m2,gears] = max(cdf(10:length(cdf)));
        gears = gears+9; % offset
        if m2 > (1/64)
            % with gears
            subplot(5,3,i),plot(obj(:,2),obj(:,1),'g','LineWidth',1),axis equal;
            title(strcat('Gears=',num2str(gears)));
        else
            subplot(5,3,i),plot(obj(:,2),obj(:,1),'b','LineWidth',1),axis equal; 
            title('Round object but not wheel');
        end
    else
        subplot(5,3,i),plot(obj(:,2),obj(:,1),'r','LineWidth',1),axis equal;
        title('Non-round object');
    end
end

    

    