%Given an array of objects, detects the gears.
%Returns an array of gear images and the number of teeth each has.

function [gears, teeth] = detectgears(objects)
    %Convert the image to BW and invert.
    bwobj = (im2bw(objects) == 0);
    
    %Perform closing and median filtering to eliminate gaps and get rid of
    %stray noise.
    bwobj = medfilt2(imclose(bwobj, strel('disk', 1)), [2 2]);
    
    %Split the objects by removing them, one by one, from the background,
    %until none remain (find returns an empty matrix).
    fgindex = find(bwobj, 1);
    
    gears = [];
    teeth = [];
    
    while (~isempty(fgindex))
        %Extract the object from the background.
        [y,x] = ind2sub(size(bwobj), fgindex);
        fgobj = bwselect(bwobj, x, y, 8);
        bwobj = bwobj - fgobj; %Remove it from the background image.
        
        %Check to see if this is the shape we want.
        [gear, gearteeth] = isGear(fgobj);
        if (gear)
            %Add it to the list.
            gears(:,:,(~isempty(gears) * size(gears, 3))+1) = fgobj;
            teeth(size(teeth, 1)+1) = gearteeth;
        end
        
        %Repeat.
        fgindex = find(bwobj,1);
    end    
end
