python函数中的错误,用于计算多边形的质心

时间:2015-02-15 02:37:46

标签: python debugging

这是我必须计算多边形质心的函数,如下所述: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]

错误在哪里?我自己对代码进行了三次检查,现在我开始怀疑自己的理智。

1 个答案:

答案 0 :(得分:1)

你应该这样做:

area_factor = 1/(6.*area)