我正在尝试将2D高斯拟合到图像中以找到其中最亮点的位置。我的代码如下所示:
import numpy as np
import astropy.io.fits as fits
import os
from astropy.stats import mad_std
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from lmfit.models import GaussianModel
from astropy.modeling import models, fitting
def gaussian(xycoor,x0, y0, sigma, amp):
'''This Function is the Gaussian Function'''
x, y = xycoor # x and y taken from fit function. Stars at 0, increases by 1, goes to length of axis
A = 1 / (2*sigma**2)
eq = amp*np.exp(-A*((x-x0)**2 + (y-y0)**2)) #Gaussian
return eq
def fit(image):
med = np.median(image)
image = image-med
image = image[0,0,:,:]
max_index = np.where(image >= np.max(image))
x0 = max_index[1] #Middle of X axis
y0 = max_index[0] #Middle of Y axis
x = np.arange(0, image.shape[1], 1) #Stars at 0, increases by 1, goes to length of axis
y = np.arange(0, image.shape[0], 1) #Stars at 0, increases by 1, goes to length of axis
xx, yy = np.meshgrid(x, y) #creates a grid to plot the function over
sigma = np.std(image) #The standard dev given in the Gaussian
amp = np.max(image) #amplitude
guess = [x0, y0, sigma, amp] #The initial guess for the gaussian fitting
low = [0,0,0,0] #start of data array
#Upper Bounds x0: length of x axis, y0: length of y axis, st dev: max value in image, amplitude: 2x the max value
upper = [image.shape[0], image.shape[1], np.max(image), np.max(image)*2]
bounds = [low, upper]
params, pcov = curve_fit(gaussian, (xx.ravel(), yy.ravel()), image.ravel(),p0 = guess, bounds = bounds) #optimal fit. Not sure what pcov is.
return params
def plotting(image, params):
fig, ax = plt.subplots()
ax.imshow(image)
ax.scatter(params[0], params[1],s = 10, c = 'red', marker = 'x')
circle = Circle((params[0], params[1]), params[2], facecolor = 'none', edgecolor = 'red', linewidth = 1)
ax.add_patch(circle)
plt.show()
data = fits.getdata('AzTECC100.fits') #read in file
med = np.median(data)
data = data - med
data = data[0,0,:,:]
parameters = fit(data)
#generates a gaussian based on the parameters given
plotting(data, parameters)
图像是绘图,代码没有错误,但是拟合不起作用。它只是在x
和x0
的任何地方放置y0
。我图像中的像素值非常小。最大值为0.0007,std dev为0.0001,x
和y
大几个数量级。所以我相信我的问题是,因为这个我的eq到处都是零,所以curve_fit
失败了。我想知道是否有更好的方法来构建我的高斯,以便正确绘制?
答案 0 :(得分:0)
我无法访问您的图片。相反,我已经生成了一些测试"图像"如下:
y, x = np.indices((51,51))
x -= 25
y -= 25
data = 3 * np.exp(-0.7 * ((x+2)**2 + (y-1)**2))
此外,我修改了您的绘图代码,以便将圆的半径增加10:
circle = Circle((params[0], params[1]), 10 * params[2], ...)
我又注释了两行:
# image = image[0,0,:,:]
# data = data[0,0,:,:]
我得到的结果显示在附图中,对我来说看起来很合理:
问题在于您如何从FITS
文件访问数据? (例如,image = image[0,0,:,:]
)数据是4D数组吗?为什么你有4个指数?
我还看到您在此处提出了类似的问题:Astropy.model 2DGaussian issue您尝试仅使用astropy.modeling
。我会研究这个问题。
注意:您可以替换
等代码max_index = np.where(image >= np.max(image))
x0 = max_index[1] #Middle of X axis
y0 = max_index[0] #Middle of Y axis
与
y0, x0 = np.unravel_index(np.argmax(data), data.shape)