% function B=find_boundaries(image_file, boundary_threshold);
% 
% image_file = name of image to process
% boundary_threshold = gray level boundary between black and white.
% lower=more edges, higher=fewer edges. default =  graythresh()
%
% code ripped off of http://www.instructables.com/id/Image-Processing-and-Counting-using-MATLAB/
function [B]=find_boundaries(image_file, boundary_threshold);

img1=imread(image_file);

figure
subplot(2,2,1);
imshow(img1);

%Step 2: Convert the Image to Grayscale
img1=rgb2gray(img1);
subplot(2,2,2);
imshow(img1);

%Step 2a: some extra tweaks to clean up noise and low-frequency fluctuations
img2=img1;
h=[1 1 1; 1 1 1; 1 1 1]./9;
img2=imfilter(img2,h);
h=fspecial('unsharp');
img2=imfilter(img2,h);
subplot(2,2,3);
imshow(img2);


%Step 3: Threshold the image
if ~exist('boundary_threshold','var'),
    boundary_threshold=graythresh(img2)
end

img3=im2bw(img2,boundary_threshold);

% invert
img3=~img3;

subplot(2,2,4);
imshow(img3)



% Step 4: Find the Boundaries of the Objects
B = bwboundaries(img3);
imshow(img3)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(B))))

% Step 5: Draw the Boundaries
hold on
for k = 1:length(B)
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 1)
end


return

