首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中用shapely计算重心?

如何在python中用shapely计算重心?
EN

Stack Overflow用户
提问于 2018-11-27 22:33:16
回答 3查看 13K关注 0票数 11

我发现了形状,但我不知道如何计算多边形的重心!

有人有解决方案吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-11-29 18:26:56

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

代码语言:javascript
复制
from shapely.geometry import Polygon

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

print(P.centroid)
#POINT (0.5 0.5)
票数 22
EN

Stack Overflow用户

发布于 2019-07-19 00:18:38

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

代码语言:javascript
复制
from shapely.geometry import Polygon
centroid =   list(Polygon([[0, 0], [1, 0], [1, 1], [0, 1]]).centroid.coords)
#[(0.5, 0.5)]

我已经对更复杂的几何图形测试了这种方法,它工作得很好。

票数 9
EN

Stack Overflow用户

发布于 2021-03-25 22:34:26

没有shapely的解决方案

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

代码语言:javascript
复制
import numpy as np

def polygon_area(xs, ys):
    """https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"""
    # https://stackoverflow.com/a/30408825/7128154
    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]')

输出

代码语言:javascript
复制
[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]
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53502002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档