#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
/*
* @brief 得到最小二乘法拟合直线的系数矩阵X A*X = B
* param[in] points 单个虚线轮廓内的所有中点
* param[out] 最小二乘法拟合出的直线的系数 直线 y= ax + b,返回结果即为(a,b)
*/
Mat getParameterMatrix(vector<Point2i> points)
{
// 最小二乘拟合
// 构建矩阵A
Mat A = Mat::zeros(2, 2, CV_64FC1);
for (int row = 0; row < A.rows; row++)
{
for (int col = 0; col < A.cols; col++)
{
for (int k = 0; k < points.size(); k++)
{
A.at<double>(row, col) = A.at<double>(row, col) + pow(points[k].x, row + col);
}
}
}
//构建矩阵B
Mat B = Mat::zeros(2, 1, CV_64FC1);
for (int row = 0; row < B.rows; row++)
{
for (int k = 0; k < points.size(); k++)
{
B.at<double>(row, 0) = B.at<double>(row, 0) + pow(points[k].x, row) * points[k].y;
}
}
// A*X = B, 其中X为要求解的系数矩阵
Mat X;
solve(A, B, X, DECOMP_LU);
return X;
}