Python:将曲线拟合到整数列表

Zac*_*Zac 3 python numpy pixel matplotlib

我有一个整数列表。

intList = [96, 98, 120, 163, 158, 166, 201, 201, 159, 98, 93, 73, 77, 72]
Run Code Online (Sandbox Code Playgroud)

这些数字代表 14 个像素条带的灰度值,我想将曲线拟合到分布并保存顶点的 x 位置。

为了上下文:我实际上正在使用一个(更大的)列表列表,每个列表包含图像中一行像素的灰度值。对于每一行像素,我想绘制一条数据曲线,并将顶点的 x 位置附加到不断增长的列表中。每行像素都会有一些噪声,但只有一个宽阔、清晰的像素强度峰值(下面的示例图像)

我从中提取数据的图像

我有 NumPy、SciPy、matplotlib 和枕头,但我不太了解每个函数中的许多函数。有人可以向我指出一个可以做到这一点的模块或函数吗?

mcw*_*itt 5

要拟合多项式,例如二次项,请使用polyfit

from pylab import *

x = arange(len(intList))
p = polyfit(x, intList, 2)
a, b, c = p
x0 = -0.5*b/a # x coordinate of vertex

# plot
x = arange(len(intList))
plot(x, intList)
plot(x, polyval(p, x))
axvline(x0, color='r', ls='--')
Run Code Online (Sandbox Code Playgroud)

二次拟合

要拟合更复杂的函数,例如高斯函数,您可以使用curve_fit

from scipy.optimize import curve_fit

# define function to fit
ffunc = lambda x, a, x0, s: a*exp(-0.5*(x-x0)**2/s**2)

# fit with initial guess a=100, x0=5, s=2
p, _ = curve_fit(ffunc, x, intList, p0=[100,5,2])

x0 = p[1] # location of the mean

# plot
plot(x, intList)
plot(x, ffunc(x, *p))
axvline(x0, color='r', ls='--')
Run Code Online (Sandbox Code Playgroud)

高斯拟合

(尽管为了拟合高斯分布,您最好直接计算分布的均值和方差。)