如何在MATLAB中识别多个相交的多边形?

时间:2018-06-20 18:52:22

标签: matlab geometry polygon intersection overlap

我正在尝试识别重叠/相交的多边形。我发现的技术一次只能比较两个多边形。我在一个数据集中有上万个单元,每个单元中有2-20个多边形,每个多边形均由x-y坐标描述。我想在每个单元格中找到重叠的多边形。每对之间的循环很慢,所以我想问一下...

是否可以同时比较所有多边形并提取重叠的ID?

这是数据集中单个条目的简单示例:

mutate()

此示例包含以下4个多边形:

The example dataset contains these 4 polygons

此图是用单独的“多边形”对象制作的,但这并不意味着我需要在解决方案中使用这种对象。

我想要的输出是每个重叠对的记录:

shapes = cell(4,2);
shapes{1,1} = 'poly1';
shapes{2,1} = 'poly2';
shapes{3,1} = 'poly3';
shapes{4,1} = 'poly4';
shapes{1,2} = [1, 3, 3; 1, 1, 3]';
shapes{2,2} = [2, 4, 2; 2, 2, 5]';
shapes{3,2} = [4, 5, 5, 4; 3, 3, 5, 5]';
shapes{4,2} = [1, 3, 3, 1; 4, 4, 6, 6]';

P.S。我当前的方法是遍历每对,并在该对的每个多边形上使用poly2mask函数。然后使用&运算符将二进制掩码加在一起。这样会产生一个逻辑1的数组,其中有任何重叠。

P.P.S。我要查看的实际多边形都是环形扇区,因此它们都不都是凸形

Annular sector

1 个答案:

答案 0 :(得分:1)

这是一个利用“多边形”向量的解决方案,避免了在多余的循环中进行所有成对比较(尽管我不知道“重叠”函数的工作原理)。

% Set up empty vector to hold the different shapes
polyvec = [];

% Loop all shapes and combine into polyshape vector
for ii = 1 : size(shapes, 1)

    poly = polyshape(shapes{ii,2}(:,1), shapes{ii,2}(:,2));

    % When you combine polyshape objects together the you get 
    % a vector that is of the polyshape object type
    polyvec = [polyvec, poly];

end

% Use the overlap function to compute a symmetric binary matrix 
% of which polygons in the polygon vector overlap. 
interMatSym = overlaps(polyvec);

% I only need the upper triangle of the symmetric interaction 
% matrix and all polygons overlap with themselves so use 'triu'
interMat = triu(overlaps(polyvec), 1);

% Find the coordinates of the overlap in the interaction matrix
[x, y] = find(interMat);

% Save the result
result = [shapes(x,1), shapes(y,1)];

result =
  2×2 cell array
    {'poly1'}    {'poly2'}
    {'poly2'}    {'poly4'}

如果有一种方法可以更有效地创建polyshpae向量,那么我很想知道!