赞
踩
下面代码拟合函数为二次函数,自己可根据需要自己定义要拟合的函数
- import numpy as np
-
- import matplotlib
- matplotlib.use('TkAgg')
- import matplotlib.pyplot as plt
- from scipy.optimize import curve_fit
-
- # 读取图片并手动选择曲线上的数据点
- img = plt.imread('2.jpg')
- plt.imshow(img)
-
- points = plt.ginput(n=-1,timeout=0)
- print(points)
-
- # 将数据点转换为numpy数组
- xdata, ydata = zip(*points)# 与 zip 相反,可理解为解压,为zip的逆过程,可用于矩阵的转置
- xdata = np.array(xdata)
- ydata = np.array(ydata)
-
- # 定义要拟合的二次函数
- def quadratic_function(x, a, b, c):
- return a*x**2 + b*x + c
-
- # 执行曲线拟合
- popt, _ = curve_fit(quadratic_function, xdata, ydata)
-
- # 打印拟合函数的系数
- print("拟合函数的系数:a=%f, b=%f, c=%f" % tuple(popt))
- print("拟合函数:y={%f}x**2 + {%f}*x+ {%f}" % tuple(popt))

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。