clear all, clc;

img = imread('q.jpg');
img = im2bw(img, graythresh(img));
imgDist = -bwdist(~img,'chessboard');
figure, imshow(imgDist, [])
% imgDist(~img)=-inf; 
% figure, imshow(imgDist, [])

%% check local minimums
Dis_img = imregionalmin(imgDist);
figure, imshow(~Dis_img);  
bw = img;
dis = Dis_img .* bw;
[p, q] = find(dis == 1);
figure, imshow(bw), hold on
plot(q, p, 'r+'), hold off;

bw0 = img;
bw0(find(dis == 1)) = 0;
figure, imshow(bw0);

%% watershed
imgLabel = watershed(imgDist);    
bgm = imgLabel == 0;
figure, imshow(bgm,'InitialMagnification','fit')
img(bgm) = 0;
img = bwareaopen(img,5);
figure, imshow(img);

colorimg = bwlabel(img);
figure,imshow(label2rgb(colorimg,'jet','k','shuffle'));

