opencv 最小二乘法拟合曲线
生活随笔
收集整理的這篇文章主要介紹了
opencv 最小二乘法拟合曲线
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//-----------------------------------【頭文件包含部分】---------------------------------------
// 描述:包含程序所依賴的頭文件
//----------------------------------------------------------------------------------------------
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include <iostream>
//-----------------------------------【命名空間聲明部分】--------------------------------------
// 描述:包含程序所使用的命名空間
//-----------------------------------------------------------------------------------------------
using namespace cv;
bool polynomial_curve_fit(std::vector<cv::Point>& key_point, int n, cv::Mat& A)
{
//Number of key points
int N = key_point.size();
//構造矩陣X
cv::Mat X = cv::Mat::zeros(n + 1, n + 1, CV_64FC1);
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < n + 1; j++)
{
for (int k = 0; k < N; k++)
{
X.at<double>(i, j) = X.at<double>(i, j) +
std::pow(key_point[k].x, i + j);
}
}
}
//構造矩陣Y
cv::Mat Y = cv::Mat::zeros(n + 1, 1, CV_64FC1);
for (int i = 0; i < n + 1; i++)
{
for (int k = 0; k < N; k++)
{
Y.at<double>(i, 0) = Y.at<double>(i, 0) +
std::pow(key_point[k].x, i) * key_point[k].y;
}
}
A = cv::Mat::zeros(n + 1, 1, CV_64FC1);
//求解矩陣A
cv::solve(X, Y, A, cv::DECOMP_LU);
return true;
}
int main()
{
//創建用于繪制的深藍色背景圖像
cv::Mat image = cv::Mat::zeros(480, 640, CV_8UC3);
image.setTo(cv::Scalar(0, 0, 100));
//輸入擬合點
std::vector<cv::Point> points;
points.push_back(cv::Point(100., 58.));
points.push_back(cv::Point(150., 70.));
points.push_back(cv::Point(200., 90.));
points.push_back(cv::Point(252., 140.));
points.push_back(cv::Point(300., 220.));
points.push_back(cv::Point(350., 400.));
//將擬合點繪制到空白圖上
for (int i = 0; i < points.size(); i++)
{
cv::circle(image, points[i], 5, cv::Scalar(0, 0, 255), 2, 8, 0);
}
//繪制折線
cv::polylines(image, points, false, cv::Scalar(0, 255, 255), 1, 8, 0);
cv::Mat A;
polynomial_curve_fit(points, 3, A);
std::cout << "A = " << A << std::endl;
std::vector<cv::Point> points_fitted;
for (int x = 0; x < 400; x++)
{
double y = A.at<double>(0, 0) + A.at<double>(1, 0) * x +
A.at<double>(2, 0)*std::pow(x, 2) + A.at<double>(3, 0)*std::pow(x, 3);
points_fitted.push_back(cv::Point(x, y));
}
cv::polylines(image, points_fitted, false, cv::Scalar(255, 255, 255), 1, 8, 0);
cv::imshow("image", image);
cv::waitKey(0);
return 0;
}
總結
以上是生活随笔為你收集整理的opencv 最小二乘法拟合曲线的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html5 audio音频播放全解析
- 下一篇: DBA日常工作内容和职责