clear all;
clc;
for n=0:24
%% Read in image
    tmpl='soccer%d.jpg';
    fileName = sprintf(tmpl, n)
    im=imread(fileName); %put image name here
    im = imfilter(im, fspecial('gaussian'));
    
    %% Create BW images with only green pixels
    sz=size(im);
    for i=1:sz(1)
        for j=1:sz(2)
            r = im(i,j,1);
            g = im(i,j,2);
            b = im(i,j,3);
            if r>=g 
                green(i,j)=0;
            elseif b>=g
                green(i,j)=0;
            elseif g>=r+5 & g>=b+5
                green(i,j)=1;
            else
                green(i,j)=0;
           end
        end
    end
    
    %% Perform morphs to get cleaner, fuller objects
    green1 = imclearborder(green);
    green2 = bwmorph(green1, 'close');
    green3 = bwareaopen(green2, 6000);
    green4 = imfill(green3, 'holes');
    %imshow(green4)
    
    %% Find bounding boxes/centroids of green objects
    [B,L] = bwboundaries(green4, 'noholes');
    STATS = regionprops(L, 'all');
    %imshow(label2rgb(L))

    %% Find fields and plot on original image
    figure,
    imshow(im),
    title('Results');
    hold on
    for i = 1 : length(STATS)
      centroid = STATS(i).Centroid;
      if (STATS(i).MinorAxisLength/STATS(i).MajorAxisLength > .4) && (STATS(i).MinorAxisLength/STATS(i).MajorAxisLength < .9) && (STATS(i).MinorAxisLength * STATS(i).MajorAxisLength / 4 * 3.14159 * 0.86 < STATS(i).FilledArea)
          %plot(centroid(1), centroid(2), 'r+');
          text(centroid(1), centroid(2), sprintf('Ratio = %0.3f, \nAreaPercent = %0.3f', STATS(i).MinorAxisLength/STATS(i).MajorAxisLength, (STATS(i).FilledArea)/(STATS(i).MinorAxisLength * STATS(i).MajorAxisLength / 4 * 3.14159)),'BackgroundColor',[.7 .9 .7]);
	else
		text(centroid(1), centroid(2), sprintf('Ratio = %0.3f, \nAreaPercent = %0.3f', STATS(i).MinorAxisLength/STATS(i).MajorAxisLength, (STATS(i).FilledArea)/(STATS(i).MinorAxisLength * STATS(i).MajorAxisLength / 4 * 3.14159)),'BackgroundColor',[.9 .7 .7]);
      end
      
    end
    NumObjects = length(STATS)
    clearvars tmpl fileName im green green1 green2 green3 green4 B L STATS NumObjects;
end