%% We can also use morphological operators to trace the edges
clear 
close all

% First we can load in the image as per usual, and convert it to a logical
% image
img = im2double(rgb2gray(imread('Picture2.png')));
imgBW = im2bw(img,graythresh(img));

figure
imshow([img imgBW])

% You can see the paper clips and some of the coins have holes in them.  We
% can use the imfill command to correct for that.

imgBW2 = imfill(imgBW,'holes');
figure
imshow(imgBW2)
% To find the boundary, we can dilate the image, and then subtract the
% original.
imgDil = imdilate(imgBW2,strel('disk',3));
imgBound = imgDil - imgBW2;

figure
imshow([imgBW2 imgDil imgBound])

% We can also do this by eroding and subtracting that from the original.
imgEr = imerode(imgBW2,strel('disk',3));
imgBound2 = imgBW2 - imgEr;

figure
imshow([imgBW2 imgEr imgBound2])

% We can compare the two
figure
imshow([imgBound imgBound2])


%% BWMORPH
% bwmorph is a very useful command.  it only takes in a BW image (no
% grayscale), but it allows you to perform a vairety of different
% operations on an image.
clear
close all

img = im2double(rgb2gray(imread('Picture2.png')));
imgBW = im2bw(img,graythresh(img));
img2 = imfill(imgBW,'holes');

% Remove takes away the internal components so you only have the outlines
imgRemove = bwmorph(img2,'remove');

figure
imshow([img2 imgRemove])

% Skeleton takes a 2D object and reduces it to a line.  It does this by
% thinning the objects repeadetly.  You need a 3rd argument, which is the
% number of times to run the skeletonization algorithm

imgSkel1 = bwmorph(img2,'skel',1);
imgSkel2 = bwmorph(img2,'skel',10);
imgSkel3 = bwmorph(img2,'skel',50);

figure
imshow([img2 imgSkel1; imgSkel2 imgSkel3])

% Endpoints is often used in conjunction with the skeleton images.  Does
% exactly what it says.

imgEnd = bwmorph(imgSkel3,'EndPoints');
imgEnd2 = imdilate(imgEnd,strel('disk',3));

figure
imshow([img2 imgSkel3 imgEnd2])

figure
imshowpair(img2,imgEnd2)


% Branchpoints are similar to endpoints, but they highlight where there is
% a branch in the skeleton image.

imgBranch = bwmorph(imgSkel3,'BranchPoints');
imgBranch2 = imdilate(imgBranch,strel('disk',4));

figure
imshow([img2 imgSkel3 imgBranch2])

figure
imshowpair(img2,imgBranch2)

%Thinning and thickening are exactly like the sound.
imgThin1 = bwmorph(img2,'Thin', 1);
imgThin2 = bwmorph(img2,'Thin', 10);
imgThin3 = bwmorph(img2,'Thin', Inf);

figure
imshow([img2 imgThin1; imgThin2 imgThin3])

%Thickening
imgThick1 = bwmorph(img2,'Thick', 1);
imgThick2 = bwmorph(img2,'Thick', 10);
imgThick3 = bwmorph(img2,'Thick', Inf);

figure
imshow([img2 imgThick1; imgThick2 imgThick3])


