Ok, here is a version of the script that works. I put comments and explanations in the script itself:
from math import sqrt
from ij import IJ, ImagePlus,WindowManager
from net.imglib2 import Point as Pt
from net.imglib2.util import Util
from net.imglib2.algorithm.localization import PeakFitter, Gaussian, LevenbergMarquardtSolver, LocalizationUtils, MLGaussianEstimator, Observation
from net.imglib2.img import ImagePlusAdapter
from jarray import zeros,array
def fit2DGaussian( img, peaks ) :
# The core class is PeakFitter.
# It needs to know what solver to use (here LM), what function to fit (here,
# a plain symmetric Gaussian), and an estimator that can generate
# some estimates of the fit parameters as initial values for the fit (here, the
# MLGaussianEstimator, configured with a typical sigma of 2 and on 2D).
fitter = PeakFitter( img, peaks, LevenbergMarquardtSolver(), Gaussian(), MLGaussianEstimator( 2., 2 ) )
print( fitter.toString() )
if not fitter.checkInput() or not fitter.process():
print( 'Error with the peak fitter: %s.' % fitter.getErrorMessage() )
imp = WindowManager.getCurrentImage()
# Wrap into an ImgLib2 image.
img = ImagePlusAdapter.wrap( imp )
# You need to provide the initial guess of the position of peaks.
# It is a list of 'Localizable', for instance 'Point's.
center = array([imp.width / 2, imp.height / 2], 'l')
cpoint = Pt(center)
peaks = [ cpoint ] # Here we have just one point.
# This list can be provided automatically, e.g. by a LoG detector.
# Fit by a symmetric 2D Gaussian.
results = fit2DGaussian( img, peaks )
# The results are returned as a dictionary of the peak objects as
# keys, and with the fit output as values.
# In our case we fit A × exp( -b × ∑ (xᵢ - x₀ᵢ)² ) and the fit output
# is a 4-double array made of x, y, A and b.
for peak in results:
print( '\nFound a peak around %s. Fit results:' % Util.printCoordinates( peak ) )
params = results[ peak ]
print( ' - X position: %9.3f' % params )
print( ' - Y position: %9.3f' % params )
print( ' - Amplitude: %9.3f' % params )
print( ' - Sigma: %9.3f' % ( 1. / sqrt(2. * params) ) )
When I run it on the image you sent:
Gauss.tif (9.6 KB)
I get the following output:
Started Gauss_.py at Thu Mar 26 23:27:53 CET 2020
PeakFitter configured to:
- fit a Gaussian function A × exp( -b × ∑ (xᵢ - x₀ᵢ)² )
- on 1 peaks
- in image FloatImagePlus [49x49]
- using Maximum-likelihood estimator for symetric gaussian peaks
- and Levenberg-Marquardt least-square curve fitting algorithm
- allocating 8 threads.
Found a peak around (24.0, 24.0). Fit results:
- X position: 24.992
- Y position: 25.004
- Amplitude: 0.195
- Sigma: 2.804
Tell me if this is what you need.