1 //叉乘算三角形面積(有正負),以及算三角形質心坐标
2 void TriangleCentroid(Vec2d P1, Vec2d P2, Vec2d P3, double& area,Vec2d& centroid)
3 {
4 Vec2d P12 = P2 - P1;
5 Vec2d P13 = P3 - P1;
6
7 double x1 = P12.x();
8 double y1 = P12.y();
9
10 double x2 = P13.x();
11 double y2 = P13.y();
12
13
14 //向量叉乘計算三角形面積
15 area = (x1*y2 - x2*y1)/2;
16
17 //計算三角形質心
18 centroid.x = (p1.x + p2.x + p3.x) / 3;
19 centroid.y = (p1.y + p2.y + p3.y) / 3;
20
21 return;
22 }
23
24 //計算質心坐标,多邊形的頂點按順序排列在數組中
25 bool PolygonCentroid(std::vector<Vec2d> Points, Vec2d& centroid)
26 {
27 int count = Points.size();
28
29 //如果不是多邊形,不計算
30 if (count < 3)
31 return false;
32
33 //多邊形總面積
34 double totalArea = 0;
35
36 //n邊形劃分成n-2個三角形,每個三角形質心坐标與該三角形面積乘積之和
37 Vec2d totalTriangleCentroid(0,0);
38
39 //按頂點順序,1,2,3;1,3,4;1,4,5;如此建構三角形
40 for (int i = 1; i < count - 1; i++)
41 {
42 double temp;
43 Vec2d tempCentroid;
44
45 //計算每個三角形的面積與質心坐标
46 TriangleCentroid(Points[0], Points[i], Points[i + 1], temp,tempCentroid);
47
48 totalTriangleCentroid.x += tempCentroid.x * temp;
49 totalTriangleCentroid.y += tempCentroid.y * temp;
50
51 totalArea += temp;
52 }
53
54
55 //計算質心坐标
56 centroid.x = totalTriangleCentroid.x / temp;
57 centroid.y = totalTriangleCentroid.y / temp;
58
59 return true;;
60 }
二維與三維,多元是一樣的情況;
三角形的質心(A+B+C)/3,采用向量計算(三角形面積有正負);
多邊形質心 = ( (對應三角形質心_X)*對應的子三角面積/總面積 , (對應三角形質心_Y)*對應的子三角面積/總面積 )