计算给定 (x,y) 坐标的多边形面积 [英] Calculate area of polygon given (x,y) coordinates
问题描述
我有一组点,想知道是否有一个函数(为了方便和速度)可以计算一组点所包围的面积.
I have a set of points and would like to know if there is a function (for the sake of convenience and probably speed) that can calculate the area enclosed by a set of points.
例如:
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 坐标的任何负值......它们将是没有任何定义函数的多边形.
given points
the area should be approximately equal to (pi-2)/4
. Maybe there is something from scipy, matplotlib, numpy, shapely, etc. to do this? I won't be encountering any negative values for either the x or y coordinates... and they will be polygons without any defined function.
点很可能没有任何指定的顺序(顺时针或逆时针),并且可能非常复杂,因为它们是来自一组边界下的 shapefile 的一组 utm 坐标
points will most likely not be in any specified order (clockwise or counterclockwise) and may be quite complex as they are a set of utm coordinates from a shapefile under a set of boundaries
推荐答案
鞋带公式的实现可以在 Numpy
中完成.假设这些顶点:
Implementation of Shoelace formula could be done in Numpy
. Assuming these vertices:
import numpy as np
x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)
我们可以重新定义numpy中的函数来求面积:
We can redefine the function in numpy to find the area:
def PolyArea(x,y):
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
并获得结果:
print PolyArea(x,y)
# 0.26353377782163534
避免 for
循环使这个函数比 PolygonArea
快 50 倍:
Avoiding for
loop makes this function ~50X faster than PolygonArea
:
%timeit PolyArea(x,y)
# 10000 loops, best of 3: 42 µs per loop
%timeit PolygonArea(zip(x,y))
# 100 loops, best of 3: 2.09 ms per loop.
计时在 Jupyter notebook 中完成.
Timing is done in Jupyter notebook.
这篇关于计算给定 (x,y) 坐标的多边形面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!