您可以使用 bwboundaries 查找白色连通分量的像素边界,这样每个连通分量都有一组对应的边界。
%calculate boundries and generate boundry mask
B = bwboundaries(im,'noholes');
boundriesImage = zeros(size(im));
boundriesPixels = cell2mat(B);
boundriesImage(sub2ind(size(im),boundriesPixels(:,1),boundriesPixels(:,2)))=1;
%finds the connected component in the original image and in the boundry
%mask
CC = bwconncomp(im);
CC2 = bwconncomp(boundriesImage);
结果:CC 和 CC2 包含相同数量的连通分量
CC =
Connectivity: 8
ImageSize: [535 1571]
NumObjects: 814
PixelIdxList: {1x814 cell}
CC2 =
Connectivity: 8
ImageSize: [535 1571]
NumObjects: 814
PixelIdxList: {1x814 cell}
此外,每个连接的组件 CC2{ii} 与它的 CC{ii} 匹配,如以下测试结果所示:
%tests that for each ii, CC{ii} is contained in CC{i}
CC2MatchesToCC1 = true;
for ii=1:length(CC.PixelIdxList)
if length(intersect(CC2.PixelIdxList{ii},CC.PixelIdxList{ii}))~=length(CC2.PixelIdxList{ii})
CC2MatchesToCC1 = false;
end
end
结果:
CC2MatchesToCC1 =
1