仅水平垂直线

horizontal-vertical only lines

我是 matlab 新手。我有一个图像块,如下图所示:

白色显示其值等于 1 的像素,黑色显示其值等于 0

的像素

我想得到vertical only lines。这意味着应该删除水平线,如下图所示:

我也想得到horizontal only lines。这意味着应删除垂直线,如下图所示:

如何在 Matlab 中完成?我更喜欢形态学操作。

假设您的图像是 BW 下面:

% detecting all connected regions:
B = bwboundaries(BW,4);

这将生成一个元胞数组 B,其中包含所有 "patches",这些元胞是通过连接具有值 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')

"Diagonal edges" 是我们排除行后剩下的,所以我们可以只查找目前没有找到的内容:

subplot 133
imagesc(BW & ~BWv & ~BWh)
title('Diagonal edges')
colormap 'gray'

此方法将忽略任何非 one-cell 粗线的内容,例如,下图中中间的正方形将仅显示在 对角线边缘 模式:

这个问题很有趣,因为有很多方法可以做到这一点。 本质上,您需要取出特定维度的连续像素。 我看到解决这个问题的一种方法是与 [1 1][1 1]' 向量进行卷积,然后取出所有获得值 2.

的元素
bw(conv2(bw,[1 1],'same')==2)=0;

这仍然会留下单个像素,您可以使用

轻松取出这些像素
bw = bwareaopen(bw,2) ;

这只是主要思想,您可能需要在边缘周围更加小心,或者用零填充以避免 conv2 可能产生的边缘伪影)...

另一种想法,使用 Hough transform 检测线并仅保留那些具有 theta=0 或 90 度的线...