Matlab watershed函数学习(2)
% 2. Compute the distance transform of thecomplement of the binary
% image.
%
% D = bwdist(~bw);
% figure,imshow(D,[],'InitialMagnification','fit')
% title('Distance transform of ~bw')
2. 计算上述二值图像的补的距离变换
% 3. Complement the distance transform, andforce pixels that don't
% belong to the objects to be at -Inf.
%
% D = -D;
% D(~bw) = -Inf;
3. 计算距离变换的补, 并令不属于两个对象的像素为负无穷.
% 4. Compute the watershed transform, anddisplay the resulting label
% matrix as an RGB image.
%
% L = watershed(D);
% rgb = label2rgb(L,'jet',[.5 .5 .5]);
% figure,imshow(rgb,'InitialMagnification','fit')
% title('Watershed transform of D')
4. 计算分水岭变换, 并将标签矩阵显示为RGB图像
如果直接对bw做分水岭变换, 结果如下:
观察watershed函数的代码:
cc =bwconncomp(imregionalmin(A, conn), conn);
L =watershed_meyer(A,conn,cc);
imregionalmin是计算极小值区域, 所谓极小值区域指的是具有相同像素值t的连通区域, 且区域外边界的像素值均大于t.imregionalmin的结果是二值图像, 属于极小值区域的像素值为1, 其它像素值为0.
bwconncomp是寻找二值图像中的连通区域, 并加以区分(标识).
因此, 如果直接对bw计算分水岭变换, 初始的最小值区域只有1个(即连通的黑色背景部分), 随着水位的增长必将形成1个区域.
以下贴出有更多对比的代码及结果图(注意距离变换的极小值区域两个圆心位置的亮点).
center1 = -10;
center2 = -center1;
dist =sqrt(2*(2*center1)^2);
radius = dist/2 *1.4;
lims =[floor(center1-1.2*radius) ceil(center2+1.2*radius)];
[x,y] =meshgrid(lims(1):lims(2));
bw1 =sqrt((x-center1).^2 + (y-center1).^2) <= radius;
bw2 =sqrt((x-center2).^2 + (y-center2).^2) <= radius;
bw = bw1 | bw2;
figure;
subplot(4, 2, 1);
imshow(bw,'InitialMagnification','fit');
title('原始图像');
D = bwdist(~bw);
subplot(4, 2, 2);
imshow(D,[],'InitialMagnification','fit');
title('原始图像的反的距离变换');
D =-D; %将会使得两圆圆心像素分别成为极小值区域
D(~bw)= -Inf;%使得背景称为极小值区域
subplot(4, 2, 3);
imshow(D,[],'InitialMagnification','fit');
title('处理后的距离变换');
temp_cc =bwconncomp(imregionalmin(bw));
temp_bw = zeros(69,69);
temp_bw =int32(temp_bw);
for obj_no =1:temp_cc.NumObjects;
temp_bw(temp_cc.PixelIdxList{obj_no}) =obj_no;%为原始二值图像的每个极小值区域赋予相应标签
end
rgb =label2rgb(temp_bw, 'jet', [.5 .5 .5]);
subplot(4, 2, 4);
imshow(rgb,'InitialMagnification','fit');
title('原始图像的所有极小值区域');
temp_cc =bwconncomp(imregionalmin(D));
temp_D = zeros(69,69);
temp_D =int32(temp_D);
for obj_no =1:temp_cc.NumObjects;
temp_D(temp_cc.PixelIdxList{obj_no}) =obj_no;%为处理后的距离变换的每个极小值区域赋予相应标签
end
rgb =label2rgb(temp_D, 'jet', [.5 .5 .5]);
subplot(4, 2, 5);
imshow(rgb,'InitialMagnification','fit');
title('处理后的距离变换的所有极小值区域');
L = watershed(bw);
rgb =label2rgb(L,'jet',[.5 .5 .5]);
subplot(4, 2, 6);
imshow(rgb,'InitialMagnification','fit')
title('原始图像的分水岭变换');
L = watershed(D);
rgb =label2rgb(L,'jet',[.5 .5 .5]);
subplot(4, 2, 7);
imshow(rgb,'InitialMagnification','fit')
title('处理后的距离变换的的分水岭变换')