如何在python中以匀称的方式计算重心?

Via*_*eux 9 python shapely

我发现了匀称但我没有找到如何计算多边形的重心!

有人有解决方案吗?

ewc*_*wcz 18

如果您的多边形具有均匀的密度,则其质心与其质心重合。在shapely中,质心可以直接计算为:

from shapely.geometry import Polygon

P = Polygon([[0, 0], [1, 0], [1, 1], [0, 1]])

print(P.centroid)
#POINT (0.5 0.5)
Run Code Online (Sandbox Code Playgroud)


Mar*_*hke 6

一个解决方案没有shapely

您也可以仅使用 手动计算它numpy

import numpy as np

def polygon_area(xs, ys):
    """https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"""
    # /sf/answers/2128617781/
    return 0.5 * (np.dot(xs, np.roll(ys, 1)) - np.dot(ys, np.roll(xs, 1)))

def polygon_centroid(xs, ys):
    """https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"""
    xy = np.array([xs, ys])
    c = np.dot(xy + np.roll(xy, 1, axis=1),
               xs * np.roll(ys, 1) - np.roll(xs, 1) * ys
               ) / (6 * polygon_area(xs, ys))
    return c

print(polygon_centroid(xs=[0, 1, 1, 0], ys=[0, 0, 1, 1]),
      'expect: [.5, .5]')
print(polygon_centroid(xs=[0, 0, 2], ys=[1, -1, 0]),
      'expect: [2/3, 0]')
print(polygon_centroid(xs=[0, 0, 2], ys=[-1, 1, 0]),
      'expect: [2/3, 0]')

# https://wolfram.com/xid/0e5bspgmqyj9a5-cfx5ps
print(polygon_centroid(xs=[0, 1, 1.5, 1, 0, -.5], ys=[0, 0, .5, 1, 1, .5]),
      'expect: [.5, .5]')
Run Code Online (Sandbox Code Playgroud)

输出

[0.5 0.5]          expect: [.5, .5]
[0.66666667 -0. ]  expect: [2/3, 0]
[0.66666667 0.  ]  expect: [2/3, 0]
[0.5 0.5]          expect: [.5, .5]
Run Code Online (Sandbox Code Playgroud)


Mau*_*ata 5

上面的答案是对的。但有时您不想使用这种格式。因此,要获得可以使用的值:

from shapely.geometry import Polygon
centroid =   list(Polygon([[0, 0], [1, 0], [1, 1], [0, 1]]).centroid.coords)
#[(0.5, 0.5)]
Run Code Online (Sandbox Code Playgroud)

我已经针对更复杂的几何结构测试了这种方法,并且效果很好。