Skip to content

Instantly share code, notes, and snippets.

@marcbln
Created April 13, 2022 18:30
Show Gist options
  • Save marcbln/4fc3d5179d06adb5a82551db43d80b07 to your computer and use it in GitHub Desktop.
Save marcbln/4fc3d5179d06adb5a82551db43d80b07 to your computer and use it in GitHub Desktop.
calculatin of centroid of a polygon in python
#!/usr/bin/env python3
# calculatin of centroid of a polygon
# original: https://stackoverflow.com/a/43747218/2848530
# 04/2022 created
from typing import List
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def get_polygon_centroid(pts: List[Point]) -> Point:
first = pts[0]
last = pts[-1]
if first.x != last.x or first.y != last.y:
pts = pts.copy()
pts.append(first)
twicearea = 0
x = 0
y = 0
nPts = len(pts)
i = 0
j = nPts - 1
while i < nPts:
p1 = pts[i]
p2 = pts[j]
f = (p1.y - first.y) * (p2.x - first.x) - (p2.y - first.y) * (p1.x - first.x)
twicearea += f
x += (p1.x + p2.x - 2 * first.x) * f
y += (p1.y + p2.y - 2 * first.y) * f
j = i
i += 1
f = twicearea * 3
return Point(x / f + first.x, y / f + first.y)
# ---------- MAIN ------------
pts = [
Point(78.0001462, 40.0008827),
Point(78.0000228, 40.0008940),
Point(78.0000242, 40.0009264),
Point(78.0001462, 40.0008827),
]
c = get_polygon_centroid(pts)
print(c) # --> Point(78.0000644, 40.000901033333335)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment