% hw2 Vuk Malbasa

close all
clear all

A = imread('objects.jpg');
A = im2bw(A);

% process object to clear things up a bit
i = 1;
B=imdilate(A,strel('disk',i));
B=imerode(A,strel('disk',i));

%partition
[labeled count] = bwlabel(not(B),4);
labeledpic = labeled/(max(labeled(:)));

for i = 1:count %for every element
    %remove everything except the segment
    currentwhole = labeled;
    currentwhole(currentwhole~=i)=0;
    currentwhole (currentwhole >0) = 1;

    %get image boundries
    starty = find(sum(currentwhole,1)>0,1,'first');
    endy = find(sum(currentwhole,1)>0,1,'last');
    startx = find(sum(currentwhole,2)>0,1,'first');
    endx = find(sum(currentwhole,2)>0,1,'last');

    %crop to current segment
    current = currentwhole(startx:endx,starty:endy);
    
    %check size in pixels to remove noise
    if sum(sum(current)) < 200 %if less than 200 pix disregard
        continue
    end
    
    %draw current object in context
    subplot(3,2,1);
    imshow(currentwhole);
    title('current partition');

    %draw object separated
    subplot(3,2,2);
    imshow(current);
    title('crop of extracted pixels');

    %find the starting point for trace boundary, start with leftmost
    %topmost pixel and move to the left
    startbound = find(current(1,:)~=0,1,'last');
    bound = bwtraceboundary(current,[1 startbound],'S'); %W

    %plot boundary
    subplot(3,2,3);
    plot(bound(:,2),bound(:,1))
    title('extracted boundary');
    
    %get center by finding mean of pixels
    [t1 t2] = find(current);
    t3 = [t1 t2];
    center = round(mean(t3));
    
    %add red x to center of current figure
    subplot(3,2,2);
    hold on
    scatter(center(2),center(1),1000,'rx');
    xlabel(['center at ' num2str(center)]);
    hold off
    
    %get distances from center
    distances = dist(center,bound');
    %sorry this just works better
    distances = distances-mean(distances);
    
    %draw distances
    subplot(3,2,4);
    plot(distances);
    title('time series');

    %get fft coefficients
    freq = abs(fft(distances));
    freq = freq(1:50);
    [v i] = max(freq);
    
    %draw fft coefficients
    subplot(3,2,5);
    plot(freq);
    title('frequency analysis');

    %if highest harmonic (except the 0-th one) is higher than 10 then its a
    %gear otherwise its not
    
    text = ['highest harmonic ' num2str(i-1)];
    if i-1<10
        text = [text ', probably not a gear'];
    else
        text = [text ', probably a gear'];
    end
    xlabel(text);
    
    %draw all objects separated
    subplot(3,2,6);
    colormap('Jet');
    imagesc(labeledpic);
    title('Object segmentation');
    pause;
end
close all
    