function watershed_example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%2_D
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
center1 = -10; %第一个圆的中心(-10, -10)
center2 =-center1;%第二个圆的中心(10, 10)
dist = sqrt(2*(2*center1)^2);%两圆心距离
radius = dist/2 * 1.4;%两圆心距离的0.7倍, 使得两个圆重叠
lims= [floor(center1-1.2*radius) ceil(center2+1.2*radius)];%[-3434]
[x,y] = meshgrid(lims(1):lims(2));%生成一个矩形网格, X: [-34, -34], Y: [-34, -34], x,y均为2维矩阵, 这两个矩阵可用于指定任何一个69X69矩阵的任何位置对应的直角坐标
bw1 = sqrt((x-center1).^2 + (y-center1).^2) <= radius;%产生第一个圆的二值图像
bw2 = sqrt((x-center2).^2 + (y-center2).^2) <= radius;%产生第二个圆的二值图像
bw = bw1 | bw2;%逻辑或, 两幅图像综合
figure,imshow(bw,'InitialMagnification','fit'), title('bw')
D = bwdist(~bw);
figure
imshow(D,[],'InitialMagnification','fit')
title('Distance transform of ~bw')
D = -D;
D(~bw) = Inf;
L = watershed(D);
L(~bw) = 0;
rgb = label2rgb(L,'jet',[.5 .5 .5]);
figure
imshow(rgb,'InitialMagnification','fit')
title('Watershed transform of D')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%3_D
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
center1 = -10;%第一个圆的中心(-10, -10)
center2 = -center1;%第二个圆的中心(10, 10)
dist = sqrt(3*(2*center1)^2);%两圆心距离
radius = dist/2 * 1.4;%两圆心距离的0.7倍, 使得两个圆重叠
lims = [floor(center1-1.2*radius) ceil(center2+1.2*radius)];
[x,y,z] = meshgrid(lims(1):lims(2));%生成一个矩形网格, X: [-34, -34], Y: [-34, -34], x,y均为2维矩阵, 这两个矩阵可用于指定任何一个69X69矩阵的任何位置对应的直角坐标
bw1 = sqrt((x-center1).^2 + (y-center1).^2 + ...
(z-center1).^2) <= radius;%产生第一个圆的二值图像
bw2 = sqrt((x-center2).^2 + (y-center2).^2 + ...
(z-center2).^2) <= radius;%产生第二个圆的二值图像
bw = bw1 | bw2;%逻辑或, 两幅图像综合
figure, isosurface(x,y,z,bw,0.5), axis equal, title('BW')
xlabel x, ylabel y, zlabel z
xlim(lims), ylim(lims), zlim(lims)
view(3), camlight, lighting gouraud
D = bwdist(~bw);
figure, isosurface(x,y,z,D,radius/2), axis equal
title('Isosurface of distance transform')
xlabel x, ylabel y, zlabel z
xlim(lims), ylim(lims), zlim(lims)
view(3), camlight, lighting gouraud
D = -D;
D(~bw) = Inf;
L = watershed(D);
L(~bw) = 0;
figure
isosurface(x,y,z,L==1,0.5)
isosurface(x,y,z,L==2,0.5)
axis equal
title('Segmented objects')
xlabel x, ylabel y, zlabel z
xlim(lims), ylim(lims), zlim(lims)
view(3), camlight, lighting gouraud