In [1]:
%matplotlib inline
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.patches import Circle
from matplotlib.patches import Ellipse
from skimage.filters import threshold_otsu
from skimage.filters import sobel
import lmfit
from lmfit import Model
from tifffile import TiffFile
In [ ]:
def plot(image, params=None):
fig, ax = plt.subplots()
im_ax = ax.imshow(image, cmap=plt.cm.BrBG, interpolation='nearest', origin='lower')
if params:
ax.scatter(params['x0'], params['y0'], s=100, c="red", marker="x")
circle = Circle((params['x0'], params['y0']), params['sigma'], facecolor='none',
edgecolor="red", linewidth=1, alpha=0.8)
ax.add_patch(circle)
plt.colorbar(im_ax)
# 2D Gaussian model
def func(xy, x0, y0, sigma, H):
x, y = xy
A = 1 / (2 * sigma**2)
I = H * np.exp(-A * ( (x - x0)**2 + (y - y0)**2))
return I
In [95]:
# Generate model
true_params = {'x0': 5, 'y0': 5, 'sigma': 3, 'H': 200}
x = np.arange(0, 50, 1)
y = np.arange(0, 50, 1)
xy = np.meshgrid(x, y)
model = Model(func)
image = model.eval(xy=xy, **true_params)
image += np.random.poisson(5, image.shape)
plot(image, true_params)
In [96]:
# Fit generated model
# Guess initials parameters
model.set_param_hint('x0', value=25, min=0, max=300)
model.set_param_hint('y0', value=25, min=0, max=300)
model.set_param_hint('sigma', value=25, min=0, max=100)
## Guessing height (H) value
background = image[image < threshold_otsu(image)].mean()
h_guess = image.max() - background
print("H guess : {}".format(h_guess))
model.set_param_hint('H', value=h_guess, min=background, max=image.max() * 10)
# Prepare fit
x = np.arange(0, image.shape[1], 1)
y = np.arange(0, image.shape[0], 1)
xy = np.meshgrid(x, y)
# Fit
result = model.fit(image, xy=xy, method='leastsq')
# Plot result
predicted_params = result.params
plot(image, predicted_params)
plot(result.init_fit)
plot(result.best_fit)
print(result.fit_report())
#lmfit.printfuncs.report_ci(result.conf_interval())
In [97]:
image = TiffFile("spot.tif").asarray()
# Rescaling image to get 0 for the lowest value
image -= image.min()
plot(image)
In [98]:
# Fit generated model
model = Model(func)
# Guess initials parameters
model.set_param_hint('x0', value=15, min=0, max=300)
model.set_param_hint('y0', value=15, min=0, max=300)
model.set_param_hint('sigma', value=25, min=0, max=300)
## Guessing height (H) value
background = image[image < threshold_otsu(image)].mean()
h_guess = image.max() - background
print("H guess : {}".format(h_guess))
model.set_param_hint('H', value=h_guess, min=background, max=image.max() * 10)
# Prepare fit
x = np.arange(0, image.shape[1], 1)
y = np.arange(0, image.shape[0], 1)
xy = np.meshgrid(x, y)
# Fit
result = model.fit(image, xy=xy, verbose=False)
# Plot result
predicted_params = result.params
plot(image, predicted_params)
plot(result.init_fit)
plot(result.best_fit)
print(result.fit_report())
In [ ]: