I'm attempting to work out the centre of a planar polygon, and was wondering what the best way to approach this is.
I have access to the vertices that form the polygon, but nothing else.
Does anyone have any suggestions for how to approach this?
Thanks.
I wouldn't project to 2D.
Sum the coordinates of all vertices, and divide by the number of vertices. See centroid of a finite set of points.
sx = sy = sz = 0
for i in 1..n:
sx = sx + px[i]
sy = sy + py[i]
sz = sz + pz[i]
cx = sx/n
cy = sy/n
cz = sz/n
Sum the centers of all edges, weighted by the length of these edges, and divide by the total circumference.
sx = sy = sz = slen = 0
x1 = px[n]
y1 = py[n]
z1 = pz[n]
for i in 1..n:
x2 = px[i]
y2 = py[i]
z2 = pz[i]
dx = x2 - x1
dy = y2 - y1
dz = z2 - z1
len = sqrt(dx*dx + dy*dy + dz*dz)
sx = sx + (x1 + x2)/2*len
sy = sy + (y1 + y2)/2*len
sz = sz + (z1 + z2)/2*len
slen = slen + len
x1 = x2
y1 = y2
z1 = z2
cx = sx/slen
cy = sy/slen
cz = sz/slen
Triangulate the polygon, then sum the centers of mass of all triangles, weighted by their area, then divide by total area. You can choose a triangulation where not all the triangles are fully within the polygon, as long as the area outside is compensated for by triangles of a different orientation. The area of a triangle is half the length of the cross product of two of its edge vectors.
See centroid of polygon for the 2D case, but more appropriately centroid by geometric decomposition for this approach using areas. Also see centroid of triangle for the fact that the center of mass for the surface of a triangle is equal to the center of mass for its vertices.
sx = sy = sz = sarea = 0
x1 = px[1]
y1 = py[1]
z1 = pz[1]
for i in 3..n:
x2 = px[i-1]
y2 = py[i-1]
z2 = pz[i-1]
x3 = px[i]
y3 = py[i]
z3 = pz[i]
dx1 = x3 - x1
dy1 = y3 - y1
dz1 = z3 - z1
dx2 = x3 - x2
dy2 = y3 - y2
dz2 = z3 - z2
cpx = dy1*dz2 - dz1*dy2
cpy = dz1*dx2 - dx1*dz2
cpz = dx1*dy2 - dy1*dx2
area = sqrt(cpx*cpx + cpy*cpy + cpz*cpz)/2
sx = sx + (x1 + x2 + x3)/3*area
sy = sy + (y1 + y2 + y3)/3*area
sz = sz + (z1 + z2 + z3)/3*area
sarea = sarea + area
cx = sx/sarea
cy = sy/sarea
cz = sz/sarea
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With