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

鞋带公式的表达式为:

参考维基百科 - Shoelace_formula

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

也可理解为用最大矩形的面积减去各个三角形面积得到中间的多边形面积.

1. 鞋带公式实现

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

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 - 计算曲线与坐标轴的面积

计算曲线与坐标轴的面积

import numpy as np
import matplotlib.pyplot as plt
from numpy import trapz

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

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)
Last modification:June 20th, 2020 at 06:45 pm