intmain(int argc, char **argv){ double ar = 1.0, br = 2.0, cr = 1.0; // 真实参数值 double ae = 2.0, be = -1.0, ce = 5.0; // 估计参数值 int N = 100; // 数据点 double w_sigma = 1.0; // 噪声Sigma值 double inv_sigma = 1.0 / w_sigma; cv::RNG rng; // OpenCV随机数产生器
vector<double> x_data, y_data; // 已知数据存储 for (int i = 0; i < N; i++) { double x = i / 100.0; x_data.push_back(x); y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma)); }
double abc[3] = {ae, be, ce}; // 初始化待估计参数
// 2. 构建最小二乘问题 ceres::Problem problem; // 向问题中添加误差项。1. 使用自动求导,模板参数:残差类型,输出维度,输入维度,维数要与前面struct中一致 for (int i = 0; i < N; i++) { problem.AddResidualBlock( new ceres::AutoDiffCostFunction<CURVE_FITTING_COST, 1, 3>(newCURVE_FITTING_COST(x_data[i], y_data[i])), nullptr, // 2. 核函数,这里不使用,为空 abc // 3. 待估计参数 ); }