计算由(x,y)坐标给出的多边形面积

79

我有一组点,想知道是否有一种函数(为了方便和速度),可以计算由这组点围成的区域面积。

例如:

x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)

points = zip(x,y)

给定points,面积应该大致等于(pi-2)/4。也许可以用scipy、matplotlib、numpy、shapely等库来实现这个功能?我不会遇到x或y坐标为负数的情况……并且它们将是没有定义函数的多边形。

编辑:

points很可能不会按任何指定顺序(顺时针或逆时针)排列,并且可能非常复杂,因为它们是一个shapefile下一组边界内的utm坐标集合。

13个回答

0
def find_int_coordinates(n: int, coords: list[list[int]]) -> float:
    rez = 0
    x, y = coords[n - 1]
    for coord in coords:
        rez += (x + coord[0]) * (y - coord[1])
        x, y = coord
    return abs(rez / 2)

0
鞋带公式来自于根据多边形周围连续点计算内部三角形。基于这个解释编写代码可能会更加详细。多边形的面积只需将相邻向量的叉乘(行列式)长度除以二,然后将所有结果相加即可。

https://youtu.be/0KjG8Pg6LGk?t=213

import numpy as np, numpy.linalg as lin

def area(pts):
    ps = np.array([0.5 * lin.det(np.vstack((pts[i], pts[i+1]))) for i in range(len(pts)-1)])
    s = np.sum(ps)
    p1,p2 = pts[-1],pts[0] # cycle back, last pt with the first 
    s += 0.5 * lin.det(np.vstack((p1,p2)))
    return np.abs(s)

points = np.array([[0,0],[10,0],[10,10],[0,10]])
area(points) # 100

0

基于

https://www.mathsisfun.com/geometry/area-irregular-polygons.html

def _area_(coords):
    t=0
    for count in range(len(coords)-1):
        y = coords[count+1][1] + coords[count][1]
        x = coords[count+1][0] - coords[count][0]
        z = y * x
        t += z
    return abs(t/2.0)

a=[(5.09,5.8), (1.68,4.9), (1.48,1.38), (4.76,0.1), (7.0,2.83), (5.09,5.8)]
print _area_(a)

诀窍在于第一个坐标也应该是最后一个。


当我尝试使用15个顶点的更复杂区域时,它给出了错误的结果。 - Edip Ahmet
请问您能提供坐标吗? - Takis Tsiberis
抱歉,是我的错。我测试了您的代码几次,并将结果与CAD软件进行了比较。我测试了coords = [(1141.784, 893.124), (1521.933, 893.124), (1521.933, 999.127), (1989.809, 999.127), (1989.809, 622.633),(2125.054, 622.633), (2125.054, 326.556), (1372.067, 326.556), (1372.067, -60.903), (1872.84, -60.903),(1872.84, 52.41), (2015.396, 52.41), (2015.396, -455.673), (1090.611, -455.673), (1086.955, 436.214), (1141.784, 893.124)]。昨天我得到了错误的结果,可能是我漏掉了什么,今天它像PolygonArea函数一样运行得很好。 - Edip Ahmet
我想我不小心注释掉了它,也许昨天我在这里尝试了另一个函数。 - Edip Ahmet
1
很高兴我能帮到你。 - Takis Tsiberis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接