0

I would like to detect the location (i.e. the polygon) that describes loops in a polyline. For example the following polyline has 3 loops.

enter image description here

I had code to determine if two line-segments intersect but would like to find the region that corresponds to the loop:

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

def ccw(A,B,C):
    return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x)

def intersect(A,B,C,D):
    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

Here is the code for the plot above:

import pylab

points = [
    [-326.0419254504, -160.71836672119],
    [-144.5703805370, 3.89159459966009],
    [-163.5692598748, 142.014754139665],
    [-260.4767655176, 108.905787255049],
    [-142.6710783719, -46.249469979213],
    [-22.96021284291, 16.1890735212646],
    [ 86.29780272233, 106.064044401492],
    [ 196.5051938150, 124.986746707329],
    [ 161.3537057610, 76.7377751584564],
    [ 130.0004832662, 133.499810130049],
    [ 211.7040108463, 212.968452780035],
    [ 279.1609152616, 124.043058681519],
    [ 219.3115560361, -57.600537709290],
    [ 52.09696347526, -149.37169880679],
    [-52.41376323308, -165.45492932181],
    [-24.86101299577, -200.45984531646],
    [ 1.741836268130, -113.42121703400],
    [-200.6288906555, -155.99195627907],
]

x, y = zip(*points)

pylab.figure()
pylab.plot(x, y, 'g', lw=5)
pylab.show()
nickponline
  • 25,354
  • 32
  • 99
  • 167

1 Answers1

0

Not efficient, but easy to implement:

  • try every segment A in order along the polyline,

  • for every segment A, try all following segments B, in order along the polyline,

  • if you detect an intersection between A and B, you have found a loop; continue the scan from the segment B;

  • if you don't detect an intersection, you are done for the segment A, continue the scan.


A more efficient but more complex solution is

  • to use a line segment intersection algorithm, such as Bentley and Ottmann;

  • to order the intersections by the index of the first segment;

  • loops are joining the odd numbered to the even numbered intersections.