In this post I will show a way to calculate the centroid of a non-self-intersecting closed polygon.
I used the following formulas,
as shown in https://en.wikipedia.org/wiki/Centroid#Centroid_of_a_polygon .
In the following code, the function receives the coordinates as a list of lists or as a list of tuples.
from math import sqrt def centroid(lstP): sumCx = 0 sumCy = 0 sumAc= 0 for i in range(len(lstP)-1): cX = (lstP[i][0]+lstP[i+1][0])*(lstP[i][0]*lstP[i+1][1]-lstP[i+1][0]*lstP[i][1]) cY = (lstP[i][1]+lstP[i+1][1])*(lstP[i][0]*lstP[i+1][1]-lstP[i+1][0]*lstP[i][1]) pA = (lstP[i][0]*lstP[i+1][1])-(lstP[i+1][0]*lstP[i][1]) sumCx+=cX sumCy+=cY sumAc+=pA print cX,cY,pA ar = sumAc/2.0 print ar centr = ((1.0/(6.0*ar))*sumCx,(1.0/(6.0*ar))*sumCy) return centr
No comments:
Post a Comment