
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Image Processing Toolbox
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% coin count
warning off
I = imread('coins.png'); % read an image
imshow(I)                % show the image
BW = im2bw(I);           % convert the image in B/W
figure, imshow(BW)               % show the B/W image
dim = size(BW)           % size of the image in pixels
col = round(dim(2)/2)-90;  % determine the starting location
row = min(find(BW(:,col))) % for the boundary tracing

% traces the outline of an object in a 
% binary image BW, in which nonzero pixels belong to an object and 
% 0-pixels constitute the background.
boundary = bwtraceboundary(BW,[row, col],'N');
imshow(I)
hold on;
plot(boundary(:,2),boundary(:,1),'g','LineWidth',3);

% bwboundaries: by default finds the boundaries of all objects in an image
% including objects inside other objects. 
% In the binary image used in this example, some of the coins contain 
% black areas that bwboundaries interprets as separate objects. 
% To ensure that bwboundaries only traces the coins, 
% use imfill to fill the area inside each coin. 

BW_filled = imfill(BW,'holes');
% fills holes in the input image.  A hole is
% a set of background pixels that cannot be reached by filling in the
% background from the edge of the image.
    
boundaries = bwboundaries(BW_filled);
fprintf('Number of coins: %d \n', size(boundaries,1));

% plot all the contours around the coins
for k=1:10
   b = boundaries{k};
   plot(b(:,2),b(:,1),'g','LineWidth',3);
end
warning on