在 Python 中找到多边形的质心

问题描述 投票:0回答:4

我想计算由以下点组成的图形的质心:(0,0), (70,0), (70,25), (45, 45), (45, 180), (95, 188) , (95, 200), (-25, 200), (-25,188), (25,180), (25,45), (0, 25), (0,0).

我知道这个多边形的质心的正确结果是 x = 35 和 y = 100.4615,但是下面的代码没有返回正确的值(下面的多边形图)。

import numpy as np

points = np.array([(0,0), (70,0), (70,25), (45,45), (45,180), (95,188), (95,200), (-25,200), (-25, 188), (25,180), (25,45), (0,25), (0,0)])
centroid = np.mean(points, axis=0)
print("Centroide:", centroid)

输出:

Centroide: [32.30769231 98.15384615]

如何正确计算多边形的质心?

python numpy geometry polygon
4个回答
3
投票

如果你不想从头开始计算,我强烈建议在处理多边形时使用 shapely 库。

要根据给定的顶点坐标计算多边形的质心,您可以执行以下操作:

from shapely.geometry import Polygon
polygon = Polygon([(0,0), (70,0), (70,25), (45, 45), (45, 180), (95, 188), (95, 200), (-25, 200), (-25,188), (25,180), (25,45), (0, 25)])
print(polygon.centroid)
>>> POINT (35 100.46145124716553)

2
投票

固定:

def centroid(vertices):
    x, y = 0, 0
    n = len(vertices)
    signed_area = 0
    for i in range(len(vertices)):
        x0, y0 = vertices[i]
        x1, y1 = vertices[(i + 1) % n]
        # shoelace formula
        area = (x0 * y1) - (x1 * y0)
        signed_area += area
        x += (x0 + x1) * area
        y += (y0 + y1) * area
    signed_area *= 0.5
    x /= 6 * signed_area
    y /= 6 * signed_area
    return x, y

x, y = centroid(vertices)
print(x, y)

出品:

35.0 100.46145124716553

2
投票

这是一些代码。解释如下。

import numpy as np

polygon = np.array(
    [
        (0,0), (70,0), (70,25), (45, 45), (45, 180), (95, 188),
        (95, 200), (-25, 200), (-25,188), (25,180), (25,45), (0, 25),
    ],
    dtype=np.float64,
)

# Same polygon, but with vertices cycled around. Now the polygon
# decomposes into triangles of the form origin-polygon[i]-polygon2[i]
polygon2 = np.roll(polygon, -1, axis=0)

# Compute signed area of each triangle
signed_areas = 0.5 * np.cross(polygon, polygon2)

# Compute centroid of each triangle
centroids = (polygon + polygon2) / 3.0

# Get average of those centroids, weighted by the signed areas.
centroid = np.average(centroids, axis=0, weights=signed_areas)

print("Centroid:", centroid)

在我的机器上运行这段代码的结果是你期望的:

$ python polygon_centroid.py
Centroid: [ 35.         100.46145125]

基本思路是我们把形状分解成三角形。我们可以通过明显的公式计算每个三角形的质心(它是顶点的平均值)。要计算整个多边形的质心,我们只需计算组成三角形的质心的平均值,每个三角形由其(带符号的)面积加权。

使这个任务对于多边形特别容易的原因是我们可以允许自己包含“负”三角形——也就是说,我们可以将多边形表示为三角形的和与差。只要我们跟踪该地区的标志,一切都会顺利进行。因此,无需担心您的多边形是否为凸面,或者原点是否在多边形内部。

在上面的代码中,我们简单的分解为由连续的顶点连同原点组成的三角形。

有关更多信息,请参阅此维基百科页面


1
投票

一系列对齐点的质心是它们的平均值。

关闭。非自相交的多边形,您必须使用一些更兼容的公式 请参阅 wikipedia centroid

的“Of a polygon”

一个注意事项。我猜你还需要光束的惯性。为此,我建议分解成三角形和三角形,然后使用斯坦纳定理https://es.wikipedia.org/wiki/Teorema_del_eje_paralelo

© www.soinside.com 2019 - 2024. All rights reserved.