简体   繁体   English

python函数计算多边形质心时出错

[英]Error in a python function to calculate the centroid of a polygon

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 这是我必须计算多边形质心的函数,如此处所述: 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. 它不是用高效的Python(扩展用于循环等)编写的,因为它最初的意图是Cython。 I have converted it to Python for the sake of easily understanding what's going on. 为了轻松了解发生了什么,我将其转换为Python。

Here's the output I get: centroid: [ 5307119.41815466 5689101.16579313] 这是我得到的输出: centroid: [ 5307119.41815466 5689101.16579313]

...which is way off [37.5, 37.5] . ... [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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM