简体   繁体   English

Python中的凸包区域?

[英]Convex hull area in Python?

I have a set of points A .我有一组点A I get the convex hull CH_A of A .我得到A的凸包CH_A

Then, I have extra points, point set B .然后,我有额外的点,点集B I add B into A and get a bigger point set.我将B添加到A并获得更大的点集。 I obtain the convex hull CH_AB of this bigger set containing both A and B .我获得了包含AB更大集合的凸包CH_AB

I want to quantify how much I have to pay to add B into set A .我想量化将B添加到集合A需要支付的费用。 I am thinking about using an additional area to quantify this cost.我正在考虑使用一个额外的区域来量化这个成本。

Say CH_A has an area of Area_A , then CH_AB has an area of Area_AB .假设CH_A的面积为Area_A ,那么CH_AB的面积为Area_AB Then, I want to calculate the marginal cost as然后,我想计算边际成本为

(Area_AB - Area_A) / Area_A 

How may I get the area of the convex hull in Python?如何在 Python 中获得凸包的面积?

You could just use the ConvexHull class from scipy.spatial .你可以只用ConvexHull类从scipy.spatial It will not only give you the hull's area, but it will compute the hull for you as well.它不仅会为您提供船体的面积,还会为您计算船体。 But if you do use it, BEWARE!但是,如果您确实使用它,请注意 In 2D, the attribute you want to use is not area , it is volume , because the former will actually give you the hull's perimeter.在 2D 中,您要使用的属性不是area ,而是volume ,因为前者实际上会给您船体的周长。

That's because the attributes are named after their values in 3D, where area will indeed be the hull's area, and volume , well, its volume.那是因为属性以其在 3D 中的值命名,其中area确实是船体的面积,而volume它的体积。 For 2D hulls, the names are the same, but what they actually contain is not quite what it says on the tin.对于 2D 外壳,名称是相同的,但它们实际包含的内容与罐头上所说的不同。 Worse, the documentation does not warn you about this.更糟糕的是,文档不会就此向您发出警告。

(You can easily check this with trivial examples such as an isosceles right triangle of length 1 on its legs: the perimeter should be 2+sqrt(2), or about 3.414213562, and the area should be 0.5.) (您可以通过一些简单的例子轻松地检查这一点,例如边上长度为 1 的等腰直角三角形:周长应为 2+sqrt(2),或约为 3.414213562,面积应为 0.5。)

Convex hull is simply a convex polygon so you can easily try {this} or {this} to find area of 2D polygon. Convex hull只是一个凸多边形,因此您可以轻松地尝试使用{this}{this}来查找 2D 多边形的面积。

Something like the following (our version):类似于以下内容(我们的版本):

def PolyArea2D(pts):
    lines = np.hstack([pts,np.roll(pts,-1,axis=0)])
    area = 0.5*abs(sum(x1*y2-x2*y1 for x1,y1,x2,y2 in lines))
    return area

in which pts is array of polygon's vertices ie, a (nx2) array.其中 pts 是多边形顶点数组,即 (nx2) 数组。

Full usage:完整使用:

import numpy as np

def PolyArea2D(pts):
    lines = np.hstack([pts,np.roll(pts,-1,axis=0)])
    area = 0.5*abs(sum(x1*y2-x2*y1 for x1,y1,x2,y2 in lines))
    return area

pts = [[0,0],[1,0],[1,1],[0,1]]
print PolyArea2D(pts)    

pts = [[0,0],[1,0],[0,1]]
print PolyArea2D(pts)    

pts = [[0,0],[1,0],[0.5,0.5]] 
print PolyArea2D(pts)    

>>>
1.0
0.5
0.25

您可以使用多边形库为您做数学运算: https//pypi.python.org/pypi/Polygon/2.0.4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM