numpy 在Python中查找面的质心

j8ag8udp  于 2023-03-18  发布在  Python
关注(0)|答案(4)|浏览(229)

我想计算一个由点组成的图形的质心:(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
import matplotlib.pyplot as plt

poligono = 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)])

x = pontos[:, 0]
y = pontos[:, 1]

points_array_2 = np.array(points)

centroid = np.mean(points_array_2, axis=0)

print("Centroide:", centroid)

我想知道是否有人可以帮助我正确计算多边形的质心

imzjd6km

imzjd6km1#

已经提供了非常好和详细的答案。如果你不想从头开始做数学,我强烈建议在处理多边形时使用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)
axzmvihb

axzmvihb2#

固定:

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
wfypjpf4

wfypjpf43#

下面是一些代码,解释如下。

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]

基本思想是将形状分解为三角形,通过一个明显的公式(即顶点的平均值)计算每个三角形的质心,要计算整个多边形的质心,只需计算组成三角形的质心的平均值,每个三角形按其面积(带符号)加权。
对于多边形来说,这一任务之所以特别容易,是因为我们可以允许自己包含“负”三角形--也就是说,我们可以将多边形表示为三角形的和与差。只要我们跟踪面积中的符号,一切都可以解决。因此,不必担心多边形是否是凸的,或者原点是否在多边形内部。
在上面的代码中,我们简单地分解成由连续顶点和原点组成的三角形。
更多信息请参见维基百科页面。

zf2sa74q

zf2sa74q4#

一系列对准点的质心是它们的平均值。
对于闭合的、非自相交的多边形,必须使用一些更复杂的公式,请参见wikipedia centroid中的“多边形的”
注意,我想你还需要梁的惯性,为此,我建议分解成三角形和三角形,然后使用斯坦纳定理

相关问题