用贝塞尔曲线拟合函数(纯代码无说明)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_37772174/article/details/88957538

#先上代码,后面附解析

#include <iostream>
#include <fstream>
#include <regex>
#include <string>
using namespace std;

typedef struct Piont2D_
{
	float x;
	float y;
}Point2D;

Point2D PointOnCubicBezier(Point2D* cp, float t)
{
	float   ax, bx, cx;
	float   ay, by, cy;
	float   tSquared, tCubed;
	Point2D result;

	cx = 3.0 * (cp[1].x - cp[0].x);
	bx = 3.0 * (cp[2].x - cp[1].x) - cx;
	ax = cp[3].x - cp[0].x - cx - bx;

	cy = 3.0 * (cp[1].y - cp[0].y);
	by = 3.0 * (cp[2].y - cp[1].y) - cy;
	ay = cp[3].y - cp[0].y - cy - by;

	tSquared = t * t;
	tCubed = tSquared * t;

	result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
	result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
	cout << result.x << " " << result.y << endl;
	return result;
}

void ComputeBezier(Point2D* cp, int numberOfPoints, Point2D* curve)
{
	float  dt;
	int		i;
	dt = 1.0 / (numberOfPoints - 1);
	for (i = 0; i < numberOfPoints; i++)
		curve[i] = PointOnCubicBezier(cp, i*dt);
}

int main()
{
	ifstream datfile;
	smatch result;
	regex pattern("([\\-|\\+]*[\\d+\\.]+[\\d]+),([\\-|\\+]*[\\d+\\.]+[\\d]+),(.*)");

	string str;
	string temp;
	datfile.open("shangyixing.dat");
	const int N = 100;
	Point2D P[N];
	Point2D *p2D = &P[0];
	Point2D curve[N];
	int P_count = 0;
	while (getline(datfile,str)) {
		regex_match(str, result, pattern);
		if (!result.empty()) {
			temp = result.str(1);
			P[P_count].x = atof(temp.c_str());
			temp = result.str(2);
			P[P_count].y = atof(temp.c_str());
			P_count++;
		}
	}
	ComputeBezier(p2D, P_count, curve);
	p2D++;
	//ComputeBezier(p2D, P_count, curve);
	datfile.close();
	return 0;
}


数据

-12.9719,2.8864, 0 
-12.8404,2.9858, 0 
-12.707,3.0828, 0 
-12.5719,3.1773, 0 
-12.4351,3.2693, 0 
-12.2966,3.3587, 0 
-12.1565,3.4455, 0 
-12.0148,3.5298, 0 
-11.8715,3.6114, 0 
-11.7268,3.6903, 0 
-11.5806,3.7666, 0 
-11.433,3.8401, 0 
-11.2841,3.9109, 0 
-11.1339,3.9789, 0 
-10.9825,4.0441, 0 
-10.8299,4.1065, 0 
-10.6762,4.1661, 0 
-10.5214,4.2228, 0 
-10.3656,4.2766, 0 
-10.2088,4.3276, 0 
-10.0511,4.3756, 0 
-9.8925,4.4207, 0 
-9.7331,4.4629, 0 
-9.573,4.5021, 0 
-9.4121,4.5384, 0 
-9.2507,4.5716, 0 
-9.0886,4.6019, 0 
-8.926,4.6291, 0 
-8.7629,4.6534, 0 
-8.5994,4.6746, 0 
-8.4356,4.6928, 0 
-8.2714,4.708, 0 
-8.107,4.7201, 0 
-7.9424,4.7291, 0 
-7.7776,4.7352, 0 
-7.6128,4.7381, 0 
-7.4479,4.738, 0 
-7.2831,4.7349, 0 
-7.1183,4.7287, 0 
-6.9537,4.7195, 0 
-6.7893,4.7072, 0 
-6.6252,4.6919, 0 
-6.4613,4.6735, 0 
-6.2978,4.6522, 0 
-6.1348,4.6278, 0 
-5.9722,4.6003, 0 
-5.8102,4.5699, 0 
-5.6487,4.5365, 0 
-5.4879,4.5001, 0 
-5.3279,4.4607, 0 
-5.1685,4.4184, 0 
-5.01,4.3731, 0 
-4.8523,4.3249, 0 

展开阅读全文

没有更多推荐了,返回首页