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

我有一个整数列表.

intList = [96, 98, 120, 163, 158, 166, 201, 201, 159, 98, 93, 73, 77, 72]

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

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

我有NumPy,SciPy,matplotlib和pillow,但是我对每个函数中发现的许多功能不是很了解.有人能指出我可能会这样做的模块或功能吗?

解决方法:

拟合多项式,例如二次方,使用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='--')

为了适合更复杂的功能,例如高斯,可以使用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='--')

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

上一篇:Java-Android 2.1本机锁定位图像素


下一篇:opencv:遍历访问像素