在python中,将2D高斯函数的和与2D数据相匹配?

2024-10-06 12:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些二维数据,特别是扫描的X光片。这些都有重叠点源暴露的测量。数据示例:http://i.stack.imgur.com/oawlU.png

我想通过拟合二维高斯函数和数据来找出峰值位置。我尝试过其他几种方法,也取得了一些成功,包括一种“星搜索”方法,它可以定位全局最大值,拟合高斯函数并减去它。循环这会发现所有的峰值都相当好,但它不稳定,也不太准确。我想使用star search输出作为匹配的第一个猜测,但是在实现scipy.optimize.curve_fit时遇到了麻烦。在

我做了一个函数twoD_envelope,它创建了从恒星搜索中找到的所有高斯人的二维包络。这将产生以下输出:http://i.stack.imgur.com/4KnpG.png

我的印象是我可以用它作为curve_fit的初始猜测,但是我得到了以下TypeError

^{1}$

358802比数据的大小多1个,这是一个巨大的线索,但我不知道是什么问题!我是一个物理学家,有“实用”的编码知识,所以任何输入都是非常感谢的。在

代码如下。在

^{pr2}$

sq_image是数据,是形状为(599,599)ndarray

pars, xls, yxl=star search的高斯拟合参数列表)

makeGaussian是在别处定义的函数)


Tags: 数据方法函数comhttp示例searchpng
1条回答
网友
1楼 · 发布于 2024-10-06 12:36:27

你认为这是一个错误的结果。这可能会导致data数组被解释为vars,这将导致您看到的{}(如果不能运行代码,很难判断)。根据文件,传递给曲线拟合的函数应

take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

您可能还需要在初始猜测之前使用一个星来将其作为元组传递,例如

pars_opt, pars_cov = opt.curve_fit(twoD_envelope, coords, data, p0=*initial_guess)

{1,可能有一个很好的高斯参数。在

一个可能解决你的问题可能是循环通过你的二维sq_图像,并使用一个单一的二维高斯拟合与每个初始参数从恒星搜索。。。在

编辑:代码适合高斯。在

import scipy.optimize as opt
import numpy as np
import pylab as plt
import matplotlib.cm as cm
import Image


def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta):
    xo = float(xo)
    yo = float(yo)    
    a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
    b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
    c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
    g = amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) 
                            + c*((y-yo)**2)))
    return g.ravel()


# Create x and y indices
I = Image.open('./30155885.png')
p = np.asarray(I).astype('float')
w,h = I.size
x, y = np.mgrid[0:h, 0:w]

#Use only one channel of image
p = p[:,:,0]

#Fit 2D Gaussian
initial_guess = (3,10,10,20,40,0)
popt, pcov = opt.curve_fit(twoD_Gaussian, (x, y), p.ravel(), p0=initial_guess)
data_fitted = twoD_Gaussian((x, y), *popt)


fig, ax = plt.subplots(1, 1)
cb = ax.imshow(p, cmap=plt.cm.jet, origin='bottom',
    extent=(x.min(), x.max(), y.min(), y.max()))
ax.contour(x, y, data_fitted.reshape(x.shape[0], y.shape[1]), 8, colors='w')


plt.colorbar(cb)
plt.show()

在图像30155885所在的位置

请注意,只使用了图像数据的一个通道(您应该将数据数组替换为sq_image中的一个)。结果是

enter image description here

相关问题 更多 >