Skip to content

Instantly share code, notes, and snippets.

@AndrewTheTM
Created January 27, 2022 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewTheTM/a2357a36f162f4d1ab1068f30f6bf67f to your computer and use it in GitHub Desktop.
Save AndrewTheTM/a2357a36f162f4d1ab1068f30f6bf67f to your computer and use it in GitHub Desktop.
I'm putting this here for posterity. This is how pretty accurate centroids can be determined from a set of points. This was originally written using the shapefile library, and I no longer need it in my code because I'm switching everything to the geopandas package (because of another step that needs geoprocessing that the shapefile library doesn…
def getCentroidFromPoints(self, s):
points = s.points
p_x = 0
p_y = 0
pp = np.array(s.points)
pp = np.append(pp, [pp[0]], axis = 0)
area = self.shoelace(pp)
for p in range(0, len(pp) - 1):
p_x += (pp[p, 0] + pp[p + 1, 0])*(pp[p, 0] * pp[p + 1, 1] - pp[p + 1, 0] * pp[p, 1])
p_y += (pp[p, 1] + pp[p + 1, 1])*(pp[p, 0] * pp[p + 1, 1] - pp[p + 1, 0] * pp[p, 1])
return((-1.0 / (6 * area) * p_x, -1.0 / (6 * area) * p_y))
def shoelace(self, x_y):
# Thanks to https://stackoverflow.com/a/58515054/877387
x_y = x_y.reshape(-1,2)
x = x_y[:,0]
y = x_y[:,1]
S1 = np.sum(x * np.roll(y,-1))
S2 = np.sum(y * np.roll(x,-1))
area = .5 * np.absolute(S1 - S2)
return area
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment