python 计算多边形面积的骚操作


写在前面
这是一篇关于求多边形面积的文章,这类求面积原理基本都是积分/面积分解。常用于语义/实例分割中求取object的面积。

一、原理

参考文章:【国际数学竞赛】任意多边形面积计算公式

二、python实现的多种方法及测试

1、法一

来源:stackoverflow

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))~

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乄洛尘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值