%% Watershed
clear
close all

% First load in the image
img = imread('circles.png');

figure
imshow(img)

% What happens if we watershed
Ltest = watershed(img);

figure
imshow(Ltest,[])

% We want to mark basins at the center of each circle.  Then as they fill
% up, they will mark each one.  We can use the bwdist command.  Each pixel
% gets a number which is how many pixels it is away from an object.
imgD = bwdist(img);

figure
imshow([img mat2gray(imgD)])

% That's not quite right.  We want to mark the circles.  To do that we'll
% take the complement and bwdist that.

imgD2 = bwdist(imcomplement(img));
figure
imshow([img imcomplement(img) mat2gray(imgD2)])

% This looks much better.  But these are pyramids - we want basins.  Lets
% take the complement of that image
imgD3 = imcomplement(imgD2);

figure
imshow([img mat2gray(imgD3)])

% If we try to take the watershed of this image, something sin't right.
L = watershed(imgD3);
figure
imshow(L,[])

% So now we want to set the background pixels equal to zero.  If we
% multiply by the original image, all of the background was equal to zero.
imgD4 = mat2gray(imgD3).*img;
L2 = watershed(imgD4);
Lrgb = label2rgb(L2, 'jet', 'w', 'shuffle');

figure
imshow(img)
hold on
Limg = imshow(Lrgb);
Limg.AlphaData = 0.3;


