已知多边形顶点坐标求面积(C++ / Python)

本文详细介绍了如何通过顶点坐标计算多边形面积的方法,包括三角形、四边形及多边形的面积计算公式,并提供了C++和Python的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多边形面积: S○ = ½ * |S1 - S2|
S1与S2表示为顶点坐标xy的交叉乘加,面积取绝对值。

S1 = (x1y2+x2y3+…+xn·y1)
S2 = (x1yn+x2y1+x3y2+…xn·ym) (m为n-1)

C++(完整代码):

#include <vector>
#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

/**
* @brief calculate the Polygon Area with vertex coordinates
* @refer https://blog.csdn.net/qq_38862691/article/details/87886871
*
* @param points: input vertex coordinates
* @return float: polygon area
*/
double getPolygonArea(vector<Point> const& points)
{
	const int sizep = points.size();
	if(sizep<3)	return 0.0;

	double area = points.back().x * points[0].y - points[0].x * points.back().y;
	for(int i=1,v=0;i<sizep;i++,v++) {
		area += (points[v].x * points[i].y);
		area -= (points[i].x * points[v].y);
	}

	return fabs(0.5 * area);
}

Python(完整代码):

import os

def getPolygonArea(points):
    '''
    brief: calculate the Polygon Area with vertex coordinates
    refer: https://blog.csdn.net/qq_38862691/article/details/87886871
    :param points: list, input vertex coordinates
    :return: float, polygon area
    '''

    sizep = len(points)
    if sizep<3:
        return 0.0

    area = points[-1][0] * points[0][1] - points[0][0] * points[-1][1]
    for i in range(1, sizep):
        v = i - 1
        area += (points[v][0] * points[i][1])
        area -= (points[i][0] * points[v][1])

    return abs(0.5 * area)

方法从三角形面积的计算开始推导:

一、三角形面积
已知三角形顶点坐标A(x1,y1),B(x2,y2),C(x3,y3),求三角形ABC面积。

1.列行列式
|x1 y1 1|
|x2 y2 1|
|x3 y3 1|

2.顺序交叉乘加
(*可以忽略第3列的1,下同)
S1 = (x1y2+x2y3+x3y1)

3.逆序交叉乘加
S2 = (x1y3+x2y1+x3y2)

4.得到ABC面积
S△ABC = ½ * |S1 - S2|

二、四边形面积
已知四边形顶点坐标A(x1,y1),B(x2,y2),C(x3,y3),D(x4,y4),求四边形ABCD面积。

1.列行列式
|x1 y1 1|
|x2 y2 1|
|x3 y3 1|
|x4 y4 1|

2.顺序交叉乘加
S1 = (x1y2+x2y3+x3y4+x4y1)

3.逆序交叉相乘
S2 = (x1y4+x2y1+x3y2+x4y3)

4.得到ABCD面积
S□ABCD = ½ * |S1 - S2|

三、多边形面积
已知多边形顶点坐标A(x1,y1),B(x2,y2)…(xn,yn),求多边形面积。

1.列行列式
|x1 y1 1|
|x2 y2 1|
|......1|
|xn yn 1|

2.顺序交叉乘加
S1 = (x1y2+x2y3+...+xn·y1)

3.逆序交叉乘加
S2 = (x1yn+x2y1+x3y2+...xn·ym)		(m为n-1)

4.得到多边形面积
S○ = ½ * |S1 - S2|
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值