python计算任意多边形的面积

在网上发现一个很有意思且很有用的多边形面积计算公式-鞋带公式

鞋带公式的表达式为:

img

where
$\bullet A$ is the area of the polygon,
$\bullet n$ is the number of sides of the polygon, and $\cdot\left(x{i}, y{i}\right), i=1,2, \ldots, n$ are the ordered vertices (or “corners”) of the polygon.

参考wiki:Shoelace formula

可以理解为,是把每个顶点向x轴做垂线,每个边和坐标轴构成的梯形面积矢量和就是多边形的面积。

1. 鞋带公式实现

From: stackoverflow - calculate-area-of-polygon-given-x-y-coordinates

1
2
def polygon_area(x,y):
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

2. 示例1 - 计算曲线与坐标轴的面积

[计算曲线与坐标轴的面积

1
2
3
4
5
6
7
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)
plt.plot(x, y)
plt.show()
area_value = polygon_area(np.append(x, 0), np.append(y, 0))

3. 示例2 - detectron2 mask 面积

detectron2/structures/masks.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def area(self):
"""
Computes area of the mask.
Only works with Polygons, using the shoelace formula
Returns:
Tensor: a vector, area for each instance
"""
area = []
for polygons_per_instance in self.polygons:
area_per_instance = 0
for p in polygons_per_instance:
area_per_instance += polygon_area(p[0::2], p[1::2])
area.append(area_per_instance)

return torch.tensor(area)

在线多变形面积计算工具

多边形面积计算工具

image-20200916102553183