我的图片:
我正在尝试检测图像中的曲线 – 图中显示的是堆叠的硬币。我想计算这些平行曲线的数量。大多数线条是不连续的。
假设我使用5个点和numpy.polyfit来获取描述线条的函数。
有什么最好的方法来搜索这些线条,并指出这些点在第一条线上,那些点在第二条线上等等?
我在考虑尝试最小二乘法,并上下移动线条。我认为曲线可以看作是抛物线(ax^2 + bx + c) – 移动它意味着移动顶点x=-b/2a => y=a*(-b/2a)^2 + b*(-b/2a)+c 。
import numpy as npdata = np.array([[0,0], [1,-1], [2, -2], [3,-1], [4,0]])data_x = [k[0] for k in data ]data_y = [k[1] for k in data ]p = np.poly1d(np.polyfit(data_x, data_y, 2))
请问有人能帮我举个例子,如何将图像中的点拟合到我刚找到的p上?我在这里如何应用最小二乘法?
提前感谢!
回答:
经过多日在网上阅读和研究,我找到了一个非常优雅的解决方案,使用了lmfit。 https://lmfit.github.io/lmfit-py/ 我感谢这个模块的创建者们,他们做得非常出色。
现在是将数据拟合到曲线上的解决方案。当我们有一个多项式p时
>>> p
poly1d([ 0.42857143, -1.71428571, 0.05714286])
创建一个包含这些参数的Python函数
def fu(x,a=0.4285,b=-1.71,c=0.057): return x*x*a + x * b + c
现在我们可以使用该函数创建一个lmfit模型
>>> gmodel = Model(fu)>>> gmodel.param_names['a', 'c', 'b']>>> gmodel.independent_vars['x']
你可以看到它识别了独立变量和参数。它会尝试改变参数,使函数最佳拟合数据。
>>> result = gmodel.fit(y_test, x=x_test)>>> print(result.fit_report())[[Model]] Model(fu)[[Fit Statistics]] # function evals = 11 # data points = 8 # variables = 3 chi-square = 2.159 reduced chi-square = 0.432 Akaike info crit = -4.479 Bayesian info crit = -4.241[[Variables]] a: 0.12619047 +/- 0.050695 (40.17%) (init= 0.4285) c: -0.55833335 +/- 0.553020 (99.05%) (init= 0.057) b: -0.52857141 +/- 0.369067 (69.82%) (init=-1.71)[[Correlations]] (unreported correlations are < 0.100) C(a, b) = -0.962 C(c, b) = -0.793 C(a, c) = 0.642
完整的Python脚本:
import matplotlib.pyplot as pltfrom lmfit import Modelimport numpy as npdef fu(x,a=0.4285,b=-1.71,c=0.057): return x*x*a + x * b + cgmodel = Model(fu)print "Params" , gmodel.param_namesprint "Independent var", gmodel.independent_varsparams = gmodel.make_params()print " Params prop", paramsdata_test = np.array([[0,0], [1,-1.2], [2, -2], [3,-1.3], [4,0], [5,0.5], [6,0.9], [7, 1.5]])x_test = data_test[:,0]y_test = data_test[:,1]result = gmodel.fit(y_test, x=x_test)print(result.fit_report())plt.plot(x_test, y_test, 'bo')plt.plot(x_test, result.init_fit, 'k--')plt.plot(x_test, result.best_fit, 'r-')plt.show()