拟合贝塞尔曲线c++代码
时间: 2023-11-03 17:07:11 浏览: 212
c++曲线拟合
4星 · 用户满意度95%
以下是一份C++版本的拟合贝塞尔曲线代码,可以实现二次和三次bezier曲线的绘制,具体实现方法和参数可以参考代码注释:
```
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// 定义点的结构体
struct Point {
double x;
double y;
};
// 计算组合数C(n, i)
double Combination(int n, int i) {
double res = 1;
for (int j = 1; j <= i; j++) {
res *= (n - j + 1) / (double)j;
}
return res;
}
// 计算贝塞尔曲线上某一点的坐标
Point Bezier(vector<Point>& points, double t) {
int n = points.size() - 1;
double x = 0, y = 0;
for (int i = 0; i <= n; i++) {
double factor = Combination(n, i) * pow(t, i) * pow(1 - t, n - i);
x += factor * points[i].x;
y += factor * points[i].y;
}
return { x, y };
}
// 拟合二次贝塞尔曲线
vector<Point> FitQuadraticBezier(vector<Point>& points) {
vector<Point> res;
if (points.size() < 3) {
return res;
}
for (double t = 0; t <= 1; t += 0.01) {
Point p = Bezier(points, t);
res.push_back(p);
}
return res;
}
// 拟合三次贝塞尔曲线
vector<Point> FitCubicBezier(vector<Point>& points) {
vector<Point> res;
if (points.size() < 4) {
return res;
}
for (double t = 0; t <= 1; t += 0.01) {
Point p = Bezier(points, t);
res.push_back(p);
}
return res;
}
int main() {
// 示例:二阶贝塞尔曲线points = {{10,10}, {20, 80},{40,120}}
vector<Point> points = { {10,10}, {20, 80},{40,120} };
vector<Point> res = FitQuadraticBezier(points);
for (auto p : res) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
return 0;
}
```
阅读全文