多边形面积: 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|