Wednesday, October 26, 2016

How to know if the polyline direction is clockwise or counter-clockwise?


I found myself puzzled with this question today, when dealing with closed lines today. I thought I could deal with this summing the horizontal deflections, but not every polygon works with this solution.
Then I found this interesting answer: 

http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order

The answer: you have to sum over the edges, (x2 − x1)*(y2 + y1). If the result is positive the curve is clockwise, if it's negative the curve is counter-clockwise. (The result is twice the enclosed area, with a +/- convention.)

If we have a list of tuples (x,y) representing point coordinates, named lstP:
lstEdge = []
for i in range(len(lstP)-1):
    lstEdge.append((lstP[i+1][0]-lstP[i][0])*(lstP[i+1][1]+lstP[i][1]))
result = sum(lstEdge)
if result>0:
   print "Clockwise"
else:
   print "Counter-Clockwise"

    

No comments:

Post a Comment