opencv曲线拟合c++
时间: 2023-09-09 17:13:02 浏览: 61
以下是使用OpenCV进行曲线拟合的示例代码:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 生成一组随机数据点
vector<Point2f> points;
for (int i = 0; i < 50; i++)
{
float x = i * 0.1;
float y = sin(x) + rand() % 10 / 10.0 - 0.5;
points.push_back(Point2f(x, y));
}
// 利用多项式函数进行拟合
Mat coeffs;
polyfit(points, 3, coeffs);
// 绘制拟合曲线
Mat curve(500, 500, CV_8UC3, Scalar(255, 255, 255));
for (int i = 0; i < curve.cols; i++)
{
float x = i / 50.0;
float y = coeffs.at<float>(0, 0) + coeffs.at<float>(1, 0) * x + coeffs.at<float>(2, 0) * x * x + coeffs.at<float>(3, 0) * x * x * x;
circle(curve, Point2f(x * 50, 250 - y * 50), 1, Scalar(0, 0, 255), -1);
}
// 绘制原始数据点
for (int i = 0; i < points.size(); i++)
{
circle(curve, Point2f(points[i].x * 50, 250 - points[i].y * 50), 3, Scalar(0, 255, 0), -1);
}
imshow("Curve Fitting", curve);
waitKey(0);
return 0;
}
void polyfit(vector<Point2f>& points, int degree, Mat& coeffs)
{
int n = points.size();
Mat A(n, degree + 1, CV_32FC1);
Mat B(n, 1, CV_32FC1);
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= degree; j++)
{
A.at<float>(i, j) = pow(points[i].x, j);
}
B.at<float>(i, 0) = points[i].y;
}
solve(A, B, coeffs, DECOMP_NORMAL);
}
```
该代码生成了50个随机数据点,并使用3次多项式函数进行拟合。拟合结果通过绘制拟合曲线展示出来。可以根据需要修改数据点和拟合函数的次数以适应不同的场景。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)