Skip to content

Instantly share code, notes, and snippets.

@mistycheney
Created March 13, 2016 11:41
Show Gist options
  • Save mistycheney/4f274f6c4436bda614e5 to your computer and use it in GitHub Desktop.
Save mistycheney/4f274f6c4436bda614e5 to your computer and use it in GitHub Desktop.
sort polygon vertices counterclockwise
def less(center):
def less_helper(a, b):
if (a[0] - center[0] >= 0 and b[0] - center[0] < 0):
return 1;
if (a[0] - center[0] < 0 and b[0] - center[0] >= 0):
return -1;
if (a[0] - center[0] == 0 and b[0] - center[0] == 0):
if (a[1] - center[1] >= 0 or b[1] - center[1] >= 0):
return 2*int(a[1] > b[1]) - 1;
return 2*int(b[1] > a[1]) - 1
# compute the cross product of vectors (center -> a) x (center -> b)
det = (a[0] - center[0]) * (b[1] - center[1]) - (b[0] - center[0]) * (a[1] - center[1])
if (det < 0):
return 1;
if (det > 0):
return -1;
# points a and b are on the same line from the center
# check which point is closer to the center
d1 = (a[0] - center[0]) * (a[0] - center[0]) + (a[1] - center[1]) * (a[1] - center[1])
d2 = (b[0] - center[0]) * (b[0] - center[0]) + (b[1] - center[1]) * (b[1] - center[1])
return 2*int(d1 > d2) - 1
return less_helper
def sort_vertices_counterclockwise(cnt):
# http://stackoverflow.com/a/6989383
center = cnt.mean(axis=0)
return sorted(cnt, cmp=less(center))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment