另一种可能性是使用BW边界 http://www.mathworks.com/help/toolbox/images/ref/bwboundaries.html函数,其中:
追踪物体的外部边界,以及物体的边界
这些物体内部有洞
该信息包含在第四个输出中A
,表示父子孔依赖关系的邻接矩阵。
%# read binary image
bw = imread('SUvif.png');
%# find all boundaries
[B,L,N,A] = bwboundaries(bw, 8, 'holes');
%# exclude inner holes
[r,~] = find(A(:,N+1:end)); %# find inner boundaries that enclose stuff
[rr,~] = find(A(:,r)); %# stuff they enclose
idx = setdiff(1:numel(B), [r(:);rr(:)]); %# exclude both
bw2 = ismember(L,idx); %# filled image
%# compare results
subplot(311), imshow(bw), title('original')
subplot(312), imshow( imfill(bw,'holes') ), title('imfill')
subplot(313), imshow(bw2), title('bwboundaries')