对点云数据求凸包的最小外接矩形的c++代码
时间: 2023-10-19 15:06:01 浏览: 227
以下是对点云数据求凸包的最小外接矩形的C++代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
// 定义点结构体
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
};
// 定义向量结构体
struct Vector {
double x, y;
Vector() {}
Vector(double x, double y) : x(x), y(y) {}
Vector(Point A, Point B) : x(B.x - A.x), y(B.y - A.y) {}
double length() { return hypot(x, y); } // 计算向量长度
};
// 两个点是否相等
bool operator==(const Point& A, const Point& B) {
return A.x == B.x && A.y == B.y;
}
// 向量点乘
double operator*(const Vector& A, const Vector& B) {
return A.x * B.x + A.y * B.y;
}
// 向量叉乘
double operator^(const Vector& A, const Vector& B) {
return A.x * B.y - A.y * B.x;
}
// 求点集的凸包
vector<Point> convexHull(vector<Point> points) {
int n = points.size();
if (n < 3) return points;
sort(points.begin(), points.end(), [](const Point& A, const Point& B) {
return A.x < B.x || (A.x == B.x && A.y < B.y);
});
vector<Point> ch;
for (int i = 0; i < n; i++) {
while (ch.size() >= 2 && ((ch[ch.size() - 1] - ch[ch.size() - 2]) ^ (points[i] - ch[ch.size() - 2])) <= 0) {
ch.pop_back();
}
ch.push_back(points[i]);
}
int k = ch.size();
for (int i = n - 2; i >= 0; i--) {
while (ch.size() >= k + 1 && ((ch[ch.size() - 1] - ch[ch.size() - 2]) ^ (points[i] - ch[ch.size() - 2])) <= 0) {
ch.pop_back();
}
ch.push_back(points[i]);
}
if (ch.size() > 1) ch.pop_back();
return ch;
}
// 求点集的最小外接矩形
double minBoundingRect(vector<Point> points) {
vector<Point> ch = convexHull(points);
int n = ch.size();
if (n < 3) return 0;
double ans = 1e18;
for (int i = 0, j = 2; i < n; i++) {
Vector v1(ch[i], ch[(i + 1) % n]), v2;
while ((v2 = Vector(ch[i], ch[(j + 1) % n])) ^ v1 >= 0) j = (j + 1) % n;
double len1 = v1.length(), len2 = v2.length();
ans = min(ans, len1 * len2 * abs(v1 * v2) / 2 / abs(v1 ^ v2));
}
return ans;
}
int main() {
// 输入点云数据
vector<Point> points = {{-1, 0}, {0, 2}, {2, 1}, {1, -1}};
// 求点集的最小外接矩形
double rect = minBoundingRect(points);
cout << "Minimum bounding rectangle: " << rect << endl;
return 0;
}
```
注意:上述代码中的 `minBoundingRect` 函数需要先求出点集的凸包,然后枚举凸包上的每条边,计算以该边为对角线的矩形面积,并取所有面积的最小值。
阅读全文