假设你的图片是BW下面:
% detecting all connected regions:
B = bwboundaries(BW,4);
这将生成一个单元格数组 B,其中包含所有“补丁”,这些“补丁”是通过将具有值 1 的相邻单元格连接起来的,这些单元格从 4 条边之一连接,即不在对角线上。
B =
[11x2 double]
[ 2x2 double]
[ 3x2 double]
[ 3x2 double]
[ 2x2 double]
[ 3x2 double]
[ 2x2 double]
[ 2x2 double]
[ 3x2 double]
[ 3x2 double]
[ 2x2 double]
[11x2 double]
例如:
>> B{6}
ans =
3 7
3 8
3 7
每一行是一个单元格坐标。第一列是它的行,第二列是它的列,第一个和最后一个单元格总是相同的。
现在我们需要遍历B 中的单元格,找出其中哪些是水平线或垂直线,并将它们保存到新的矩阵中。
% matrices for horizontal and vertical lines:
BWh = zeros(size(BW)); % horizontal lines
BWv = zeros(size(BW)); % vertical lines
for k = 1:numel(B)
% if the coordinates changes ONLY vertically:
% a vertical line is where all the coulmn indecies are the same
% and there are different row indices
if all(B{k}(1,2)==B{k}(:,2)) && B{k}(1,1)~=B{k}(2,1)
BWv(sub2ind(size(BW),B{k}(:,1),B{k}(:,2))) = 1;
end
% if the coordinates changes ONLY horizontaly:
% a vertical line is where all the row indecies are the same
% and there are different column indices
if all(B{k}(1,1)==B{k}(:,1)) && B{k}(1,2)~=B{k}(2,2)
BWh(sub2ind(size(BW),B{k}(:,1),B{k}(:,2))) = 1;
end
end
subplot 131
imagesc(BWh)
title('Horizontal lines')
subplot 132
imagesc(BWv)
title('Vertical lines')
“对角边”是我们排除线条后留下的,所以我们可以寻找到目前为止我们没有找到的东西:
subplot 133
imagesc(BW & ~BWv & ~BWh)
title('Diagonal edges')
colormap 'gray'
此方法将忽略任何不是单格粗线的内容,例如,下图中中间的正方形将仅以 对角线 模式显示: