知方号

知方号

计算不规则四边形的面积+代码实现<不规则四边形面积公式推导>

计算不规则四边形的面积+代码实现

求两点间距离 /***** 求两点间距离*****/float getDistance(CvPoint pointO, CvPoint pointA){    float distance;    distance = powf((pointO.x - pointA.x), 2) + powf((pointO.y - pointA.y), 2);    distance = sqrtf(distance);    return distance;} 点到直线的距离:P到AB的距离 /***** 点到直线的距离:P到AB的距离*****///P为线外一点,AB为线段两个端点float getDist_P2L(CvPoint pointP, CvPoint pointA, CvPoint pointB){    //求直线方程    int A = 0, B = 0, C = 0;    A = pointA.y - pointB.y;    B = pointB.x - pointA.x;    C = pointA.x*pointB.y - pointA.y*pointB.x;    //代入点到直线距离公式    float distance = 0;    distance = ((float)abs(A*pointP.x + B*pointP.y + C)) / ((float)sqrtf(A*A + B*B));    return distance;} 只知道一个不规则四边形的边长,能计算出其面积吗?为什么?

 

不能!因为根据四边形的四条边,不能确定一个四边形的形状,所以四边形面积的大小是不定的。

比如下图中,蓝色和红色的四边形存在可变性,面积也会跟着变化,而且凸四边形在边长不变的情况下,还可以转变为凹四变形使得面积减小。

 

要证明这点,我们需要利用到,一般四边形(凸四边形)的婆罗摩笈[jí]多公式:

其中S为四边形的面积,a、b、c、d为四边形的四边长度,θ为四边形任一对角和的一半,s为半周长(a+b+c+d)/2。

我们可以看出,角度θ并不是确定值,会随着四边形的不稳定而变化,只有当θ=90°时,四边形的面积是最大的,既四边形对角和为180°时。

另外,婆罗摩笈多公式在一条边等于零时,退化为三角形的海伦公式,其中的可变量θ与零相乘消失,海伦公式可以直接给出确定的三角形面积:

所以,三角形具有稳定性,根据三条边就可以计算出面积 。

注:如果知道四个点的坐标就很容易求出 不规则四边形的面积,原理就是 计算两个三角形的面积。

代码如下:

float area_rotation_rect(RotatedRect rect) {Point2f vertices[4]; //定义4个点的数组rect.points(vertices); //将四个点存储到vertices数组中float a = sqrt((vertices[0].x - vertices[1].x)*(vertices[0].x - vertices[1].x) + (vertices[0].y - vertices[1].y)*(vertices[0].y - vertices[1].y));float b = sqrt((vertices[2].x - vertices[1].x)*(vertices[2].x - vertices[1].x) + (vertices[2].y - vertices[1].y)*(vertices[2].y - vertices[1].y));float c = sqrt((vertices[2].x - vertices[3].x)*(vertices[2].x - vertices[3].x) + (vertices[2].y - vertices[3].y)*(vertices[2].y - vertices[3].y));float d = sqrt((vertices[0].x - vertices[3].x)*(vertices[0].x - vertices[3].x) + (vertices[0].y - vertices[3].y)*(vertices[0].y - vertices[3].y));float h = sqrt((vertices[0].x - vertices[2].x)*(vertices[0].x - vertices[2].x) + (vertices[0].y - vertices[2].y)*(vertices[0].y - vertices[2].y));float x1 = (a + b + h) / 2;float x2 = (c + d + h) / 2;float s1 = sqrt(x1 * (x1 - a) * (x1 - b) * (x1 - h));float s2 = sqrt(x2 * (x2 - c) * (x2 - d) * (x2 - h));return s1 + s2;}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。