Here's a function I have to calculate the centroid of a polygon, as described here: http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
import numpy as np
# a polygon approximating a circle with geometric centre at (37.5, 37.5)
testpoly = np.array(
[[ 50., 37.5 ],
[ 48.91931822, 42.58420804],
[ 45.86413258, 46.78931032],
[ 41.36271243, 49.38820645],
[ 36.19339421, 49.93152369],
[ 31.25, 48.32531755],
[ 27.38728757, 44.84731565],
[ 25.27315499, 40.09889614],
[ 25.27315499, 34.90110386],
[ 27.38728757, 30.15268435],
[ 31.25, 26.67468245],
[ 36.19339421, 25.06847631],
[ 41.36271243, 25.61179355],
[ 45.86413258, 28.21068968],
[ 48.91931822, 32.41579196]])
def calculate_poly_centroid(vertex_coords, num_vertices):
xs = vertex_coords[:, 0]
ys = vertex_coords[:, 1]
centroid = np.zeros(2, dtype=np.float64)
area = 0
for index in range(num_vertices-1):
area += 0.5*(xs[index]*ys[index+1] - xs[index+1]*ys[index])
area_factor = (1/6.)*area
sum_x = 0
sum_y = 0
for index in range(num_vertices-1):
k = (xs[index]*ys[index+1] - xs[index+1]*ys[index])
sum_x += area_factor*(xs[index] + xs[index+1])*k
sum_y += area_factor*(ys[index] + ys[index+1])*k
centroid[0] = sum_x
centroid[1] = sum_y
print "centroid: ", centroid
return centroid
calculate_poly_centroid(testpoly, len(testpoly))
It is not written in efficient Python (expanded for loops, etc.) because it was initially meant to be Cython. I have converted it to Python for the sake of easily understanding what's going on.
Here's the output I get: centroid: [ 5307119.41815466 5689101.16579313]
...which is way off [37.5, 37.5]
.
Where does the error lie? I have triple checked the code myself, and am now beginning to doubt my sanity.
您应该这样做:
area_factor = 1/(6.*area)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.