Shading correction (optix.shading)
Estimators of the flat field, dark field and per-frame baseline, and the correction that applies them.
Estimators
Shading correction: flat field, dark field and per-frame baseline.
Building blocks of these estimators are in optix.shading.utils.
BaSiC
BaSiC(*, working_size=None, darkfield=None, timelapse=None, lambda_flat=None, lambda_dark=None, epsilon=None, tol=None, max_iterations=None, max_reweight=None, reweight_tol=None, mu_coef=None, rho=None, max_mu_coef=None, max_frames=None, sampling=None, seed=None, variant=None, normalize_weights=None, baseline_method=None, sort_intensity=None, baseline_norm=None, faithful=True, dtype=None, device=None, layout=None)
Bases: Estimator
BaSiC: shading and baseline by low-rank + sparse decomposition.
Image formation for frame i of a group (one flat and dark field per group, shared by its samples):
yₙ = f ⊙ (xₙ + bₙ) + d
with a smooth flat field f (mean 1), a smooth dark field d, a spatially constant baseline bₙ (time-lapse data) and the latent image xₙ. The corrected frame is
x̂ₙ = (yₙ − d) / f − bₙ + b_{norm}
where b_{norm} is an arbitrary background: 0 removes the background (fluorescence), meanₙ bₙ keeps the raw intensity range (bright field). (Peng et al. 2017: I = y, S = f, D = d, Bᵢ = bₙ, F = x, I_B = L, I_R = E.)
Flat and dark field. The fitting frames, sorted at each pixel over the frames and resized to the working size (128 × 128), form the measurement matrix Y (one column per sorted frame). BaSiC decomposes it into a low-rank part L = f bᵀ + z, with z = d_Z (1 − f) + d_R, and a sparse residual E:
min ‖W ⊙ E‖₁ + λ_f ‖𝓕(f)‖₁ + λ_d ‖𝓕(d_R)‖₁ + λ_d ‖d_R‖₁
s.t. Y = L + E, d_Z ∈ [0, min Y]
with 𝓕 the orthonormal 2-D DCT. The problem is solved by the linearised augmented Lagrangian method (LADM), with reweighted-L1 weights W = 1 / (|E / L| + ε), scaled to mean 1. The default regularisation is λ_f = ‖𝓕(ȳ)‖₁ / 800 and λ_d = ‖𝓕(ȳ)‖₁ / 2000, with ȳ the per-pixel mean frame divided by its mean. The fields are resized back (bilinear) to the image size; d = d_Z + d_R.
Baseline (timelapse=True). After sorting, the fitted bₙ belong
to the sorted frames, so bₙ is estimated in a second step on every
unsorted frame (at the working size) with f and d fixed:
min_b ‖W ⊙ (yₙ − bₙ f − d)‖₁, reweighted as above.
Note
The fit reads the max_frames fitting frames of each group (a
representative subset, as suggested by the authors for long
sequences), plus one pass over the stack with timelapse=True.
apply works on frame batches. Sorting needs
all the fitting frames of a strip of rows at once: the strips are
sized to the memory budget, and each fitting frame is read once per
strip.
Implementation choices
The inner LADM loop stops when ‖Y − L − E‖_F / ‖Y‖_F < tol
or after max_iterations. The penalty starts at μ₀ = 12.5 / ‖Y‖₂
and grows by ρ = 1.5, capped at 10⁷ μ₀ to stay finite. Images are
resized by bilinear interpolation with anti-aliasing, after
sorting. The baseline step solves each reweighted problem exactly
(weighted median).
Interpretations of the paper
- 𝓕 is the orthonormal 2-D DCT: the "Fourier transform" of the Supplementary Information refers to the DCT of the authors' implementation.
- The weights of Eq. (9) are scaled to mean 1, which the λ of
Supplementary Note 4 are taken to assume
(
normalize_weights=Falseuses Eq. (9) as printed). - The regions "S ≥ 1" and "S < 1" of the dark-field update are read as f ≥ mean(f) and f < mean(f), f being unnormalised there.
- The frames are sorted at full resolution and then resized to the working size.
References
- Peng T, Thorn K, Schroeder T, Wang L, Theis FJ, Marr C, Navab N. A BaSiC tool for background and shading correction of optical microscopy images. Nat Commun 8:14836, 2017. doi:10.1038/ncomms14836
BibTeX
@article{peng2017basic,
author = {Peng, Tingying and Thorn, Kurt and Schroeder, Timm
and Wang, Lichao and Theis, Fabian J. and Marr,
Carsten and Navab, Nassir},
title = {A {BaSiC} tool for background and shading
correction of optical microscopy images},
journal = {Nature Communications},
volume = {8},
pages = {14836},
year = {2017},
doi = {10.1038/ncomms14836},
}
Extensions (off by default)
sort_intensity=False: fit the unsorted frames;fit_baseline_then holds the fitted baselines.variant="basicpy": the solver of BaSiCPy 2.0.0 (fitting_mode="approximate"): weights divided by the frame mean of L and normalised to mean 1, bₙ clipped at 0, f started at 1, the dark field fitted on the frames with bₙ < 1 with a 10× smaller threshold, and λ_d = λ_f / 10 by default. Withsort_intensity=Falseandreweight_tol=1e-2it reproduces BaSiCPy.baseline_method="basicpy": BaSiCPy'sfit_only_baseline, a reweighted-L1 ALM trusting only the pixels below each frame's 10 % quantile, run per batch. It is biased low where the flat field varies (about −11 % with a flat of ±25 %).sampling="reservoir": random fitting frames.normalize_weights=False: the weights of Eq. (9) without scaling.
Attributes:
| Name | Type | Description |
|---|---|---|
estimates |
dict
|
|
fit_frames_ |
(k,) Tensor
|
Flat sample indices (storage order) of the fitting frames. |
fit_baseline_ |
(*group, k) Tensor or None
|
Without |
Examples:
>>> import torch
>>> from optix.models import random_shading, simulate_shading
>>> truth = random_shading((64, 64), seed=0)
>>> x = 100 + 50 * torch.rand(40, 64, 64)
>>> data = simulate_shading(x, truth)
>>> basic = BaSiC(working_size=64).fit(data)
>>> flat = basic.estimates["shading"].flat
>>> corrected = basic.apply(data)
Set the options; unset ones come from the preset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
working_size
|
int or (int, int) or None
|
Size the frames are resized to for fitting (None: no resizing). Default 128. |
None
|
darkfield
|
bool
|
Also estimate the dark field d. |
None
|
timelapse
|
bool
|
None
|
|
lambda_flat
|
float
|
λ_f and λ_d, the weights of the DCT sparsity of f and of d_R. Default: derived from the data, per group. |
None
|
lambda_dark
|
float
|
λ_f and λ_d, the weights of the DCT sparsity of f and of d_R. Default: derived from the data, per group. |
None
|
epsilon
|
float
|
ε of the reweighting. Default 0.1. |
None
|
tol
|
(float, int)
|
Inner stop: ‖Y − L − E‖_F / ‖Y‖_F < |
None
|
max_iterations
|
(float, int)
|
Inner stop: ‖Y − L − E‖_F / ‖Y‖_F < |
None
|
max_reweight
|
(int, float)
|
Reweighting stop: relative L1 change of f (and of d) below
|
None
|
reweight_tol
|
(int, float)
|
Reweighting stop: relative L1 change of f (and of d) below
|
None
|
mu_coef
|
float
|
Penalty schedule: μ₀ = |
None
|
rho
|
float
|
Penalty schedule: μ₀ = |
None
|
max_mu_coef
|
float
|
Penalty schedule: μ₀ = |
None
|
max_frames
|
int or None
|
Number of fitting frames per group (None: all). Default 512. |
None
|
sampling
|
(stride, reservoir)
|
How the fitting frames are chosen when there are more than
|
"stride"
|
seed
|
int
|
Seed of the reservoir. |
None
|
variant
|
(paper, basicpy)
|
Solver details: the paper's, or BaSiCPy 2.0.0's. |
"paper"
|
normalize_weights
|
bool
|
Scale the reweighting weights to mean 1 (default True; the "basicpy" variant always does). |
None
|
baseline_method
|
(paper, basicpy)
|
Baseline estimator used with |
"paper"
|
sort_intensity
|
bool
|
Sort each pixel over the fitting frames before the fit. |
None
|
baseline_norm
|
float or mean
|
Background b_{norm} added back by
|
None
|
faithful
|
bool
|
True: the |
True
|
dtype
|
optional
|
See |
None
|
device
|
optional
|
See |
None
|
layout
|
optional
|
See |
None
|
CIDRE
CIDRE(*, working_size=None, quantiles=None, quantile_method=None, bins=None, lambda_r=None, lambda_z=None, lambda_b=None, cauchy_width=None, barrier_width=None, band=None, scales=None, zero_light_limits=None, max_iterations=None, history_size=None, tol=None, init_method=None, normalize_fit=None, faithful=True, dtype=None, device=None, layout=None)
Bases: Estimator
CIDRE: illumination gain and zero-light term by energy minimisation.
CIDRE (corrected intensity distributions using regularised energy minimisation) estimates, from many images acquired under the same conditions, the illumination gain f and the additive zero-light term d of
y(r) = f(r) x(r) + d(r) (1)
It assumes that objects appear anywhere with equal probability, so that the sorted intensities q(r) at every location are a linear transform of a distribution common to all locations:
q(r) = f(r) Q + c(r), c(r) = d(r) − f(r) Z_Q (7, 8)
with Z_Q the zero-light point. (Smith et al. 2015: I_o = y, I = x, v = f, z = d, b = c, location x = r.)
Target distribution (Eqs. 5-6). Q is the robust mean of the q(r) whose mean q̄(r) lies in the central band [ρ_{½−ω}, ρ_{½+ω}] of {q̄(r)}, ρ_u being the u-th quantile over the locations.
Energy (Eq. 9). f, c and the zero-light point (Z_Q, Z_q) minimise
E = E_f + λᵣ Eᵣ + λ_z E_z + λ_b E_b
with
- E_f = ∑_r ∑ₙ (w²/2) log(1 + ((Qₙ f(r) + c(r) − qₙ(r)) / w)²), a Cauchy fit of the K sorted values (Eq. 10);
- Eᵣ = ∑{t∈T} ∑ ((1/|T|) t² ∇²Gₜ ∗ f(i, j))², the scale-normalised Laplacian of Gaussian of f (Eq. 11), t being the standard deviation of the Gaussian;
- E_z = ∑_r (f(r) Z_Q + c(r) − Z_q)², which pulls every regression line through the zero-light point (Eq. 12);
- E_b = β(Z_Q) + β(Z_q), with β zero on [α₁, α₂] and ((x − α)/w_b)² outside (Eqs. 13-14). By default α₁ = 0 and α₂ = min q(r), the smallest value of the data.
The default λ_z is 0.5 and λᵣ goes linearly from 9.5 for one image to 6 for 200 images, and is 6 beyond. E is minimised by L-BFGS in the pivot space (Eqs. 19-20), where Q and q(r) are shifted by their medians; then d = c + f Z_Q (Eq. 7).
Correction. apply reverses Eq. 1
and, by default, rescales the result by the mean gain f̄ ("dynamic
range corrected"):
x = (y − d) / f · f̄ (+ d̄ for "zero-light preserved")
Note
The fit makes one pass over the data, plus a second one when the
per-pixel distributions are summarised by histograms. Each frame
is first resampled to the working grid (bilinear, with
anti-aliasing), then the K quantiles are computed at every location
of the grid. The fitted f and d are resampled back to the image size
(bilinear). apply works on frame
batches.
Implementation choices
- The intensities are divided by their maximum (over the working grid) before the fit, so that the default weights and widths apply whatever the range of the data. Not specified in the paper.
- Each location is summarised by K = 100 quantiles at levels
(k − ½)/K (all values when there are fewer images), so E_f has
at most 100 terms per location whatever the number of images.
They are interpolated linearly between exact order statistics
(rank N u + ½ for level u) when the resampled stack fits the
memory budget (
quantile_method="auto"), else read from per-pixel histograms ofbinsbins over the per-pixel range. Not specified in the paper. - The pivot space reparametrises c only: the medians shift Q and q, and c is recovered exactly, so the energy is unchanged.
- The gradients are those of Eqs. 10-14 as written, obtained by automatic differentiation; the optimisation runs in float64.
- Q is the mean over the central band (Eq. 6 prints a sum; the text calls it a robust mean).
- The scale-space pyramid that the authors use when few images are available is not part of the method here: the paper does not give the function from entropy to the number of octaves.
- The Laplacian of Gaussian is normalised by t² with t the standard deviation (Supplementary Note 3 calls t the variance but multiplies by t², which is scale-invariant only for the standard deviation).
- The optimiser works on rescaled variables (a diagonal preconditioning that leaves the energy unchanged).
- Not specified in the paper: the working grid (long side 128), the Cauchy width w = 0.05 and the barrier width w_b = 10⁻³ (in units of the maximum intensity), λ_b = 1, ω = 0.25, the scales T = {1, 2, 4, 8} (pixels of a grid whose long side is 128, rescaled with the working grid), the borders of the filters (point reflection, so that linear trends are not penalised), the L-BFGS settings and the initialisation (f = 1 and each line through the pivot; Z_Q = Z_q = (α₁ + α₂)/2).
References
- Smith K, Li Y, Piccinini F, Csucs G, Balazs C, Bevilacqua A, Horvath P. CIDRE: an illumination-correction method for optical microscopy. Nat Methods 12(5):404–406, 2015. doi:10.1038/nmeth.3323
BibTeX
@article{smith2015cidre,
author = {Smith, Kevin and Li, Yunpeng and Piccinini,
Filippo and Csucs, Gabor and Balazs, Csaba and
Bevilacqua, Alessandro and Horvath, Peter},
title = {{CIDRE}: an illumination-correction method for
optical microscopy},
journal = {Nature Methods},
volume = {12},
number = {5},
pages = {404--406},
year = {2015},
doi = {10.1038/nmeth.3323},
}
Extension (off by default)
normalize_fit=True divides E_f by the number K of quantiles (the
λ then weigh 1/K as much data).
Attributes:
| Name | Type | Description |
|---|---|---|
estimates |
dict
|
|
zero_light_ |
(*group, 2) Tensor
|
Zero-light point (Z_Q, Z_q) of each group, in data units. |
lambda_r_ |
float
|
λᵣ used by the last fit. |
target_ |
(*group, K) Tensor
|
Target distribution Q of each group, in data units. |
Examples:
>>> import torch
>>> from optix.models import random_shading, simulate_shading
>>> truth = random_shading((64, 64), dark=20.0, seed=0)
>>> x = 100 + 400 * torch.rand(50, 64, 64)
>>> data = simulate_shading(x, truth)
>>> cidre = CIDRE().fit(data)
>>> flat = cidre.estimates["shading"].flat
>>> corrected = cidre.apply(data)
Set the options; unset ones come from the preset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
working_size
|
int or (int, int) or None
|
Grid of the fit: an int is the length of the long side (images that are smaller are not resampled), a pair the exact shape, None the image size. Default 128. Not specified in the paper. |
None
|
quantiles
|
int
|
Number K of quantiles per location (all values when there are fewer images). Default 100. Not specified in the paper. |
None
|
quantile_method
|
(auto, exact, histogram)
|
Exact order statistics of the resampled stack, held in memory; quantiles of per-pixel histograms (second pass over the data); or "auto": exact when the resampled stack fits the configured memory budget. Not specified in the paper. |
"auto"
|
bins
|
int
|
Histogram bins per pixel. Default 1024. Not specified in the paper. |
None
|
lambda_r
|
float
|
Weight of the smoothness energy Eᵣ. Default: 9.5 for one image, decreasing linearly to 6 at 200 images, 6 beyond. |
None
|
lambda_z
|
float
|
Weight of the zero-light energy E_z. Default 0.5. |
None
|
lambda_b
|
float
|
Weight of the barrier energy E_b. Default 1. Not specified in the paper. |
None
|
cauchy_width
|
float
|
Width w of the Cauchy function of E_f, as a fraction of the maximum intensity. Default 0.05. Not specified in the paper. |
None
|
barrier_width
|
float
|
Width w_b of the barrier, as a fraction of the maximum intensity. Default 10⁻³. Not specified in the paper. |
None
|
band
|
float
|
Half-width ω of the central band of Eq. 5. Default 0.25. Not specified in the paper. |
None
|
scales
|
sequence of float
|
Scales T of Eᵣ: standard deviations of the Gaussians, in pixels of a grid whose long side is 128 (they are rescaled with the working grid). Default (1, 2, 4, 8). Not specified in the paper. |
None
|
zero_light_limits
|
(float, float)
|
Limits [α₁, α₂] of the zero-light point, in data units. Default: [0, min q(r)]. |
None
|
max_iterations
|
(int, int, float)
|
L-BFGS (strong Wolfe line search): at most |
None
|
history_size
|
(int, int, float)
|
L-BFGS (strong Wolfe line search): at most |
None
|
tol
|
(int, int, float)
|
L-BFGS (strong Wolfe line search): at most |
None
|
init_method
|
(pivot, least_squares)
|
Initial lines: slope 1 through the pivot (the medians of Q and q(r)), or the per-pixel least-squares fit. The zero-light point starts at the middle of [α₁, α₂]. Default "pivot". Not specified in the paper. |
"pivot"
|
normalize_fit
|
bool
|
Divide E_f by the number of quantiles (extension). Default False. |
None
|
faithful
|
bool
|
Selects the preset; both presets are the paper's method. |
True
|
dtype
|
optional
|
See |
None
|
device
|
optional
|
See |
None
|
layout
|
optional
|
See |
None
|
apply
apply(data, out=None, *, mode='dynamic_range')
Correct images with the fitted f and d.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
array - like or Labeled
|
Images, in the layout of the fit (unless labelled otherwise). |
required |
out
|
writable array-like
|
Output (see |
None
|
mode
|
(dynamic_range, zero_light, direct)
|
"dynamic_range" (dynamic range corrected, the default): x = (y − d) / f · f̄. "zero_light" (zero-light preserved): x = (y − d) / f · f̄ + d̄. "direct": Eq. 1, x = (y − d) / f. f̄ and d̄ are the means of the maps of the group. |
"dynamic_range"
|
Returns:
| Type | Description |
|---|---|
writable array-like
|
|
DarkFlatCalibration
DarkFlatCalibration(*, statistic=None, normalize=None, faithful=True, dtype=None, device=None, layout=None)
Bases: CalibrationEstimator
Prospective flat-field correction from dark and flat references.
optix convention
Dark/flat correction is standard practice with no single defining
publication; the reductions and normalisation below are documented
optix choices (faithful refers to these defaults).
Model and correction:
x = (I − D)/(F − D) · mean(F − D),
with D the per-pixel dark reference (camera offset plus dark current), F the per-pixel flat reference (uniform sample) and mean(F − D) its spatial mean, which keeps the corrected intensities in ADU.
Note
fit(flats, dark=darks): both are stacks in the same layout; the
dark may also be a precomputed map (a Tensor that broadcasts to the
(*group, *spatial) maps), a
ShadingEstimate (its dark)
or a SensorEstimate (its
offset). Without a dark, D = 0.
Estimates: "shading" (flat, dark) and, when a dark stack is
given, "sensor" (offset = D and the per-pixel temporal
variance of the dark stack).
Configure the calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statistic
|
(mean, median)
|
Per-pixel reduction of the reference stacks. |
"mean"
|
normalize
|
(mean, none)
|
|
"mean"
|
faithful
|
bool
|
See |
True
|
dtype
|
bool
|
See |
True
|
device
|
bool
|
See |
True
|
layout
|
bool
|
See |
True
|
GammaMixture
GammaMixture(*, nclass=None, noise=None, order=None, gain=None, nodes=None, nu_bounds=None, quantization=None, max_iterations=None, tol=None, learn_modulation=None, learn_alpha=None, lr=None, max_halvings=None, max_log_step=None, bg_fraction=None, threshold=None, spread_floor=None, concentration=None, v_prior=None, v_dof=None, lam=None, faithful=True, dtype=None, device=None, layout=None)
Bases: Estimator
Joint model of the sensor, the shading and the tissue classes.
Image formation. A pixel i of frame n records
yₙᵢ ~ N(cᵢ + fᵢ·uₙᵢ, vᵢ + g·fᵢ·uₙᵢ)
with the offset c (camera offset plus background, in ADU), the variance v of an empty pixel, the gain g (ADU per electron), the smooth modulation f (flat field) and the signal u ≥ 0 in ADU. It is the Gaussian limit of
yₙᵢ = oᵢ + g·Poisson(fᵢ·(sₙᵢ + bᵢ) + d_{ei}) + read noise,
with the dark signal dₑ, u = g·s, c = o + g·(f·b + dₑ) and v = σ² + g²·(f·b + dₑ).
Probabilistic model. The signal is a mixture of K tissue classes and a background class, with proportions drawn per picture:
πₙ ~ Dirichlet(α), zₙᵢ ~ Categorical(πₙ)
uₙᵢ | zₙᵢ = background ~ δ(0)
uₙᵢ | zₙᵢ = k ~ Gamma(νₖ, rate νₖ / μₖ)
f = exp(Φ·θ), θ ~ N(0, (λ·diag(bending energy))⁻¹)
with Φ the separable DCT-II basis without its DC term (geometric mean of f = 1) and an inverse-gamma-like prior on v, log p(v) = −½·v_dof·(log v + v₀/v).
Inference. The variational posterior is
q = ∏ₙ q(πₙ) · ∏ₙᵢ q(zₙᵢ) q(uₙᵢ | zₙᵢ) · δ(c, v, θ, μ, ν, α)
- q(z, u) is exact given everything else: the integral over u is a Gauss-Hermite quadrature in t = log u centred on the mode of the integrand (the roots of a cubic for the "full" noise model).
- q(πₙ) is Dirichlet (conjugate update).
- μ, ν are refitted to the aggregated posterior of u in each class, and α by Minka's fixed-point Newton method.
- c, v, θ take one joint Fisher-scoring step per iteration: the per-pixel unknowns (c, v) are eliminated exactly, which leaves a small dense system in θ. A step that lowers the bound is halved.
Data are quantised: each observation is replaced by a uniform
distribution over its quantisation bin of width Δ, so that every
squared residual becomes r² + Δ²/12 and the bound stays finite when a
pixel takes the same value in many pictures. Δ = 1 (integer data in
ADU) by default; quantization="auto" detects it from a sample of
the data.
The gain g is held at its nominal value (gain, or the gain of an
initial SensorEstimate): in this
model it is identified only through the shape of the signal
distribution.
Note
Memory and streaming: the fit reads the data in batches of frames, once per iteration (plus one pass per halved step), and twice more for the initialisation (once by strips of rows holding every frame, for per-pixel order statistics, and once by frame batches).
The data-driven initialisation takes the per-pixel order statistic
of rank ½·bg_fraction·N as c and its distance to the rank
0.1587·bg_fraction·N as the standard deviation of the background
(clamped to [¼, 4] times its median); values more than threshold
standard deviations above c are labelled as tissue. The flat field
is initialised from their mean excess over the threshold, and the
classes by a k-means on the log of the tissue values.
The fit stops when the bound improves by less than tol per data
point, or after max_iterations iterations.
Attributes:
| Name | Type | Description |
|---|---|---|
estimates |
dict
|
|
concentration_ |
Tensor
|
|
theta_ |
Tensor
|
|
quantization_ |
Tensor
|
|
Examples:
>>> import torch
>>> from optix.models import random_sensor, simulate_gamma_mixture
>>> from optix.models import simulate_sensor
>>> sensor = random_sensor((32, 32), gain=2.0, offset_sd=0.0, seed=0)
>>> draw = simulate_gamma_mixture((20, 32, 32), [100.0], [2.0], seed=0)
>>> data = simulate_sensor(draw.signal / 2.0, sensor, seed=1).round()
>>> mixture = GammaMixture(gain=2.0, max_iterations=5).fit(data)
>>> offset = mixture.estimates["sensor"].offset
>>> corrected = mixture.apply(data)
>>> foreground = mixture.apply(data, output="foreground")
Set the options; unset ones come from the preset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nclass
|
int
|
Number K of tissue classes (besides the background). Default 1. |
None
|
noise
|
(full, constant)
|
Variance of the data given the signal: v + g·f·u ( |
"full"
|
order
|
int or (int, int)
|
Number of DCT basis functions of log f along each spatial axis. Default (8, 8). |
None
|
gain
|
float
|
Nominal gain g in ADU per electron. Default: the (mean) gain
of an initial |
None
|
nodes
|
int
|
Number of Gauss-Hermite nodes of the integral over u (per class, pixel and picture). The cost of the fit grows in proportion. The integral is least accurate when a shape ν is close to 1 (about 5·10⁻³ on log p(y | z) with 24 nodes, 10⁻³ with 48); more nodes make it more accurate. Default 24. |
None
|
nu_bounds
|
(float, float)
|
Bounds on the Gamma shapes. The lower bound of 1 (default) prevents a tissue class from developing a spike at zero and competing with the background. Default (1, 10³). |
None
|
quantization
|
float or auto
|
Width Δ of one quantisation bin, in ADU (1 for integer data,
the default; 0 treats the data as continuous). |
None
|
max_iterations
|
int
|
Maximum number of iterations. Default 100. |
None
|
tol
|
float
|
Stop when the bound changes by less than |
None
|
learn_modulation
|
bool
|
Estimate f (default True); otherwise f = 1, or the flat field
of an initial |
None
|
learn_alpha
|
bool
|
Estimate the Dirichlet concentrations α (default True). |
None
|
lr
|
float
|
Damping of the Fisher-scoring step. Default 1. |
None
|
max_halvings
|
int
|
When the bound decreases, the last parameter step is halved up to this many times. Default 4. |
None
|
max_log_step
|
float
|
Largest change of log f in one step. Default 0.5. |
None
|
bg_fraction
|
float
|
Lower bound on the fraction of pictures in which a pixel is empty, used by the initialisation. Default 0.5. |
None
|
threshold
|
float
|
Number of background standard deviations above c beyond which a value is initially labelled as tissue. Default 3. |
None
|
spread_floor
|
bool
|
Floor the initial standard deviation of an empty pixel at the quantisation scale Δ/√12 (so that v ≥ Δ²/12), for data whose read noise is well below one bin. Default False (a warning is emitted when the initial v is below Δ²/12). |
None
|
concentration
|
float or sequence of float
|
Initial Dirichlet concentrations α of the K + 1 proportions (background last). Default 1. |
None
|
v_prior
|
float
|
Prior variance v₀ of an empty pixel. Default: the median of the initial v. |
None
|
v_dof
|
float
|
Strength of the prior on v, as a number of pseudo-observations (0 disables it). Default 5. |
None
|
lam
|
float
|
Precision λ of the bending-energy prior on log f. Default 1. |
None
|
faithful
|
bool
|
True: the reference preset. False: the |
True
|
dtype
|
optional
|
See |
None
|
device
|
optional
|
See |
None
|
layout
|
optional
|
See |
None
|
classify
classify(data, *, per_class=False, mean=False, out=None, out_mean=None)
Posterior class probabilities of the training data.
Uses the fitted parameters and the q(π) of each training picture
(concentration_). See
predict for new
pictures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
array - like or Labeled
|
The data given to [ |
required |
per_class
|
bool
|
False: the foreground probability p(z ≠ background | y), of
the shape of |
False
|
mean
|
bool
|
Also compute the posterior mean E[u | y] (0 in the
background), of the shape of |
False
|
out
|
writable array-like
|
Outputs (tensor, numpy, zarr, ...). Default: new tensors. |
None
|
out_mean
|
writable array-like
|
Outputs (tensor, numpy, zarr, ...). Default: new tensors. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
probabilities |
writable array-like
|
|
mean |
writable array-like or None
|
|
predict
predict(data, *, per_class=False, mean=False, out=None, out_mean=None, niter=20, tol=0.001)
Classify pictures with the fitted model.
c, v, f, g, μ, ν and α are kept fixed; only the proportions q(π) of each picture are inferred, by alternating q(z) and q(π) for each batch of pictures. The class likelihoods do not depend on π, so they are computed once per batch: the cost is that of one pass of the fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
array - like or Labeled
|
Pictures with the spatial (and group) shape of the fit. |
required |
per_class
|
bool
|
See |
False
|
mean
|
bool
|
See |
False
|
out
|
bool
|
See |
False
|
out_mean
|
bool
|
See |
False
|
niter
|
int
|
Maximum number of q(z) / q(π) iterations per batch. |
20
|
tol
|
float
|
Stop when the class counts of every picture change by less
than |
0.001
|
Returns:
| Name | Type | Description |
|---|---|---|
probabilities |
writable array-like
|
|
mean |
writable array-like or None
|
|
concentration |
Tensor
|
|
apply
apply(data, out=None, *, output='corrected')
Correct the data, or classify them with the fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
array - like or Labeled
|
Pictures with the spatial (and group) shape of the fit. |
required |
out
|
writable array-like
|
Output (tensor, numpy, zarr, ...). Default: a new tensor. |
None
|
output
|
(corrected, foreground, classes, mean)
|
The probabilities and the mean are those of
|
"corrected"
|
Returns:
| Type | Description |
|---|---|
writable array-like
|
|
IlluminationFunction
IlluminationFunction(*, statistic=None, smoothing=None, size=None, rescale=None, faithful=True, dtype=None, device=None, layout=None)
Bases: CalibrationEstimator
Retrospective multi-image illumination function (Singh et al., 2014).
The illumination correction function (ICF) is
f = S(meanₙ (yₙ − d)), x = (y − d)/f,
the per-pixel average of all images of a batch (e.g. a plate and channel) smoothed by S; each image is corrected by dividing it by f. (Singh et al. 2014: F = f, I = y.)
Faithful mode follows the paper: per-pixel mean over all images, then a median filter with a window of 500 pixels (Singh et al. 2014, "Computing illumination correction functions", Fig. 1), then division. The paper does not rescale the ICF and does not subtract a dark field.
Interpretation
The paper's "median filter with window size = 500 pixels" is
implemented as a square window of side size
(median_window),
pixels outside the image being ignored. The paper implements the
method in CellProfiler; CellProfiler's own conventions (a disk
median of radius ≈ size/2.35, Gaussian and polynomial smoothing,
the automatic filter size, the robust-minimum rescaling) are
extensions here, ported from CellProfiler's
CorrectIlluminationCalculate (BSD-3-Clause) where the paper defers
to it, and are off by default.
Cost
The exact square median
(median_filter) costs the same per
pixel whatever the window size: the paper's
500-pixel window on a 1280×1024 image takes a few seconds on one
CPU thread.
Note
fit(images, dark=None). dark (extension) is subtracted from the
average before smoothing: a stack, a map, or an estimate
(ShadingEstimate.dark / SensorEstimate.offset). Estimates:
"shading" with flat (meta["flat_norm"]: "none" or
"robust-min") and dark when given.
References
- Singh S, Bray M-A, Jones TR, Carpenter AE. Pipeline for illumination correction of images for high-throughput microscopy. J Microsc 256(3):231–236, 2014. doi:10.1111/jmi.12178
BibTeX
@article{singh2014pipeline,
author = {Singh, S. and Bray, M.-A. and Jones, T. R. and
Carpenter, A. E.},
title = {Pipeline for illumination correction of images for
high-throughput microscopy},
journal = {Journal of Microscopy},
volume = {256}, number = {3}, pages = {231--236},
year = {2014}, doi = {10.1111/jmi.12178}
}
Configure the illumination function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statistic
|
(mean, median)
|
Per-pixel average. |
"mean"
|
smoothing
|
(median, median - disk, gaussian, polynomial, none)
|
|
"median"
|
size
|
float
|
Window side in pixels ( |
None
|
rescale
|
(none, robust - min)
|
Extension: |
"none"
|
faithful
|
bool
|
See |
True
|
dtype
|
bool
|
See |
True
|
device
|
bool
|
See |
True
|
layout
|
bool
|
See |
True
|
Likar
Likar(*, levels=None, data_range=None, window=None, components=None, sampling=None, tol=None, max_iterations=None, faithful=True, dtype=None, device=None, layout=None)
Bases: Estimator
Retrospective shading correction by entropy minimisation.
Likar et al. (2000) model the acquired image N as the true image U with a multiplicative and an additive shading component,
N(x, y) = U(x, y) · S_M(x, y) + S_A(x, y), (Eq. 3)
and correct it by inverting the model, Û = (N − Ŝ_A) / Ŝ_M (Eq. 5). Both components are second-order polynomials, with the origin at the image centre, neutralised so that ∫∫ Ŝ_A = 0 and (1/WH) ∫∫ Ŝ_M = 1 over the W × H image (Eqs. 14-17):
Ŝ_A = a₁x + a₂y + a₃xy + a₄(x² − W²/12) + a₅(y² − H²/12)
Ŝ_M = 1 + m₁x + m₂y + m₃xy + m₄(x² − W²/12) + m₅(y² − H²/12)
The ten parameters minimise the Shannon entropy of the corrected image (Eq. 18),
{a, m} = argmin H((N − Ŝ_A) / Ŝ_M), H = −∑ₙ p(n) log p(n),
found with Powell's direction-set method and Brent's line minimisation (Press et al., 1992). The histogram is built with partial intensity interpolation (a grey value g transformed to g′ ∈ [k, k + 1] adds k + 1 − g′ to bin k and g′ − k to bin k + 1), on the range [−G, 2G] of G grey levels, and blurred by a triangular window before normalisation (Eq. 20):
*h(n) = ∑_{i=−t}^{t} h(n + i) (t + 1 − |i|), t = 2.
Pixels at the marginal grey values 1 and G of the input image are ignored (they may be saturated).
Grey levels are defined on the data range [lo, hi]: a value v has
grey level g = round((v − lo)/δ) + 1 with δ = (hi − lo)/(G − 1). By
default, integer data whose dtype has at most G values (e.g. uint8
with levels=256, the paper's setting) use the dtype range, so the
grey levels are the integer values and the marginal ones are the
saturation values 0 and 255; wider integers and floats use the
observed minimum and maximum of each group. The model and the
correction are in data units.
Several images
The paper corrects one image at a time. Given several frames (the sample axes of the layout), one shading per group is fitted to minimise the entropy of the histogram of all corrected frames together. Pooling assumes that the shading is the same in every frame: this holds for acquisition shading (illumination, optics, camera), but not for object-dependent shading (e.g. slice thickness or staining), which varies from one image to the next; fit each frame separately for per-image shading.
Streaming and memory
The fit reads the data once (twice when the range is the observed
minimum and maximum): the statistic is the count of each
(pixel, grey level) pair, which holds at most min(frames, G)
entries per pixel. When a dense table of H·W·G int32 counts fits
in the memory budget (optix.config(memory=...)), counts are
accumulated in it; otherwise they are kept sparse (int64 key and
count per pair), and a warning is issued if their worst-case size
exceeds the budget: sampling > 1 reduces it. The objective is
then evaluated on these counts. apply streams frame batches.
Estimates: "shading", a
ShadingEstimate with
flat = Ŝ_M and dark = Ŝ_A, maps (*group, H, W) in data units,
and meta["flat_norm"] = "mean" (Eq. 15); apply returns
(N − dark) / flat (Eq. 5). meta["coefficients"] holds the paper's
(a₁ … a₅) and (m₁ … m₅) per group, in pixel coordinates and data
units, and meta["entropy"] the final entropies (nats).
References
- Likar B, Maintz JBA, Viergever MA, Pernuš F. Retrospective shading correction based on entropy minimization. J Microsc 197(3):285–295, 2000. doi:10.1046/j.1365-2818.2000.00669.x
- Press WH, Teukolsky SA, Vetterling WT, Flannery BP. Numerical Recipes in C. 2nd edn. Cambridge University Press, 1992.
BibTeX
@article{likar2000retrospective,
author = {Likar, B. and Maintz, J. B. A. and
Viergever, M. A. and Pernu{\v{s}}, F.},
title = {Retrospective shading correction based on
entropy minimization},
journal = {Journal of Microscopy},
volume = {197}, number = {3}, pages = {285--295},
year = {2000},
doi = {10.1046/j.1365-2818.2000.00669.x}
}
@book{press1992numerical,
author = {Press, W. H. and Teukolsky, S. A. and
Vetterling, W. T. and Flannery, B. P.},
title = {Numerical Recipes in {C}},
edition = {2nd},
publisher = {Cambridge University Press},
year = {1992}
}
Examples:
>>> est = Likar().fit(image)
>>> corrected = est.apply(image)
Set the options; unset ones come from the preset.
Note
Not specified in the paper, and chosen here: the optimisation
starts from no shading (all parameters 0); Powell's initial
directions are the unit vectors of parameters rescaled to
coordinates x̃ = 2x/W, ỹ = 2y/H ∈ [−1, 1] (additive ones in
units of hi − lo), which changes the scale of the search but
not the model; pixel coordinates are pixel centres; corrected
values outside [−G, 2G] are clamped to the end bins; parameters
that make Ŝ_M ≤ 0 at a pixel are rejected (their objective
exceeds the maximum entropy; the minimum of the quadratic Ŝ_M
is checked exactly over the full image, also with
sampling > 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
levels
|
int
|
Number G of grey levels. Default 256 (the paper's 8-bit images). |
None
|
data_range
|
(float, float)
|
Data values [lo, hi] of grey levels 1 and G. Default: the
dtype range for integer data with at most G distinct values
(e.g. (0, 255) for |
None
|
window
|
int
|
Half-width t of the triangular histogram blur (Eq. 20). Default 2 (window of 2t + 1 = 5 bins); 0 disables it. |
None
|
components
|
(both, additive, multiplicative)
|
Shading components to fit. Extension: the paper fits both; fitting a single one is one of the modifications its discussion suggests. |
"both"
|
sampling
|
int
|
Extension: use every |
None
|
tol
|
float
|
Fractional tolerance |
None
|
max_iterations
|
int
|
Maximum number of Powell iterations. Default 200. Not specified in the paper. |
None
|
faithful
|
bool
|
Selects the preset; both presets are the paper's method. |
True
|
dtype
|
optional
|
See |
None
|
device
|
optional
|
See |
None
|
layout
|
optional
|
See |
None
|
KaskFlatField
KaskFlatField(*, model=None, regularization=None, bins=None, window=None, noise_threshold=None, intensity_threshold=None, min_background_fraction=None, foreground_sigma=None, group_size=None, outlier_factor=None, subsets=None, max_error=None, kappa=None, faithful=True, dtype=None, device=None, layout=None)
Bases: Estimator
Separate background and foreground flat fields (Kask et al., 2016).
Fluorescence images are modelled with an additive background shaded by a background profile S_b and a signal shaded by a different foreground profile S_f, both normalised to mean 1 (Eqs. 1–3):
N = S_f · U + B · S_b,
Û = (N − B̂ · S_b) / S_f + B̂,
with B̂ the mean background intensity of the image being corrected. Both profiles are estimated retrospectively from many sample images (Fig. 1), in one pass over the data:
- Background segmentation. The noise image is the local variance
over the local mean in a
window² window, after removing the slope of the background profile (division by the current profile estimate; before one exists, by a centred profile 1 − c·ρ² whose curvature c minimises the noise level). It is ≈ κ, a constant of the detection channel estimated from the series (kappa), in the background (Eq. 4) and much higher on objects. Background pixels lie below an upper threshold on the noise image; an intensity threshold then removes flat bright regions inside objects. - Foreground segmentation. The image is cut into blocks; in each,
pixels above the block mean plus
foreground_sigmaexpected standard deviations √(κ · mean) are foreground. - Binning. Both segmented images are averaged in blocks into
bins(17 × 16 pixels in the paper, from its blocks of 80 × 64 pixels); blocks without a segmented pixel are undefined. - Background profile. Images with less than
min_background_fractionbackground are discarded. The others are fitted globally (E_k ≈ a_k · S_b, step 6), images with an abnormally high mean square deviation from the fit are discarded, and the fit and the filter are repeated until no outlier remains. - Foreground profile. Consecutive sets of
group_sizebinned foreground images are outlier-filtered and averaged; the background B̄ · S_b is subtracted from each average (B̄ the mean background level of its images), and the averages are fitted globally. - Global fit and smoothing (Eq. 5). A global fit alternates the
levels a_k, by least squares (min ∑_ij (E_kij − a_k T_ij)²), and
the profile T, the smooth fit of ē = mean_k(E_k / a_k) weighted by
the number W_ij of images defining each bin,
min ∑_ij W_ij (ē_ij − T_ij)² + R ∑_ij (Lxx_ij² + Lyy_ij²),
renormalised to mean 1, until T is stable. R is given by
regularization(0.2 for the background and 20 for the foreground in the paper);model="polynomial"fits a fourth-order polynomial instead. Lxx and Lyy are second differences between neighbouring bins, at interior bins only. Not specified in the paper: Eq. 5 is written for a single image, and the paper does not give the objective of the global fit. With W_ij = K, the deviation term is ∑_k ‖E_k / a_k − T‖² up to a constant, so R does not depend on the number of images K. - Quality control. The data are split into
subsetsfitted separately (with R scaled by their share of the images, so that they smooth as much as the full fit); the spread of their profiles gives the range of the random error of the profile. A profile whose error exceedsmax_erroris not applied (replaced by 1, with a warning); the foreground profile is only estimated when the background profile passes.
Estimates
"shading": flat is the foreground profile S_f (mean 1,
meta["flat_norm"] == "mean"), and dark the background
profile scaled to the mean background level of the images used
in the background fit, B̄ · S_b, in ADU (it includes the camera
offset); the levels of discarded images are not averaged. The
background of each image is rescaled: apply estimates B̂ per
image (meta["dark_scaling"] == "per-frame"), whereas
ShadingEstimate.correct
subtracts dark as is. meta also holds the random errors,
the numbers of images used, B̄ and κ (noise_constant). The
background level of every image is in background_level_
((*group, n)).
Streaming
Frames are segmented one at a time, in storage order, and only their binned images are kept (4 · h · w values per frame: the sums and counts of the background and foreground pixels of each bin). κ is a running median of the frames' modes. The provisional background profile used to segment later frames is refitted when the number of background images reaches 10, 20, 40, … (not specified in the paper), so the result depends on the frame order but not on the batch size.
Settings not specified in the paper
κ is the median over the frames of the mode of each frame's noise
image (the position of the highest peak of the histogram of its
logarithm); while streaming, each frame uses the median of the
modes of the frames seen so far. The paper fixes the block size
(80 × 64 or 64 × 64 pixels), the estimator the number of bins:
bins=(16, 17) gives the paper's blocks on 1360 × 1024 frames
only; on other sizes the blocks, and so the pixels behind each
bin and the foreground threshold, differ from the paper, while R
keeps its per-bin meaning. The initial curvatures are
c ∈ {0, 0.05, …, 0.6}, with ρ² = 1 at the corners. Profiles are
brought from bins to pixels by linear interpolation between bin
centres (the polynomial is evaluated at the pixels). The random
error uses contiguous subsets. B̂ is ∑ N / ∑ S_b over the
background pixels of the frame, and the fit's mean level when a
frame has no background.
References
- Kask P, Palo K, Hinnah C, Pommerencke T. Flat field correction for high-throughput imaging of fluorescent samples. J Microsc 263(3):328–340, 2016. doi:10.1111/jmi.12404
BibTeX
@article{kask2016flat,
author = {Kask, P. and Palo, K. and Hinnah, C. and
Pommerencke, T.},
title = {Flat field correction for high-throughput imaging
of fluorescent samples},
journal = {Journal of Microscopy},
volume = {263}, number = {3}, pages = {328--340},
year = {2016}, doi = {10.1111/jmi.12404}
}
Configure the estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
(regularization, polynomial)
|
Profile model: image regularisation (Eq. 5, the paper's default) or a fourth-order polynomial of the coordinates, which the paper also uses. |
"regularization"
|
regularization
|
(float, float)
|
Regularisation coefficients R of Eq. 5 for the background and the foreground profiles, on the binned grid. Paper: (0.2, 20). |
None
|
bins
|
(int, int)
|
Shape (rows, columns) of the binned images, which is also the grid of foreground-segmentation blocks. Paper: 17 × 16 pixels (x × y), i.e. (16, 17), from blocks of 80 × 64 pixels of 1360 × 1024 frames. The paper fixes the block size; the number of bins is fixed here, whatever the image size. |
None
|
window
|
int
|
Odd side of the window of the local mean and variance of the noise image. Paper: 9. |
None
|
noise_threshold
|
float
|
Upper threshold on the noise image, in units of κ (see
|
None
|
intensity_threshold
|
float
|
Pixels whose local mean (after division by the profile) exceeds this factor times the median over the noise-selected pixels are not background. Not specified in the paper. |
None
|
min_background_fraction
|
float
|
Images with a smaller background fraction are not used for the background profile. Paper: 0.15. |
None
|
foreground_sigma
|
float
|
Foreground threshold, in expected standard deviations above the block mean. Paper: 5. |
None
|
group_size
|
int
|
Number of foreground images averaged together. Paper: 16. A trailing incomplete set is not used. |
None
|
outlier_factor
|
float
|
An image is an outlier when its mean square deviation from the global fit exceeds this factor times the median over the images. Not specified in the paper. |
None
|
subsets
|
int
|
Number of subsets fitted separately to estimate the random error. Not specified in the paper. |
None
|
max_error
|
(float or None, float or None)
|
Quality-control limits on the range of the random error of the background and foreground profiles; None disables the check. The paper gives 2 % as an example for the background; the foreground limit is not specified in the paper. |
None
|
kappa
|
(series, per - frame)
|
Noise constant κ (var/mean of the background), a constant of
the detection channel in the paper. |
"series"
|
faithful
|
bool
|
See |
True
|
dtype
|
bool
|
See |
True
|
device
|
bool
|
See |
True
|
layout
|
bool
|
See |
True
|
Transforms
Shading correction: flat field, dark field and per-frame baseline.
Building blocks of these estimators are in optix.shading.utils.
correct
correct(y, dark, flat)
(y − dark)/flat.
Utilities
No stability promise
optix.shading.utils holds building blocks of the estimators above; they may change without notice.
Building blocks of the shading estimators.
Semi-public: these may change without notice.
fit_polynomial
fit_polynomial(x, degree=2)
Least-squares polynomial of the coordinates (total degree <= 2).
In 2D: A·x² + B·y² + C·xy + D·x + E·y + F (CellProfiler's "Fit Polynomial"). Coordinates are scaled to [-1, 1].
gaussian_smooth
gaussian_smooth(x, sigma)
Normalised Gaussian convolution over all dims of x.
conv(x)/conv(1) with zero padding (CellProfiler's
smooth_with_function_and_mask without a mask), so that borders are
not darkened. The kernel is truncated at 4 sigma.
median_smooth
median_smooth(x, radius, *, rows=64)
Median filter with a disk of radius (2D; CellProfiler extension).
Pixels outside the image are ignored (as a rank filter). Computed in
strips of rows rows. Lower median (torch.nanmedian). See
median_disk.
median_window
median_window(x, size, *, budget=1 << 24)
Exact median filter with a square window of side size (2D).
The window of pixel (i, j) spans rows i − ⌊size/2⌋ … i + ⌈size/2⌉ − 1
(likewise for columns); pixels outside the image are ignored. Lower
median (torch.nanmedian). A side larger than 2·n − 1 along a dim of
length n is equivalent to 2·n − 1 there (every window then spans the
whole dim). The cost per pixel does not grow with size; budget
bounds the memory of small windows, which are sorted. See
median_filter.
robust_minimum
robust_minimum(x)
CellProfiler rescaling: divide by the 2nd percentile of x > 0.
Values below that robust minimum are clipped to it first, so the result is >= 1.