clf
clear
close all
% get directory listing
listing = dir('shp1*.jpg');
 
% get number of files matching the query
nFiles = numel(listing);
 
% % print all the file names using a loop
% for n=1:nFiles
%     fprintf([listing(n).name '\n']);
% end


% loop over all image files
for n=1:nFiles
    % get image name
    imName = listing(n).name;
%  
%     % read and check image, get size
%     rgbImg = imread(imName);
%     [nRows nCols nLyrs] = size(rgbImg);
%     nPix = nRows * nCols;
%  
%     % most of the lab code after this line
% end

%read image
% clf
% clear
% close all
% I = imread('shp_rectangle.jpg');
I=imread(imName);
%filter
v=4;
h = ones(v,v) / (v*v);
I = imfilter(I,h);

%Turn image to black and white
level = graythresh(I);
%imshow(I);
bw = im2bw(I,level);
%figure, imshow(bw);
%bw = imfill(bw,'holes');
bw = 1 - bw;
%figure, imshow(bw);
bw = bwareaopen(bw, 400);
%figure, imshow(bw);
cc = bwconncomp(bw, 4);

%Remove Background
background = imopen(I,strel('disk',100));
I = I-background;

%change contrast
level = 4/256;
bw = im2bw(I,level);


%Region Props
graindata = regionprops(cc, 'all');
grain_areas = [graindata.Area];
[max_area, idx] = max(grain_areas);
graindata(idx)


%first test for ellispe or rectangle
graindata(idx).Eccentricity
if (graindata(idx).Eccentricity > .8) 
    
     % rotate shape and print
        newIm = imrotate(bw, -1 * graindata(idx).Orientation);
        %imshow(newIm);
    
    % recompute regionprops and call it graindata2
        graindata2 = regionprops(cc, 'all');
        grain_areas2 = [graindata2.Area];
        [max_area2, idx] = max(grain_areas2);
        graindata2(idx);
    
    % get ratio of new bounding box to area
        bbarea = (graindata2(idx).BoundingBox(3) * graindata2(idx).BoundingBox(4));
        if (graindata2(idx).Area/bbarea > 0.79)
        %rectangle
            myshape = 1;
            disp('Rectangle!');
%             I1=imName(:,:,1); I1(L0)=0; % red
%             I2=imName(:,:,2); I2(L0)=0; % green
%             I3=imName(:,:,3); I3(L0)=0; % blue
%             II=cat(3, I1, I2, I3); % rgb
%             figure; imshow(II);
            figure; imshow(imName);
            title('RECTANGLE!');
        else
        % ellipse
            myshape = 2;
            disp('Ellipse!');
            figure; imshow(imName);
            title('ELLIPSE!');
        end
else 
    % circle or square:
    R=(graindata(idx).BoundingBox(3)/2);
%     y=graindata(idx).BoundingBox(4);
%     H=graindata(idx).ConvexHull;
%     [C,R] = incircle([x,y],H)
    %[C,R] = incircle(x,y);
    % get ratio of area to incircle
     if ((graindata(idx).Area/(pi*R^2))<1.05);
        % circle
        myshape = 3;
        disp('Circle!');
        figure; imshow(imName);
        title('CIRCLE!');
        else
        % square
        myshape = 4;
        disp('Square!');
        figure; imshow(imName);
        title('SQUARE!');
        end
end

end