![](/img/trans.png)
[英]Python: find a method to calculate the “inner centroid” (X,Y) of a polygon
[英]Error in a python function to calculate the centroid of a polygon
這是我必須計算多邊形質心的函數,如此處所述: 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))
它不是用高效的Python(擴展用於循環等)編寫的,因為它最初的意圖是Cython。 為了輕松了解發生了什么,我將其轉換為Python。
這是我得到的輸出: centroid: [ 5307119.41815466 5689101.16579313]
... [37.5, 37.5]
。
錯誤在哪里? 我自己對代碼進行了三遍檢查,現在開始懷疑我的理智。
您應該這樣做:
area_factor = 1/(6.*area)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.