Matlab 自带 bwboundaries 函数,能够解析图形,返回图片上所有图形的轮廓
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function outline = mask_to_outline(mask) arguments (Input) mask (:,:) double end arguments (Output) outline (:,:) logical end B = bwboundaries(mask==1, 'holes');
numBoundaries = length(B); totalPoints = 0; for k = 1:numBoundaries totalPoints = totalPoints + size(B{k}, 1); end allBoundaries = zeros(totalPoints, 2);
currentIndex = 1; for k = 1:numBoundaries boundary = B{k}; boundarySize = size(boundary, 1); allBoundaries(currentIndex:currentIndex+boundarySize-1, :) = boundary; currentIndex = currentIndex + boundarySize; end outline = zeros(size(mask)); linearIndices = sub2ind(size(outline),allBoundaries(:, 1), allBoundaries(:, 2)); outline(linearIndices) = 1; end
|
ℹ 这里展示的代码会把所有孔洞的轮廓都返回,如果只想要求闭合轮廓则是 bwboundaries(I, 'noholes');
结果展示
原来的 mask 图
得到的outline图
Ref