python计算多边形面积骚操作
写在前面
这是一篇关于求多边形面积的文章,这类求面积原理基本都是积分/面积分解。常用于语义/实例分割中求取object的面积。
一、原理
参考文章:【国际数学竞赛】任意多边形面积计算公式
二、python实现的多种方法及测试
1、法一
def component_polygon_area(poly):
"""Compute the area of a component of a polygon.
Args:
x (ndarray): x coordinates of the component
y (ndarray): y coordinates of the component
Return:
float: the are of the component
"""
x = poly[:,0]
y = poly[:,1]
return 0.5 * np.abs(
np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) # np.roll 意即“滚动”,类似移位操作
# 注意这里的np.dot表示一维向量相乘
测试:
import numpy as np
x = np.random.rand(36,2)
area = component_polygon_area(x)
print("area",area)
输出:
2、法二
def calculate_triangle_area(poly_a, poly_b, poly_c):
triangle_area = 0.5*((poly_b[0] - poly_a[0])*(poly_c[1] - poly_a[1]) -
(poly_b[1] - poly_a[1])*(poly_c[0] - poly_a[0]))
return triangle_area
def cal_area(poly):
sum_area = 0
for i in range(1,poly.shape[0]-1):
temp = poly[i+1]
sum_area += calculate_triangle_area(poly[0],poly[i],temp)
return abs(sum_area)
测试:
x = np.random.rand(36,2)
area =cal_area(x)
print("area",area)
输出:
3、法一、法二对比测试:
三、结论
法一和法二两种方式计算的结果差不多,误差在小数点后14位以后了;
法一代码少,计算虽稍显复杂,但仍推荐使用(谁让咱们是程序猿呢 o(╥﹏╥)o))~