c++ 多項式擬合 本文部分轉載


#include <opencv2\opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;

Mat polyfit(vector<Point>& in_point, int n);

int main()

{

	Point in[26] = { Point(1, 22), Point(10, 129), Point(20, 412), Point(30, 724), Point(40, 1294)
		, Point(50, 1838), Point(60, 1672), Point(70, 1090), Point(80, 720), Point(90, 525)
		, Point(100, 4278), Point(110, 3535), Point(120, 3120), Point(130, 2711), Point(140, 2482)
		, Point(150, 241), Point(160, 231), Point(170, 214), Point(180, 203), Point(190, 203)
		, Point(200, 195), Point(210, 199), Point(220, 223), Point(230, 339), Point(240, 784), Point(250, 2478) };

	vector<Point> in_point(begin(in), end(in));

	//n:多項式階次
	int n =4;
	Mat mat_k = polyfit(in_point1, n);

	//計算結果可視化
	Mat out(500, 500, CV_8UC3, Scalar::all(0));

	//畫出擬合曲線
	for (int i = in[0].x; i < in[26 - 1].x; ++i)
	{
		Point2d ipt;
		ipt.x = i;
		ipt.y = 0;
		for (int j = 0; j < n + 1; ++j)
		{
			ipt.y += mat_k.at<double>(j, 0)*pow(i, j);
		}
		circle(out, ipt, 1, Scalar(255, 255, 255), CV_FILLED, CV_AA);

	}

	//畫出原始散點
	for (int i = 0; i < 26; ++i)
	{
		Point ipt = in1[i];
		Point in1[26];
		in1[i].y = in[i].y*0.00463;
		circle(out, ipt, 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);
	}
	imshow("9次擬合", out);
	waitKey(0);
	return 0;

}

Mat polyfit(vector<Point>& in_point, int n)
{
	int size = in_point.size();
	//所求未知數個數
	int x_num = n + 1;
	//構造矩陣U和Y
	Mat mat_u(size, x_num, CV_64F);
	Mat mat_y(size, 1, CV_64F);

	for (int i = 0; i < mat_u.rows; ++i)

		for (int j = 0; j < mat_u.cols; ++j)

		{

			mat_u.at<double>(i, j) = pow(in_point[i].x, j);

		}



	for (int i = 0; i < mat_y.rows; ++i)

	{

		mat_y.at<double>(i, 0) = in_point[i].y;

	}



	//矩陣運算,獲得係數矩陣K

	Mat mat_k(x_num, 1, CV_64F);

	mat_k = (mat_u.t()*mat_u).inv()*mat_u.t()*mat_y;

	cout << mat_k << endl;

	return mat_k;

}

        int hahaType = mat_k.type();//顯示矩陣 mat_k的數據類型  
        cout << hahaType << endl;

        cout << mat_k.cols << endl;  //1
        cout << mat_k.rows << endl;  //6   多項式係數矩陣的行列數

將係數矩陣 mat_k的值提取出來並保存到係數結構體中  五次多項式即五個係數

struct xishu//係數
{
    double A1;
    double A2;
    double A3;
    double A4;
    double A5;
};

		xishu A;
		for (int r = 0; r < mat_k.rows; r++)
		{
			for (int c = 0; c < mat_k.cols; c++)
			{
				cout << "r: " << r << " c: " << c << endl;
				cout << mat_k.at<double>(r, c) << ","; //多項式係數矩陣的值讀取出來
				//A.A1 = mat_k.at<double>(r, c);

			}
			cout << endl;
		}

		A.A1 = mat_k.at<double>(1, 0);
		A.A2 = mat_k.at<double>(2, 0);
		A.A3 = mat_k.at<double>(3, 0);
		A.A4 = mat_k.at<double>(4, 0);
		A.A5 = mat_k.at<double>(5, 0);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章