Skip to content

Denoising (optix.denoise)

Estimators

Denoising.

Block matching and collaborative filtering: BM3D for images (Dabov et al. 2007) and BM4D for volumes (Maggioni et al. 2013), for white Gaussian noise or, after the generalised Anscombe transform, Poisson-Gaussian noise; non-local means (Buades, Coll & Morel 2005); PURE-LET (Luisier et al. 2011) for mixed Poisson-Gaussian noise; ACsN for sCMOS frames (Mandracchia et al. 2020); total-variation denoising (Rudin, Osher & Fatemi 1992). Building blocks (transforms, block matching, the two filtering stages, the patch distances, the PURE-LET system, the total-variation solver) are in optix.denoise.utils.

NCS (Liu et al. 2017) corrects the pixel-dependent noise of sCMOS cameras by MAP estimation with the camera's offset, gain and variance maps and a penalty on the spectrum outside the optical transfer function; its building blocks (mask, cost, solver, segments) are also in optix.denoise.utils.

BM3D

BM3D(*, sigma=None, data_range=None, profile=None, output=None, search=None, step=None, inverse=None, block=None, keep_dc=None, faithful=True, dtype=None, device=None, layout=None)

Bases: _BlockMatching

BM3D denoising of images (Dabov et al. 2007).

Applies bm3d to each image (the two spatial axes of the layout; other axes are samples or groups). The noise is white Gaussian with a known σ, or Poisson-Gaussian with the parameters of a SensorEstimate, in which case the image is denoised after the generalised Anscombe transform (Mäkitalo & Foi 2013, doi:10.1109/TIP.2012.2202675) with σ = 1, and transformed back by its exact unbiased inverse; maps of the estimate apply pixel by pixel.

fit sets the noise model and, unless data_range is given, reads the data once to estimate the range of the clean signal. apply streams blocks with the halo of bm3d_halo (the reference grid is that of the whole image), so arrays larger than memory (zarr, memmap) give the whole-image result.

Note

Faithful mode is the Normal Profile of the paper. search, step and keep_dc are extensions; data_range, output, inverse and block do not change the method.

References

  1. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
  2. Maggioni M, Katkovnik V, Egiazarian K, Foi A. A nonlocal transform-domain filter for volumetric data denoising and reconstruction. IEEE Trans Image Process 22(1):119–133, 2013. doi:10.1109/TIP.2012.2210725
BibTeX
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}
@article{maggioni2013nonlocal,
  author  = {Maggioni, Matteo and Katkovnik, Vladimir and
             Egiazarian, Karen and Foi, Alessandro},
  title   = {A nonlocal transform-domain filter for volumetric
             data denoising and reconstruction},
  journal = {IEEE Transactions on Image Processing},
  volume  = {22}, number = {1}, pages = {119--133},
  year    = {2013}, doi = {10.1109/TIP.2012.2210725}
}

Examples:

>>> import torch
>>> from optix.denoise import BM3D
>>> clean = torch.linspace(0, 255, 48).expand(48, 48)
>>> noisy = clean + 20 * torch.randn(48, 48)
>>> den = BM3D(sigma=20, data_range=255).fit().apply(noisy)
>>> bool((den - clean).square().mean() < (noisy - clean).square().mean())
True

Configure the denoiser.

Parameters:

Name Type Description Default
sigma float

Standard deviation σ of white Gaussian noise, in data units. Omit it to give a SensorEstimate to fit instead.

None
data_range float

Intensity range mapped to the paper's [0, 255] (not specified in the paper, whose images are 8-bit). Default: clean_range of the data given to fit (of the stabilised data, with σ = 1, with a SensorEstimate).

None
profile normal

Profile of Table I. Default: "normal".

"normal"
output (final, basic)

The final estimate (default) or the basic estimate of step 1.

"final"
search int

Extension: side N_S of the search window (paper: 39).

None
step int

Extension: step N_step between reference blocks (paper: 3, or 4 and 6 for σ > 40).

None
inverse (exact, closed - form, asymptotic, algebraic)

Inverse of the Anscombe transform (see inverse_anscombe). Default: "exact".

"exact"
block sequence of int or None

Core block size per spatial axis (default: from the memory budget). The result does not depend on it.

None
keep_dc bool

Extension: never threshold the DC coefficient of a group, as in BM4D, which makes the basic estimate invariant to an offset of the intensities. Default: False (the paper).

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

BM4D

BM4D(*, sigma=None, data_range=None, profile=None, output=None, search=None, step=None, inverse=None, block=None, faithful=True, dtype=None, device=None, layout=None)

Bases: _BlockMatching

BM4D denoising of volumes (Maggioni et al. 2013).

Applies bm4d to each volume (the three spatial axes of the layout). Noise models, fitting and streaming are those of BM3D: blocks are z-slabs (or smaller) with the halo of bm4d_halo.

Note

Faithful mode is the normal or modified profile of Table I. search and step are extensions.

References

  1. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
  2. Maggioni M, Katkovnik V, Egiazarian K, Foi A. A nonlocal transform-domain filter for volumetric data denoising and reconstruction. IEEE Trans Image Process 22(1):119–133, 2013. doi:10.1109/TIP.2012.2210725
BibTeX
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}
@article{maggioni2013nonlocal,
  author  = {Maggioni, Matteo and Katkovnik, Vladimir and
             Egiazarian, Karen and Foi, Alessandro},
  title   = {A nonlocal transform-domain filter for volumetric
             data denoising and reconstruction},
  journal = {IEEE Transactions on Image Processing},
  volume  = {22}, number = {1}, pages = {119--133},
  year    = {2013}, doi = {10.1109/TIP.2012.2210725}
}

Configure the denoiser.

Parameters:

Name Type Description Default
sigma float

Standard deviation σ of white Gaussian noise, in data units. Omit it to give a SensorEstimate to fit instead.

None
data_range float

Intensity range mapped to the paper's [0, 1]. Default: clean_range of the data given to fit (of the stabilised data, with σ = 1, with a SensorEstimate).

None
profile (normal, modified)

Profile of Table I. Default: "normal".

"normal"
output (final, basic)

The final (Wiener) estimate (default) or the hard-thresholding estimate.

"final"
search int

Extension: side N_S of the search cube (paper: 11).

None
step int

Extension: step N_step between reference cubes (paper: 3).

None
inverse (exact, closed - form, asymptotic, algebraic)

Inverse of the Anscombe transform. Default: "exact".

"exact"
block sequence of int or None

Core block size per spatial axis (default: from the memory budget). The result does not depend on it.

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

NCS

NCS(*, numerical_aperture=None, wavelength=None, pixel_size=None, alpha=None, mask=None, segment=None, units=None, max_iter=None, tol=None, block=None, faithful=True, dtype=None, device=None, layout=None)

Bases: Estimator

NCS noise correction of sCMOS images (Liu et al. 2017).

Applies ncs to each image (the two spatial axes of the layout; other axes are samples or groups) with the pixel maps of a SensorEstimate given to fit (offset in ADU, read-noise variance in ADU², gain in ADU per electron; maps of shape (*group, H, W), (H, W) or scalars, cropped to each streamed block).

apply streams blocks with the halo of ncs_halo; the segments are on the grid of the whole image, so arrays larger than memory (zarr, memmap) give the whole-image result.

Note

Faithful mode is the paper's cost: α = 0.2, an OTF mask of the paper ("otf-weighted", the default, or "noise-only") and a segment size in the recommended range 8–32. Another α, a user-defined mask or another segment size are extensions. units, max_iter, tol and block do not change the cost. The result is the minimiser of that cost only where the solver converges; apply emits a RuntimeWarning with the count of segment solves that did not. The defaults are all the paper's, so faithful=False changes nothing.

Negative estimates

The estimate is bounded below by −γᵢ = −σᵢ²/gᵢ², not by 0, and can be negative at pixels of large read noise next to brighter neighbours (see ncs).

References

  1. Liu S, Mlodzianoski MJ, Hu Z, Ren Y, McElmurry K, Suter DM, Huang F. sCMOS noise-correction algorithm for microscopy images. Nat Methods 14(8):760–761, 2017. doi:10.1038/nmeth.4379
BibTeX
@article{liu2017scmos,
  author  = {Liu, Sheng and Mlodzianoski, Michael J. and
             Hu, Zhenhua and Ren, Yuan and McElmurry, Kristi
             and Suter, Daniel M. and Huang, Fang},
  title   = {{sCMOS} noise-correction algorithm for
             microscopy images},
  journal = {Nature Methods},
  volume  = {14}, number = {8}, pages = {760--761},
  year    = {2017}, doi = {10.1038/nmeth.4379}
}

Examples:

>>> import torch
>>> from optix.denoise import NCS
>>> from optix.estimates import SensorEstimate
>>> g = torch.Generator().manual_seed(0)
>>> variance = 1 + 400 * torch.rand(48, 48, generator=g)
>>> sensor = SensorEstimate(
...     offset=torch.tensor(100.0), variance=variance,
...     gain=torch.tensor(2.0))
>>> clean = torch.full((48, 48), 20.0)
>>> noise = variance.sqrt() * torch.randn(48, 48, generator=g)
>>> raw = 100 + 2 * torch.poisson(clean, generator=g) + noise
>>> est = NCS(numerical_aperture=1.4, wavelength=0.7, pixel_size=0.1)
>>> out = est.fit(init=sensor).apply(raw)
>>> before = ((raw - 100) / 2 - clean).square().mean()
>>> bool((out - clean).square().mean() < before)
True

Configure the noise correction.

Parameters:

Name Type Description Default
numerical_aperture float

NA of the objective (required).

None
wavelength float

Detection wavelength λ (required).

None
pixel_size float

Pixel size in the object plane, in the unit of wavelength (required).

None
alpha float

Weight α of the noise contribution. Default: 0.2 (the paper).

None
mask (otf - weighted, noise - only)

OTF mask (see ncs_mask). Default: "otf-weighted" (the paper's recommendation).

"otf-weighted"
segment int

Segment size M. Default: 16 (not in the paper, which recommends 8–32).

None
units (electrons, adu)

Units of the result. Default: "electrons" (the paper).

"electrons"
max_iter int

Maximum number of Newton iterations per segment. Default: 50.

None
tol float

Tolerance on max |∇f|. Default: relative to the signal (see ncs_solve).

None
block sequence of int or None

Core block size per spatial axis (default: from the memory budget, with a working memory of about 35·(M + 2)²/M² times the block). The result does not depend on it, to rounding.

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

fit

fit(data=None, *, layout=None, init=None, **kwargs)

Set the camera maps.

Parameters:

Name Type Description Default
data array - like

Not read; only its layout is recorded.

None
layout Layout
None
init SensorEstimate or Estimator

Offset, read-noise variance and gain (scalars or maps), or an estimator holding such an estimate (e.g. a fitted SCMOSCalibration).

None
**kwargs object

Ignored (callback, verbose).

{}

Returns:

Type Description
Estimator

self

halo

halo()

Halo of the block-wise processing, 2M − 1.

Returns:

Type Description
int

ACsN

ACsN(*, na=None, wavelength=None, pixel_size=None, ratio=None, sigma_fit=None, camera_cutoff=None, hotspot=None, sigma=None, block=None, faithful=True, dtype=None, device=None, layout=None)

Bases: Estimator

ACsN: automatic correction of sCMOS-related noise.

Applies acsn to each frame (the two spatial axes of the layout; other axes are samples or groups) with the offset and gain maps of a SensorEstimate given to fit (for instance that of SCMOSCalibration, the calibration of the paper's Methods, Eq. (2)). The noise level σ_N is estimated from each frame, which makes the processing frame-independent.

apply streams batches of frames; each frame is loaded whole (the noise estimate needs its FFT) and its sparse filter runs in blocks with a halo (halo). The estimated σ_N of every frame is kept in sigma_ (shape (*group, *sample), electrons), and its no-reference quality score (the "image quality check" of Supplementary Table 5; quality_score) in quality_ (NaN for frames smaller than 11 × 11). The output is in electrons.

Note

Faithful mode is the paper (ratio="1d", sigma_fit="histogram", hotspot=False, sigma=None), with camera_cutoff=1.1 from the ACsN code (not in the paper). faithful=False selects ratio="area", the exact white-noise ratio, and hotspot=True. block does not change the result. The variance map of the estimate is not used: σ_N comes from the frame.

sigma_ in faithful mode is not the noise level

The 1-D ratio of Supplementary Eq. (11) overestimates the noise of a 2-D frame. In faithful mode sigma_ is about 1.2 to 1.9 times the standard deviation of the noise, depending on f_c/f̄ (1.35 for f_c at 0.8 times the Nyquist frequency). It is the level the filter uses, not a measurement of the read noise or the SNR; ratio="area" (faithful=False) gives the noise standard deviation.

Hot pixels

With hotspot=False (faithful mode), a single hot pixel or cosmic ray makes σ_N, and so the whole filter, wrong (see acsn). On real camera data use hotspot=True (as faithful=False does), or correct hot pixels first.

References

  1. Mandracchia B, Hua X, Guo C, Son J, Urner T, Jia S. Fast and accurate sCMOS noise correction for fluorescence microscopy. Nat Commun 11:94, 2020. doi:10.1038/s41467-019-13841-8
  2. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
BibTeX
@article{mandracchia2020fast,
  author  = {Mandracchia, Biagio and Hua, Xuanwen and
             Guo, Changliang and Son, Jeonghwan and
             Urner, Tara and Jia, Shu},
  title   = {Fast and accurate {sCMOS} noise correction for
             fluorescence microscopy},
  journal = {Nature Communications},
  volume  = {11}, pages = {94},
  year    = {2020}, doi = {10.1038/s41467-019-13841-8}
}
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}

Examples:

>>> import torch
>>> from optix.denoise import ACsN
>>> from optix.estimates import SensorEstimate
>>> y = torch.arange(48.0).expand(48, 48)
>>> sensor = SensorEstimate(
...     offset=torch.tensor(100.0),
...     variance=torch.tensor(4.0),
...     gain=torch.tensor(2.0),
... )
>>> raw = 100 + 2 * torch.poisson(y) + 2 * torch.randn(48, 48)
>>> den = ACsN(na=1.4, wavelength=0.7, pixel_size=0.1)
>>> den = den.fit(init=sensor).apply(raw)
>>> den.shape
torch.Size([48, 48])

Configure the denoiser.

Parameters:

Name Type Description Default
na float

Numerical aperture of the detection objective.

None
wavelength float

Emission wavelength, in the unit of pixel_size (e.g. µm).

None
pixel_size float

Pixel size in the image plane (camera pixel divided by the magnification).

None
ratio ('1d', area)

σ_N/σ_c: Supplementary Eq. (11) ("1d", the paper) or its exact 2-D value for white noise ("area", extension; the default with faithful=False).

"1d"
sigma_fit (histogram, std)

σ_c from a Gaussian fit to the histogram of |h| (the ACsN code, default) or the RMS of h (extension).

"histogram"
camera_cutoff float

Camera cutoff f̄ in units of the Nyquist frequency (default 1.1, from the ACsN code, not in the paper). The pixel size must be below λ/(4·NA)·camera_cutoff.

None
hotspot bool

Extension: hot-pixel removal of the ACsN code. Default False in faithful mode, True with faithful=False.

None
sigma float

Extension: known σ_N in electrons, for every frame.

None
block sequence of int

Core block size of the sparse filter (default: from the memory budget). The result does not depend on it.

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

halo

halo()

Halo of the blocks of the sparse filter inside a frame.

See acsn_halo: frames cannot be tiled with it, since σ_N and the [0, 255] mapping come from the whole frame.

Returns:

Type Description
int

fit

fit(data=None, *, layout=None, init=None, **kwargs)

Set the camera calibration.

Parameters:

Name Type Description Default
data array - like

Only its layout is recorded: the noise is estimated frame by frame in apply.

None
layout Layout
None
init SensorEstimate or Estimator

Offset β (ADU) and gain γ (ADU per electron), scalars or (*group, *spatial) maps. Without it, β = 0 and γ = 1 (data already in electrons).

None
**kwargs object

Ignored (callback, verbose).

{}

Returns:

Type Description
Estimator

self

PURELET

PURELET(*, sigma=None, gain=None, offset=None, levels=None, reliability=None, sharpness=None, ndim=None, pixelwise=None, block=None, faithful=True, dtype=None, device=None, layout=None)

Bases: Estimator

PURE-LET denoising of Poisson-Gaussian noise (Luisier et al. 2011).

Applies pure_let to each image (the spatial axes of the layout; other axes are samples or groups, and each frame gets its own LET coefficients). The noise parameters are a SensorEstimate given to fit (gain α, offset δ, read variance in ADU²), or sigma, gain and offset given at construction.

apply reads the data twice, in blocks with a periodic halo of pure_let_halo pixels (wrapped around the image, the boundary condition of the paper): the first pass accumulates, per frame, the 2·(2^d − 1)·J × 2·(2^d − 1)·J linear system of PURE (PureSums: sums over pixels and coefficients, so blocks give the whole-image system), which is solved once per frame; the second pass reconstructs each block with the frame's coefficients. Arrays larger than memory (zarr, memmap) thus give the whole-image result.

Note

Faithful mode is the UWT PURE-LET of the paper (Haar, Section III), with its T = 10 and κ = 100 (called k in the paper). pixelwise (per-pixel noise maps), ndim ≠ 2 (volumes, space-time stacks) and other values of reliability or sharpness are extensions; levels (not given in the paper) and block do not change the method. Maps in the SensorEstimate need pixelwise=True. Every spatial axis needs at least 2^J samples (see pure_let).

References

  1. Luisier F, Blu T, Unser M. Image denoising in mixed Poisson–Gaussian noise. IEEE Trans Image Process 20(3):696–708, 2011. doi:10.1109/TIP.2010.2073477
BibTeX
@article{luisier2011image,
  author  = {Luisier, Florian and Blu, Thierry and
             Unser, Michael},
  title   = {Image denoising in mixed {Poisson--Gaussian}
             noise},
  journal = {IEEE Transactions on Image Processing},
  volume  = {20}, number = {3}, pages = {696--708},
  year    = {2011}, doi = {10.1109/TIP.2010.2073477}
}

Examples:

>>> import torch
>>> from optix.denoise import PURELET
>>> g = torch.Generator().manual_seed(0)
>>> clean = 20 + 15 * torch.sin(torch.arange(64.0) / 5).expand(64, 64)
>>> noisy = torch.poisson(clean, generator=g)
>>> noisy = noisy + 2 * torch.randn(64, 64, generator=g)
>>> den = PURELET(sigma=2.0).fit().apply(noisy)
>>> bool((den - clean).square().mean() < (noisy - clean).square().mean())
True

Configure the denoiser.

Parameters:

Name Type Description Default
sigma float

Standard deviation of the Gaussian (read) noise, in data units; 0 for pure Poisson noise. Omit it to give a SensorEstimate to fit instead.

None
gain float

α, data units per photon (default 1). Ignored with a SensorEstimate.

None
offset float

δ, in data units (default 0). Ignored with a SensorEstimate.

None
levels int

Number of levels J of the wavelet transform (not given in the paper). Default: 4.

None
reliability float

T of Section III-D (paper: 10).

None
sharpness float

κ of the smooth absolute value tanh(κ·w̄)·w̄ of Section III-C (called k there; paper: 100).

None
ndim int

Extension when ≠ 2: number of spatial axes transformed (3 for volumes, or for space-time with time declared spatial in the layout). Default: 2.

None
pixelwise bool

Extension: use the maps of a SensorEstimate (per-pixel gain, offset and read variance of sCMOS cameras) pixel by pixel. Default: False.

None
block sequence of int or None

Core block size per spatial axis (default: from the memory budget). The result does not depend on it.

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

fit

fit(data=None, *, layout=None, init=None, **kwargs)

Set the noise model.

The LET coefficients are not fitted here: PURE is minimised for each frame of the data given to apply.

Parameters:

Name Type Description Default
data array - like

Only its layout is recorded.

None
layout Layout
None
init SensorEstimate or Estimator

Noise parameters (gain α in ADU per photon, offset δ, read variance in ADU²; scalars, or maps with pixelwise=True). Default: sigma, gain and offset of the constructor.

None
**kwargs object

Ignored (callback, verbose).

{}

Returns:

Type Description
Estimator

self

halo

halo()

Halo of the block-wise processing, 2^J − 1.

Returns:

Type Description
int

NLMeans

NLMeans(*, sigma=None, h=None, patch=None, search=None, a=None, kernel_norm=None, ndim=None, bias_correction=None, inverse=None, block=None, faithful=True, dtype=None, device=None, layout=None)

Bases: _BlockMatching

Non-local means denoising (Buades, Coll & Morel 2005).

Applies nl_means to each image (the spatial axes of the layout; other axes are samples or groups). The noise is white Gaussian with a known σ, or Poisson-Gaussian with the parameters of a SensorEstimate, as in BM3D: the image is denoised after the generalised Anscombe transform with σ = 1 (so h defaults to 10 in stabilised units), and transformed back by its exact unbiased inverse; maps of the estimate apply pixel by pixel. The variance stabilisation is not in the paper.

fit only sets the noise model (NL-means needs no intensity range). apply streams blocks with the halo of nl_means_halo, so arrays larger than memory give the whole-image result.

Note

Faithful mode is the setting of Section 5 of the paper (2-D, 7 × 7 patches, 21 × 21 search window, h = 10σ), with the kernel normalisation kernel_norm="mean", a departure from the paper that repairs an inconsistency between its Sections 3 and 5 (see nl_means). h, patch, search, ndim=3, bias_correction and kernel_norm="sum" (the normalisation the paper implies) make is_faithful false; a is a choice the paper leaves open, and inverse and block do not change the method. The default h is 10σ·√(K/49), K = patchᵈ (see default_h).

References

  1. Buades A, Coll B, Morel J-M. A non-local algorithm for image denoising. IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05), vol. 2, 2005. doi:10.1109/CVPR.2005.38
BibTeX
@inproceedings{buades2005nonlocal,
  author    = {Buades, Antoni and Coll, Bartomeu and
               Morel, Jean-Michel},
  title     = {A non-local algorithm for image denoising},
  booktitle = {IEEE Computer Society Conference on Computer
               Vision and Pattern Recognition (CVPR'05)},
  volume    = {2},
  year      = {2005},
  doi       = {10.1109/CVPR.2005.38}
}

Examples:

>>> import torch
>>> from optix.denoise import NLMeans
>>> clean = torch.linspace(0, 255, 48).expand(48, 48)
>>> noisy = clean + 20 * torch.randn(48, 48)
>>> den = NLMeans(sigma=20).fit().apply(noisy)
>>> bool((den - clean).square().mean() < (noisy - clean).square().mean())
True

Configure the denoiser.

Parameters:

Name Type Description Default
sigma float

Standard deviation σ of white Gaussian noise, in data units. Omit it to give a SensorEstimate to fit instead.

None
h float

Extension: filtering parameter h (data units; stabilised units with a SensorEstimate). Default: 10σ·√(K/49), K = patchᵈ, that is 10σ for 7 × 7 patches (Section 5).

None
patch int

Extension: odd side of the patches (paper: 7).

None
search int

Extension: odd side of the search window (paper: 21).

None
a float

Standard deviation of the patch kernel G_a, in pixels (not specified in the paper). Default: (patch − 1)/4.

None
kernel_norm (mean, sum)

Normalisation of G_a: mean 1 over the patch (default, a departure from the paper) or sum 1 (implied by the paper, not faithful here); see patch_kernel.

"mean"
ndim (2, 3)

Spatial dimensions of the layout; 3 (volumes) is an extension. Default: 2.

2
bias_correction bool

Extension: subtract 2σ²·∑G_a, the expected distance between two patches of noise, from the patch distances, clamped at 0 (not in the paper). Default: False.

None
inverse (exact, closed - form, asymptotic, algebraic)

Inverse of the Anscombe transform (see inverse_anscombe). Default: "exact".

"exact"
block sequence of int or None

Core block size per spatial axis (default: from the memory budget). The result does not depend on it.

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

fit

fit(data=None, *, layout=None, init=None, **kwargs)

Set the noise model.

Gaussian noise: sigma given at construction. Poisson-Gaussian noise: init is a SensorEstimate (or an estimator holding one): the data are stabilised by the generalised Anscombe transform, denoised with σ = 1 and transformed back by the inverse selected by inverse. Maps of the estimate (of shape (*group, *spatial) or broadcastable to it) are applied pixel by pixel, cropped to each streamed block.

Parameters:

Name Type Description Default
data array - like

Not read; only its layout is recorded.

None
layout Layout
None
init SensorEstimate or Estimator

Noise parameters (gain α, offset μ, read variance σ²; scalars or maps).

None
**kwargs object

Ignored (callback, verbose).

{}

Returns:

Type Description
Estimator

self

halo

halo()

Halo of the block-wise processing.

Returns:

Type Description
int

ROF

ROF(*, sigma=None, lam=None, data_term=None, weights=None, axis_weights=None, ndim=None, max_iter=None, tol=None, inverse=None, faithful=True, dtype=None, device=None, layout=None)

Bases: Estimator

Total-variation denoising of Rudin, Osher & Fatemi (1992).

The image u is the solution of (Eqs. 2.3a–c, discretised as in Eqs. 2.9a and 2.4b: forward differences, Neumann boundaries)

minimise TV(u) = ∑ⱼ ‖(∇u)ⱼ‖₂  subject to  ∑ⱼ (uⱼ − fⱼ)² ≤ Mσ²,

f the noisy image of M pixels and σ the standard deviation of its white Gaussian noise. The mean constraint (2.3b) holds at the solution (TV is invariant to an offset and the mean of f minimises the residual). The equality of Eq. 2.3c is relaxed to an inequality, which is the same problem unless a constant image is feasible (σ² at least the variance of f). Then every feasible constant is a minimiser, so the solution is not unique; the mean of f is returned.

The paper reaches the minimiser by marching the Euler–Lagrange equation (2.5a) in time with the gradient-projection multiplier λ(t) of Eq. 2.6 (scheme 2.8–2.9). Here the same model is solved to a prescribed primal–dual gap with the convergent primal–dual method of Chambolle & Pock (2011) (tv_denoise); the multiplier λ of the solution is available from that function. Each image (the ndim spatial axes of the layout) is solved whole; the other axes are streamed one image at a time. The solver needs about 2d + 5 image sizes of working memory (d = ndim; three times that with the KL data term), which must fit in the memory budget of config, else apply raises a MemoryError. The iteration count and the final gap of each image are appended to history.extras["iterations"] and history.extras["gap"]; one RuntimeWarning per apply reports images stopped at max_iter above tol, with the worst gap.

Poisson-Gaussian noise: give a SensorEstimate to fit. With the Gaussian data term the data are stabilised by the generalised Anscombe transform (noise of unit variance, σ = 1) and transformed back by the inverse selected by inverse, as in BM3D; with the KL data term they are converted to electrons, (f − offset)/gain, with the read variance variance/gain² of the shifted-Poisson likelihood, and converted back. Maps of the estimate apply pixel by pixel.

Faithful mode and extensions

Faithful mode is the constrained Gaussian model in 2-D with the noise level sigma (or σ = 1 after the variance-stabilising transform, which is not in the paper). Extensions (off by default): lam (penalised data term λ/2·∑(u − f)² instead of the constraint), data_term="kl" (Poisson likelihood λ∑(u − f log u), with lam), weights (pixel weights ω of the data term), axis_weights (weights of the differences per axis, for example a smaller weight along an anisotropic z axis) and ndim=3 (3-D total variation). The noise constraint is ∑(u − f)² ≤ Mσ², the residual variance of Eqs. 2.2c and 2.7d; Eqs. 2.3c and 2.6 carry an extra factor ½. There is no recommended preset, so faithful=False changes nothing.

References

  1. Rudin LI, Osher S, Fatemi E. Nonlinear total variation based noise removal algorithms. Physica D 60(1–4):259–268, 1992. doi:10.1016/0167-2789(92)90242-F
  2. Chambolle A, Pock T. A first-order primal-dual algorithm for convex problems with applications to imaging. J Math Imaging Vis 40(1):120–145, 2011. doi:10.1007/s10851-010-0251-1
BibTeX
@article{rudin1992nonlinear,
  author  = {Rudin, Leonid I. and Osher, Stanley and
             Fatemi, Emad},
  title   = {Nonlinear total variation based noise removal
             algorithms},
  journal = {Physica D: Nonlinear Phenomena},
  volume  = {60}, number = {1--4}, pages = {259--268},
  year    = {1992}, doi = {10.1016/0167-2789(92)90242-F}
}
@article{chambolle2011first,
  author  = {Chambolle, Antonin and Pock, Thomas},
  title   = {A first-order primal-dual algorithm for convex
             problems with applications to imaging},
  journal = {Journal of Mathematical Imaging and Vision},
  volume  = {40}, number = {1}, pages = {120--145},
  year    = {2011}, doi = {10.1007/s10851-010-0251-1}
}

Examples:

>>> import torch
>>> from optix.denoise import ROF
>>> clean = torch.zeros(48, 48)
>>> clean[12:36, 12:36] = 100
>>> noisy = clean + 20 * torch.randn(48, 48)
>>> den = ROF(sigma=20).fit().apply(noisy)
>>> bool((den - clean).square().mean() < (noisy - clean).square().mean())
True

Configure the denoiser.

Parameters:

Name Type Description Default
sigma float

Standard deviation σ of white Gaussian noise, in data units (constrained model). Omit it to give a SensorEstimate to fit instead (the stabilised data have σ = 1, and fit raises if both are given), or with lam.

None
lam float

Extension: weight λ > 0 of a penalised data term instead of the noise constraint (required by data_term="kl").

None
data_term (gaussian, kl)

Data term. Default: "gaussian"; "kl" (extension) is the Poisson (Kullback–Leibler) likelihood, on counts or, with a SensorEstimate, on electrons.

"gaussian"
weights Tensor

Extension: pixel weights ω > 0 of the data term, of shape (*group, *spatial) or broadcastable to it.

None
axis_weights sequence of float

Extension: weight wₐ > 0 of the differences along each spatial axis (layout order). Default: 1.

None
ndim (2, 3)

Number of spatial axes. Default: 2; 3 is an extension.

2
max_iter int

Maximum number of solver iterations (not in the paper). Default: 2000.

None
tol float

Tolerance on the relative primal–dual gap (not in the paper). Default: 10⁻⁴.

None
inverse (exact, closed - form, asymptotic, algebraic)

Inverse of the Anscombe transform. Default: "exact".

"exact"
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

fit

fit(data=None, *, layout=None, init=None, **kwargs)

Set the noise model; the data are not read.

Parameters:

Name Type Description Default
data array - like

Only its layout is recorded.

None
layout Layout
None
init SensorEstimate or Estimator

Noise parameters (gain α, offset μ, read variance σ²; scalars or maps) for Poisson-Gaussian data.

None
**kwargs object

Ignored (callback, verbose).

{}

Returns:

Type Description
Estimator

self

Transforms

Denoising.

Block matching and collaborative filtering: BM3D for images (Dabov et al. 2007) and BM4D for volumes (Maggioni et al. 2013), for white Gaussian noise or, after the generalised Anscombe transform, Poisson-Gaussian noise; non-local means (Buades, Coll & Morel 2005); PURE-LET (Luisier et al. 2011) for mixed Poisson-Gaussian noise; ACsN for sCMOS frames (Mandracchia et al. 2020); total-variation denoising (Rudin, Osher & Fatemi 1992). Building blocks (transforms, block matching, the two filtering stages, the patch distances, the PURE-LET system, the total-variation solver) are in optix.denoise.utils.

NCS (Liu et al. 2017) corrects the pixel-dependent noise of sCMOS cameras by MAP estimation with the camera's offset, gain and variance maps and a penalty on the spectrum outside the optical transfer function; its building blocks (mask, cost, solver, segments) are also in optix.denoise.utils.

bm3d

bm3d(data, sigma, *, data_range=None, profile='normal', output='final', search=None, step=None, keep_dc=False)

BM3D denoising of images with white Gaussian noise.

Model (Dabov et al. 2007): z(x) = y(x) + η(x), η ~ 𝒩(0, σ²) i.i.d. Each image is denoised in two steps, each made of grouping by block matching, collaborative filtering and aggregation.

  1. Basic estimate. For each reference block Z_{x_R} (N₁ × N₁, every N_step pixels), block matching in an N_S × N_S window collects the blocks with

    d(Z_{x_R}, Z_x) = ‖Υ′(T₂D(Z_{x_R})) − Υ′(T₂D(Z_x))‖₂²/N₁² ≤ τ_match

(Eqs. (4)-(5); Υ′ hard-thresholds at λ₂D·σ), at most N₂ of them, the closest first. The group is transformed by T₃D = T₂D followed by a 1-D Haar transform along the group, hard-thresholded at λ₃D·σ, and transformed back (Eq. (6)). Its blocks are aggregated with the weight w = 1/(σ²·N_har) (Eq. (10); N_har retained coefficients) times a Kaiser window (Eq. (12)). 2. Final estimate. Block matching in the basic estimate ŷ (d = ‖Ŷ_{x_R} − Ŷ_x‖₂²/N₁² < τ_match, Eq. (7)) gives two groups, noisy and basic; the noisy one is shrunk by the empirical Wiener coefficients W = |T₃D(Ŷ)|²/(|T₃D(Ŷ)|² + σ²) (Eqs. (8)-(9)) and aggregated with w = σ⁻²‖W‖₂⁻² (Eq. (11)).

The parameters are those of the "Normal Profile" of Table I, in 8-bit units:

T₂D N₁ N₂ N_step N_S β λ₂D λ₃D τ_match
step 1, σ ≤ 40 bior1.5 8 16 3 39 2 0 2.7 2500
step 2, σ ≤ 40 DCT 8 32 3 39 2 400
step 1, σ > 40 DCT 12 16 4 39 2 2 2.8 5000
step 2, σ > 40 DCT 11 32 6 39 2 3500

The search is exhaustive (N_FS = 1, no predictive search). The group size is rounded down to a power of two (Section IV-B), and the blocks are ordered by distance, the reference first.

The DC coefficient of a group is thresholded like the others (Eq. (6) has no exception, and Eq. (10) has a case for groups with no coefficient left). The result is therefore not invariant to an offset of the intensities: the DC of a group of m blocks, √(m·N₁²) times its mean, is removed when the mean is below λ₃D·σ/√(m·N₁²) in absolute value (about 0.08·σ for m = 16), which occurs on a background close to 0. On a filament phantom with a background of 0 (96² pixels, range [0, 255], σ = 20, search=15), denoising z and z + 100 differs by up to 22 grey levels in the basic estimate and 25 in the final one (0 and 2.5 with keep_dc=True). keep_dc=True keeps the DC, as BM4D does: the basic estimate is then invariant to an offset, and the final one nearly so (the Wiener gain of the DC, |θ|²/(|θ|² + σ²), still depends on the mean).

Choices not specified in the paper

  • Intensities are mapped to the paper's 8-bit range: the data and σ are multiplied by 255/data_range (which sets τ_match and the σ > 40 switch), and the result is mapped back. data_range defaults to an estimate of the range of the clean signal, clean_range: max − min of data minus the extent of the noise. Pass the range of the clean signal when it is known.
  • bior1.5 is the periodised full dyadic transform with each basis function scaled to unit norm; see bior15_matrix. At N₁ = 8 the periodisation cancels its outer ±3/256 taps. The distance of step 1 is taken between its coefficients, the literal Eq. (4) (and the paper's footnote 3): T₂D is not orthogonal, so τ_match = 2500 applies to ‖T₂D(Z_{x_R} − Z_x)‖²/N₁², not to the mean squared difference of the pixels.
  • The reference blocks are on a grid of step N_step from the first pixel, plus the last block along each axis so that every pixel is covered; search windows are clipped at the image border; distance ties keep the raster order of the window.
  • The 2-D Kaiser window is the outer product of two 1-D windows of parameter β.
  • Wiener weights use ‖W‖₂² ≥ the smallest positive float.

Extensions

search (N_S) and step (N_step), when given, replace the values of both steps. They trade quality for speed. keep_dc=True never thresholds the DC coefficient of a group in step 1 (as in BM4D), which makes the basic estimate invariant to an offset of the intensities.

Cost and memory

The cost is about N_S²·N₁²/N_step² operations per pixel and step. The spectra of every block are kept (N₁² values per pixel, twice in step 2); block matching and filtering run in batches sized from the memory budget of optix.config. The result at a pixel depends on the data within bm3d_halo pixels, which BM3D uses to stream large arrays in blocks.

The computation is vectorised over batches of reference blocks (gathers, sorts and scatter-adds) and runs on any torch device. On the CPU it is deterministic; on CUDA the aggregation uses atomic additions, so results may differ in the last bits.

References

  1. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
  2. Maggioni M, Katkovnik V, Egiazarian K, Foi A. A nonlocal transform-domain filter for volumetric data denoising and reconstruction. IEEE Trans Image Process 22(1):119–133, 2013. doi:10.1109/TIP.2012.2210725
BibTeX
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}
@article{maggioni2013nonlocal,
  author  = {Maggioni, Matteo and Katkovnik, Vladimir and
             Egiazarian, Karen and Foi, Alessandro},
  title   = {A nonlocal transform-domain filter for volumetric
             data denoising and reconstruction},
  journal = {IEEE Transactions on Image Processing},
  volume  = {22}, number = {1}, pages = {119--133},
  year    = {2013}, doi = {10.1109/TIP.2012.2210725}
}

Parameters:

Name Type Description Default
data Tensor

(..., H, W); each image is denoised separately (floating point; other dtypes are converted to the configured dtype).

required
sigma float

Noise standard deviation σ > 0, in the units of data.

required
data_range float

Intensity range mapped to [0, 255]. Default: clean_range of data.

None
profile normal

Parameter profile of Table I.

"normal"
output (final, basic)

The final estimate (step 2) or the basic estimate (step 1).

"final"
search int

Extension: side N_S of the search window.

None
step int

Extension: step N_step between reference blocks.

None
keep_dc bool

Extension: never threshold the DC coefficient of a group.

False

Returns:

Type Description
Tensor

Of the shape of data.

bm4d

bm4d(data, sigma, *, data_range=None, profile='normal', output='final', search=None, step=None)

BM4D denoising of volumes with white Gaussian noise.

The volumetric extension of bm3d (Maggioni et al. 2013): cubes C of L × L × L voxels are grouped by cube matching,

d(C_{x_i}, C_{x_j}) = ‖C_{x_i} − C_{x_j}‖₂² / L³ ≤ τ_match

(Section II-B.1, Eqs. (2)-(3); no pre-filtering), stacked into 4-D groups and filtered with a separable 4-D transform: hard thresholding at λ₄D·σ, the DC never being thresholded (Eqs. (5)-(6)), with aggregation weight w = 1/(σ²·N_har) (Eq. (8)); then empirical Wiener filtering guided by the hard-thresholding estimate (Section II-B.2, Eqs. (9)-(11)) with w = σ⁻²‖W‖₂⁻² (Eq. (12)). Equation numbers are those of the authors' preprint. There is no Kaiser window. The DC being kept, the hard-thresholding estimate is invariant to an offset of the intensities (the final estimate nearly so: the Wiener gain of the DC depends on the mean). The 4-D transforms are a 3-D bior1.5 (stage 1) or 3-D DCT (stage 2) of each cube, then a 1-D Haar transform along the group, whose size is rounded down to a power of two.

Parameters of Table I (Section III-A; data in [0, 1]):

L M N_step N_S λ₄D τ_match
hard thresholding, normal 4 16 3 11 2.7 2.9
Wiener, normal 4 32 3 11 0.4
hard thresholding, modified 4 32 3 11 2.8 24.6
Wiener, modified 5 32 3 11 6.7

Choices not specified in the paper

  • The values of τ_match in Table I exceed the largest distance of Eq. (2) between cubes in [0, 1] (d ≤ 1), so that read literally nearly every cube would match. They are applied to the sum of squared differences ‖C_{x_i} − C_{x_j}‖₂², that is d ≤ τ_match/L³. In 8-bit units (τ_match·255²/L³) this reading gives the thresholds of BM3D, whose settings the paper reuses (Section III-A):
Table I L τ_match·255²/L³ BM3D (Dabov et al., Table I)
0.4 (Wiener, normal) 4 406 400 (step 2, σ ≤ 40)
6.7 (Wiener, modified) 5 3485 3500 (step 2, σ > 40)
2.9 (hard thr., normal) 4 2946 2500 (step 1, σ ≤ 40)
24.6 (hard thr., modified) 4 24994 none

The two Wiener values, 0.4/64 and 6.7/125, are BM3D's 400/255² and 3500/255² to rounding. * Intensities are mapped to [0, 1] by dividing the data and σ by data_range (default: clean_range of data). * Reference cubes, search windows, ties and weights as in bm3d. Voxels covered by no cube (only with step > L) keep the value of the stage's input, as in Section III-D of the paper. * The weights of hard thresholding never meet the case N_har = 0 of BM3D, since the DC is kept.

Extensions

search (N_S) and step (N_step) replace the values of both stages (Table IV of the paper studies them).

References

  1. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
  2. Maggioni M, Katkovnik V, Egiazarian K, Foi A. A nonlocal transform-domain filter for volumetric data denoising and reconstruction. IEEE Trans Image Process 22(1):119–133, 2013. doi:10.1109/TIP.2012.2210725
BibTeX
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}
@article{maggioni2013nonlocal,
  author  = {Maggioni, Matteo and Katkovnik, Vladimir and
             Egiazarian, Karen and Foi, Alessandro},
  title   = {A nonlocal transform-domain filter for volumetric
             data denoising and reconstruction},
  journal = {IEEE Transactions on Image Processing},
  volume  = {22}, number = {1}, pages = {119--133},
  year    = {2013}, doi = {10.1109/TIP.2012.2210725}
}

Parameters:

Name Type Description Default
data Tensor

(..., D, H, W); each volume is denoised separately.

required
sigma float

Noise standard deviation σ > 0, in the units of data.

required
data_range float

Intensity range mapped to [0, 1]. Default: clean_range of data.

None
profile (normal, modified)

Parameter profile of Table I.

"normal"
output (final, basic)

The final (Wiener) or the hard-thresholding estimate.

"final"
search int

Extension: side N_S of the search cube.

None
step int

Extension: step N_step between reference cubes.

None

Returns:

Type Description
Tensor

Of the shape of data.

bm3d_halo

bm3d_halo(sigma, data_range=255.0, *, profile='normal', output='final', search=None, step=None)

Halo, in pixels, that makes block-wise BM3D exact.

Each step reaches 2·⌊N_S/2⌋ + N₁ − 1 pixels: a pixel is covered by blocks within N₁ − 1 of it, grouped by references within ⌊N_S/2⌋, whose search windows extend ⌊N_S/2⌋ further. The final estimate adds the reach of both steps (90 pixels for σ ≤ 40).

Note

Only the profile depends on σ and data_range, through σ·255/data_range > 40. Without data there is no default range to estimate: data_range defaults to 255, so that sigma is in 8-bit units. For the halo of bm3d with its default range, use BM3D.fit(data) and its halo() method.

Parameters:

Name Type Description Default
sigma float

As in bm3d (they select the profile); data_range defaults to 255.

required
data_range float

As in bm3d (they select the profile); data_range defaults to 255.

required
profile str

As in bm3d.

'normal'
output str

As in bm3d.

'normal'
search str

As in bm3d.

'normal'
step str

As in bm3d.

'normal'

Returns:

Type Description
int

bm4d_halo

bm4d_halo(*, profile='normal', output='final', search=None, step=None)

Halo, in voxels, that makes block-wise BM4D exact.

2·⌊N_S/2⌋ + L − 1 per stage, as in bm3d_halo (26 voxels for the normal profile).

Parameters:

Name Type Description Default
profile str

As in bm4d.

'normal'
output str

As in bm4d.

'normal'
search str

As in bm4d.

'normal'
step str

As in bm4d.

'normal'

Returns:

Type Description
int

ncs

ncs(data, sensor, *, numerical_aperture, wavelength, pixel_size, alpha=0.2, mask='otf-weighted', segment=16, units='electrons', max_iter=50, tol=None)

NCS: noise correction of sCMOS images (Liu et al. 2017).

Each pixel i of an sCMOS camera has its own offset oᵢ, gain gᵢ (ADU per electron) and read-noise variance σᵢ² (ADU²). The algorithm (Supplementary Note 2, Supplementary Fig. 1) is:

  1. Pre-correction (Supp. Note 3, Eq. 1): Dᵢ = (Aᵢ − oᵢ)/gᵢ for the raw image A, with Dᵢ ← 10⁻⁶ where Dᵢ ≤ 0 (Supp. Notes 2 and 6), and γᵢ = σᵢ²/gᵢ² (Supp. Note 6).
  2. Segmentation (Supp. Note 7): the image is cut into segments of M × M pixels, each padded by one pixel on every side to (M + 2) × (M + 2): with the adjacent pixel of the image, or with the pixel itself at the border of the image. The pad is dropped from the result.
  3. Estimation: in each padded segment, μ minimises

    f(μ) = LL_s(μ) + α σ_N(μ),

from μ⁰ = D. LL_s is the simplified negative log-likelihood (Supp. Note 6, Eqs. 5–7),

   LL_s(μ) = ∑ᵢ μᵢ − (Dᵢ + γᵢ) ln(μᵢ + γᵢ),

of the paper's approximation of the Poisson–Gaussian pixel model: Dᵢ + γᵢ is taken as Poisson with mean μᵢ + γᵢ (Eq. 5), with Stirling's formula for Γ(Dᵢ + γᵢ + 1) (Eq. 6) and the constants dropped (Eq. 7). σ_N is the noise contribution near and outside the OTF support (Supp. Note 4, Eqs. 2–3),

   σ_N(μ) = ∑_k |μ̂(k) m(k)|²,

with μ̂ the DFT of the segment normalised by 1/L (unitary) and m the OTF mask (ncs_mask), a raised-cosine high-pass filter around the cut-off 2NA/λ (Supp. Note 5, Eq. 4). α = 0.2 (Supp. Note 2, Fig. SS6).

The output is μ, in electrons (the paper's "effective photon count"), or with units="adu" μ·g + o.

Symbols: μ, D, γ, σ_N, LL_s, f and α are the paper's; they are x, ỹ, σ̃², E_N, LL_s, J and α in the notation of optix, with m the OTF mask (the paper's M) and M the segment size.

Negative estimates

The cost is defined on μᵢ + γᵢ > 0, so μᵢ is bounded below by −γᵢ only, not by 0. Estimates can be negative at pixels of large read noise next to brighter neighbours: on the synthetic scene of the documentation the minimum is −7.5 e⁻ with the noise-only mask (0.86 e⁻ with the OTF-weighted mask). Clip the result before taking a logarithm or a square root.

Choices not specified in the paper

  • The optimiser: damped Newton with conjugate gradients, run to the tolerance (ncs_solve). The paper uses "a generic minimization routine such as fminunc", reports that the regression converges within 20 iterations (Supp. Note 2), and its software runs 15 iterations by default, with at least 10 recommended (Supp. Note 13). The result is the minimiser of the paper's cost when every segment converges; a RuntimeWarning gives the number of segments that did not.
  • segment M = 16, in the recommended range 8–32 (Supp. Notes 2 and 13). When M does not divide the image, the last segment along an axis takes the remaining pixels (segment_bounds).
  • Eq. (4) prints the transition band of the mask with ½ + ½ cos; the continuous high-pass ½ − ½ cos is used (see raised_cosine).
  • Segments need not be square or of even size; the frequencies of each axis are those of Eq. (2) for its own length.

Streaming

Segments are independent, and a segment depends only on the data of the segment and of its pad. The result at a pixel therefore depends on the data within ncs_halo(segment) = 2M − 1 pixels, and NCS streams large arrays in blocks with this halo, segmenting on the grid of the whole image. The block-wise result agrees with the whole-image one to rounding, not bitwise: a segment is solved in batches of different sizes.

References

  1. Liu S, Mlodzianoski MJ, Hu Z, Ren Y, McElmurry K, Suter DM, Huang F. sCMOS noise-correction algorithm for microscopy images. Nat Methods 14(8):760–761, 2017. doi:10.1038/nmeth.4379
BibTeX
@article{liu2017scmos,
  author  = {Liu, Sheng and Mlodzianoski, Michael J. and
             Hu, Zhenhua and Ren, Yuan and McElmurry, Kristi
             and Suter, Daniel M. and Huang, Fang},
  title   = {{sCMOS} noise-correction algorithm for
             microscopy images},
  journal = {Nature Methods},
  volume  = {14}, number = {8}, pages = {760--761},
  year    = {2017}, doi = {10.1038/nmeth.4379}
}

Parameters:

Name Type Description Default
data Tensor

Raw images A in ADU, (..., H, W); each image is corrected separately (other dtypes are converted to the configured floating dtype).

required
sensor SensorEstimate

offset (ADU), variance (ADU²) and gain (ADU per electron): scalars or maps broadcasting to data.

required
numerical_aperture float

NA of the objective.

required
wavelength float

Detection wavelength λ.

required
pixel_size float

Pixel size in the object plane, in the unit of wavelength.

required
alpha float

Weight α of the noise contribution (paper: 0.2).

0.2
mask (otf - weighted, noise - only)

OTF mask (paper default: "otf-weighted"); a callable of k_r is a user-defined radial mask.

"otf-weighted"
segment int

Segment size M (not in the paper: 16).

16
units (electrons, adu)

Units of the result (paper: electrons).

"electrons"
max_iter int

Maximum number of Newton iterations per segment.

50
tol float

Tolerance on max |∇f| (default: relative to the signal, see ncs_solve).

None

Returns:

Type Description
Tensor

The corrected images, of the shape of data.

Raises:

Type Description
ValueError

If the data or the maps are not finite, or a gain or a variance is not positive.

Warns:

Type Description
RuntimeWarning

Once per call, if segments did not converge, or if the mask of a segment is zero everywhere.

ncs_halo

ncs_halo(segment=16)

Halo, in pixels, that makes block-wise NCS exact: 2M − 1.

A segment meeting a block has at most 2M − 1 pixels (the last one of an axis takes the remainder; see segment_bounds) and a pad of one pixel, so it reaches 2M − 1 pixels beyond the block.

Parameters:

Name Type Description Default
segment int

Segment size M.

16

Returns:

Type Description
int

acsn

acsn(data, na, wavelength, pixel_size, *, offset=0.0, gain=1.0, sigma=None, ratio='1d', sigma_fit='histogram', camera_cutoff=1.1, hotspot=False, block=None)

ACsN denoising of sCMOS frames (Mandracchia et al. 2020).

Each frame is processed independently, in three steps (Supplementary Note 2, Table 5):

  1. Fixed-pattern noise. With the camera model Z_p = γ_p·{Pois(S_p) + 𝒩(0, σ_R)} + β_p (Eq. (1); Supplementary Eq. (3)), the offset map β and the gain map γ (ADU per electron), from a one-time calibration, give M_p = (Z_p − β_p)/γ_p (Supplementary Eq. (4)), in electrons.
  2. Noise estimation. The readout and shot noise of M are modelled as one white Gaussian noise of variance σ_N² = σ_R² + σ_G² (Supplementary Eq. (5)). The signal lies within the OTF, of radius f_c = 2·NA/λ, so the high-pass image h = F⁻¹[F(M)·𝟙(|f| > f_c)] holds noise only. Its standard deviation σ_c gives σ_N = √(f̄/(f̄ − f_c))·σ_c, f̄ the camera cutoff (Supplementary Eqs. (6)-(11); acsn_noise). The pixel size must be below λ/(4·NA)·camera_cutoff, so that f_c < f̄.
  3. Sparse filtering. Collaborative filtering of BM3D type with the parameters of acsn_profile (Supplementary Note 2.4): 8 × 8 patches grouped by the distance ‖P − Q‖₂²/k² ≤ 2500 (Eq. (12)) in a 19 × 19 window, at most 8 per group, hard thresholding at 4·σ_N of the 3-D spectrum (Eqs. (13)-(14)), aggregation with weights 1/N_P (Eq. (15)); then grouping on that intermediate image and empirical Wiener filtering, c_P = |τ(𝒫)|²/(|τ(𝒫)|² + σ_N²) (Eqs. (16)-(17)).

The result is the denoised M, in electrons (ADU/gain, offset removed).

Hot pixels

With hotspot=False (faithful mode), a single hot pixel or cosmic ray makes σ_N, and so the whole filter, wrong: the 10 bins of the histogram span the range of |h|, which one outlier stretches, and the same pixel sets the maximum of the [0, 255] mapping. On a 128 × 128 test frame, raising one pixel by 200 e⁻ makes σ_N 1.4 times too large, and by 1000 e⁻ 6 times. On real camera data use hotspot=True, or correct hot pixels first.

Differences from BM3D (Dabov et al. 2007)

The engine is that of bm3d, with the ACsN parameters: a 19 × 19 search window (BM3D: 39), at most 8 patches per group (16 and 32), λ = 4.0 (2.7), the hard-threshold stage matched on pixels rather than on bior1.5 coefficients, weights 1/N_P (1/(σ²·N_P), which differs only in the weight of a group with no coefficient left), the same τ_match = 2500 for every σ (BM3D switches profile for σ > 40) and no Kaiser window.

Choices not specified in the paper

  • From the ACsN code (BSD-3), not in the paper: σ_c is fitted to the histogram of |h| (see sigma_from_highpass); the filter outside the OTF is an ideal step; f̄ is 1.1 times the Nyquist frequency 1/(2Δ) (camera_cutoff=1.1); each frame is mapped to [0, 255] by its minimum and maximum before the sparse filter (the paper's τ_match and λ are in 8-bit units).
  • σ_N is always scaled with the frame by the [0, 255] mapping; the code scales it only when the range of the frame exceeds 255.
  • The transforms are those of BM3D's normal profile. The Wiener stage departs from the paper's "the same as the first one": it takes BM3D's τ_match = 400, DCT and strict test (see acsn_profile).
  • The code clamps the gain map to ≥ 1 and M to > 0; neither is done here (in optix the gain is in ADU per electron and may be below 1). The code also clips the filter radius at Nyquist and takes |f̄ − f_c|, so it runs on under-sampled frames; here they raise a ValueError.

Extensions

  • ratio="area" replaces the 1-D ratio of Supplementary Eq. (11) by its exact value for white noise over the 2-D frequencies of the frame (see noise_ratio); on white noise the 1-D formula overestimates σ_N by 1.35 for f_c at 0.8 times the Nyquist frequency (1.58 with camera_cutoff=1).
  • sigma_fit="std": σ_c is the RMS of h.
  • sigma: a known σ_N (electrons) replaces the estimate.
  • hotspot=True: the hot-pixel removal of the ACsN code (BSD-3; on by default there, not in the paper): pixels whose |h| exceeds mean(|h|) + 3·sd(|h|) are replaced by their 3 × 3 median, and the high-pass image is recomputed for the noise estimate.
  • The video filtering of Supplementary Note 2.5 (a further spatio-temporal grouping along motion trajectories, run when temporal_psnr is below 35 dB) is not implemented.

Cost and memory

The noise estimate needs the FFT of the whole frame. The sparse filter runs on blocks of the frame with a halo of 50 pixels (acsn_halo), sized from the memory budget (or block); the result does not depend on the blocks. ACsN budgets about 16 frame-sized arrays of the frame's dtype per frame being processed, for the noise estimate and the quality score.

References

  1. Mandracchia B, Hua X, Guo C, Son J, Urner T, Jia S. Fast and accurate sCMOS noise correction for fluorescence microscopy. Nat Commun 11:94, 2020. doi:10.1038/s41467-019-13841-8
  2. Dabov K, Foi A, Katkovnik V, Egiazarian K. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Trans Image Process 16(8):2080–2095, 2007. doi:10.1109/TIP.2007.901238
BibTeX
@article{mandracchia2020fast,
  author  = {Mandracchia, Biagio and Hua, Xuanwen and
             Guo, Changliang and Son, Jeonghwan and
             Urner, Tara and Jia, Shu},
  title   = {Fast and accurate {sCMOS} noise correction for
             fluorescence microscopy},
  journal = {Nature Communications},
  volume  = {11}, pages = {94},
  year    = {2020}, doi = {10.1038/s41467-019-13841-8}
}
@article{dabov2007image,
  author  = {Dabov, Kostadin and Foi, Alessandro and
             Katkovnik, Vladimir and Egiazarian, Karen},
  title   = {Image denoising by sparse {3-D} transform-domain
             collaborative filtering},
  journal = {IEEE Transactions on Image Processing},
  volume  = {16}, number = {8}, pages = {2080--2095},
  year    = {2007}, doi = {10.1109/TIP.2007.901238}
}

Parameters:

Name Type Description Default
data Tensor

(..., H, W) frames in ADU.

required
na float

Numerical aperture.

required
wavelength float

Emission wavelength, in the unit of pixel_size.

required
pixel_size float

Pixel size in the image plane (camera pixel / magnification).

required
offset Tensor or float

Offset β in ADU: scalar or (H, W) map.

0.0
gain Tensor or float

Gain γ in ADU per electron: scalar or (H, W) map.

1.0
sigma float

Extension: known σ_N in electrons (no estimate).

None
ratio ('1d', area)

σ_N/σ_c of Supplementary Eq. (11) ("1d") or its 2-D value ("area", extension).

"1d"
sigma_fit (histogram, std)

Estimate of σ_c.

"histogram"
camera_cutoff float

f̄ in units of the Nyquist frequency (1.1, from the ACsN code, not in the paper).

1.1
hotspot bool

Extension: remove hot pixels first (see the warning above).

False
block sequence of int

Core block size of the sparse filter (default: memory budget).

None

Returns:

Type Description
Tensor

Denoised frames, in electrons, of the shape of data.

acsn_halo

acsn_halo()

Halo, in pixels, of the blocks of the ACsN sparse filter.

The sum of the reach 2·⌊m/2⌋ + k − 1 = 25 of the two runs of acsn_profile: 50 pixels.

Inner blocks only

This is the halo of the blocks into which acsn cuts each frame for its sparse filter. Unlike bm3d_halo and nl_means_halo, it does not allow a frame to be tiled by the caller: σ_N and the mapping to [0, 255] are computed from the whole frame, so tiles of a frame denoised separately differ from the whole frame.

Returns:

Type Description
int

pure_let

pure_let(data, sigma=0.0, *, gain=1.0, offset=0.0, levels=4, ndim=2, reliability=10.0, sharpness=100.0)

PURE-LET denoising of mixed Poisson-Gaussian noise.

Model (Luisier et al. 2011, Eq. (1) and Section V): the data are offset + gain·y, y = z + b, z ~ 𝒫(x), b ~ 𝒩(0, σ²/gain²), with x the noise-free intensity in photons. With the paper's notation α = gain, δ = offset and σ² in units of y. Each image is normalised, y = (data − δ)/α, denoised in the unit-norm undecimated Haar wavelet domain (UWT PURE-LET, Section III) and mapped back, α·x̂ + δ:

  1. Transform. J levels of the separable undecimated Haar filterbank with periodic boundary conditions (haar_uwt); w = D_j·y are the wavelet coefficients of band j, w̄ = D̄_j·y the scaling coefficients of the same level (no group-delay compensation is needed for Haar, Section III-A).
  2. Thresholding (LET). Eq. (20), per band, θ_j(w, w̄) = a_{j,1}·w + a_{j,2}·w·exp(−(w/(3·t_j(w̄)))⁸) with t_j(w̄) = √(β_j·|w̄| + σ²), β_j = M_j^(−1/2) (Eq. (19)); the low-pass residual is kept: Eq. (21), f(y) = Σ_j Σ_k a_{j,k}·R_j·θ_{j,k}(D_j·y, D̄j·y) + R·y.}·D_{J+1
  3. PURE. The coefficients a minimise the first-order Taylor approximation of the PURE of Theorem 1, Eq. (6), an unbiased estimate of the MSE, which is quadratic in a: a solves the K × K linear system of Eq. (22), M·a = ĉ, K = 2·(2^d − 1)·J (one system per image, no iterations; see PureSums).
  4. Reliability (Section III-D). f_{j,2} is dropped (a_{j,2} = 0) when T_j = M_j·E_mean ≤ T, E_mean = (‖y‖² − 1ᵀy)/N − σ², T = 10.

In d dimensions a level has 2^d − 1 bands, each with its own (a_{j,1}, a_{j,2}); M_j = 2^(d·j) is the redundancy factor of level j (2^j in the 1-D derivation of the paper) and β_j = M_j^(−1/2).

Choices not specified in the paper

  • The number of levels J (default 4; the paper does not give it, and its Fig. 6 shows the levels 1 and 3). The result at a pixel depends on the data within 2^J − 1 pixels. Every transformed axis needs at least 2^J samples: the closed forms of PURE (Section III-B) assume that the filters of the coarsest level do not wrap around the image, and a ValueError naming the largest valid J is raised otherwise.
  • Each of the 2^d − 1 orientation bands of a level is a band of the filterbank with its own LET coefficients.
  • Boundaries are periodic, the case in which Section III-B gives the transform-dependent terms in closed form.
  • The result is returned in the units of data, α·x̂ + δ.
  • The numerical safeguards of let_threshold and PureSums.solve.

Extensions

  • gain, offset and sigma may be maps (broadcastable to the spatial shape), e.g. the per-pixel parameters of an sCMOS camera: y and σ_n² = σ_n²/α_n² are then per pixel, PURE uses Stein's lemma per pixel (see PureSums) and the threshold uses the local Gaussian variance of each coefficient.
  • ndim = 3 denoises volumes (or space-time stacks) with the separable 3-D transform; the paper derives the method in 1-D and applies it to images (d = 2).

Cost and memory

The peak memory is about K + 4·2^d + 16 images of the size of the input (periodically padded by 2^J − 1 pixels), with K = 2·(2^d − 1)·J: the K LET functions, plus the coefficients of one level and their reconstruction (56 for an image and 104 for a volume with J = 4; 2^d + 4 more with per-pixel noise maps). The cost is linear in the number of pixels. PURELET streams large arrays in blocks.

References

  1. Luisier F, Blu T, Unser M. Image denoising in mixed Poisson–Gaussian noise. IEEE Trans Image Process 20(3):696–708, 2011. doi:10.1109/TIP.2010.2073477
BibTeX
@article{luisier2011image,
  author  = {Luisier, Florian and Blu, Thierry and
             Unser, Michael},
  title   = {Image denoising in mixed {Poisson--Gaussian}
             noise},
  journal = {IEEE Transactions on Image Processing},
  volume  = {20}, number = {3}, pages = {696--708},
  year    = {2011}, doi = {10.1109/TIP.2010.2073477}
}

Parameters:

Name Type Description Default
data Tensor

(..., *spatial) with ndim spatial axes; each image (volume) is denoised separately.

required
sigma Tensor or float

Standard deviation of the Gaussian noise, in data units (0: pure Poisson noise).

0.0
gain Tensor or float

α, data units per photon.

1.0
offset Tensor or float

δ, in data units.

0.0
levels int

Number of levels J.

4
ndim int

Number of spatial axes d.

2
reliability float

T of Section III-D.

10.0
sharpness float

κ of the smooth absolute value tanh(κ·w̄)·w̄ (Section III-C, where it is called k).

100.0

Returns:

Type Description
Tensor

Of the shape of data.

pure_let_halo

pure_let_halo(levels=4)

Halo, in pixels, that makes block-wise PURE-LET exact.

A function f_{j,k} of Eq. (21) at pixel n depends on the samples n − 2^j + 1 … n + 2^j − 1 along each axis (analysis by D_j and D̄_j, then reconstruction by R_j, filters of length 2^j), hence a halo of 2^J − 1 pixels for J levels.

Parameters:

Name Type Description Default
levels int

Number of levels J.

4

Returns:

Type Description
int

nl_means

nl_means(data, sigma, *, h=None, patch=7, search=21, a=None, kernel_norm='mean', ndim=2, bias_correction=False)

Non-local means denoising of images with white Gaussian noise.

Model: y(i) = x(i) + ε(i), ε ~ 𝒩(0, σ²) i.i.d. (Eq. (1) of the paper, which writes v for the data y and u for the clean image x). Each pixel is replaced by a weighted mean of the pixels j of its search window W_i, weighted by the similarity of their patches (Section 3):

NL[y](i) = ∑_{j ∈ W_i} w(i, j)·y(j),
w(i, j) = exp(−‖y(N_i) − y(N_j)‖²_{2,a} / h²) / Z(i),
Z(i) = ∑_{j ∈ W_i} exp(−‖y(N_i) − y(N_j)‖²_{2,a} / h²),

where N_i is the patch centred on i and ‖·‖²_{2,a} the squared Euclidean distance weighted by a Gaussian kernel G_a of standard deviation a (see patch_distances). The weights satisfy 0 ≤ w(i, j) ≤ 1 and ∑_j w(i, j) = 1; the pixel itself has the largest unnormalised weight, exp(0) = 1. Section 5 sets the parameters used here by default: a 21 × 21 search window, 7 × 7 patches and h = 10σ. For other patches the default h is 10σ·√(K/49) with K = patchᵈ (see default_h), which keeps h = 10σ at the paper's settings.

This is the algorithm of Section 3, where the patch N_i contains the pixel i. The consistency results of Section 4 (Theorems 4 and 5) are stated for the patch without its centre, N_i∖{i}; that variant is not implemented. The paper prints ‖v(N_i) − v(N_i)‖ in Z(i); N_j is meant, as written above.

As h → 0 the result tends to the data (only the pixel's own patch has a non-vanishing weight, unless another patch is identical); as h → ∞ it tends to the mean of the search window. h = inf is accepted and gives that mean.

The paper notes that E‖y(N_i) − y(N_j)‖²_{2,a} = ‖x(N_i) − x(N_j)‖²_{2,a} + 2σ² (Section 3, for a kernel of sum 1) but uses the distance as is. bias_correction=True uses max(‖·‖²_{2,a} − 2σ²·∑G_a, 0) instead, the expected distance between two patches of noise being 2σ²·∑G_a (not in the paper).

Departure from the paper: the kernel normalisation

The paper implies a kernel G_a of sum 1 (the identity above holds only then), but with it h = 10σ averages nearly the whole search window, contrary to Section 5 and Fig. 2; Sections 3 and 5 are inconsistent. The default kernel_norm="mean" (mean 1 over the patch, so the distance is a weighted sum of squared differences) is a repair inferred from h² = 100σ² ≈ 2·49·σ², the expected distance between two 7 × 7 patches of noise; see patch_kernel. kernel_norm="sum" with h = 10σ/7 gives the same result.

Choices not specified in the paper

  • The width of G_a: a = (patch − 1)/4.
  • Borders: patches are completed by reflection, and the search window is clipped to the image (see patch_distances).
  • Volumes (ndim=3): cubic patches and search windows of the same sides, with the separable 3-D kernel.

Cost and memory

The cost is about searchᵈ·(d·patch + 4) operations per pixel (the patch sum is separable, one pass per axis). The computation is vectorised over batches of offsets of the search window: each offset of a batch holds at most three image-sized buffers, the batch being sized from the memory budget of optix.config. It runs on any torch device and, the offsets being accumulated one by one in a fixed order, does not depend on the batch size (to rounding). The result at a pixel depends on the data within nl_means_halo pixels, which NLMeans uses to stream large arrays in blocks.

References

  1. Buades A, Coll B, Morel J-M. A non-local algorithm for image denoising. IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05), vol. 2, 2005. doi:10.1109/CVPR.2005.38
BibTeX
@inproceedings{buades2005nonlocal,
  author    = {Buades, Antoni and Coll, Bartomeu and
               Morel, Jean-Michel},
  title     = {A non-local algorithm for image denoising},
  booktitle = {IEEE Computer Society Conference on Computer
               Vision and Pattern Recognition (CVPR'05)},
  volume    = {2},
  year      = {2005},
  doi       = {10.1109/CVPR.2005.38}
}

Parameters:

Name Type Description Default
data Tensor

(..., H, W) (or (..., D, H, W) with ndim=3); each image is denoised separately (floating point; other dtypes are converted to the configured dtype).

required
sigma float

Noise standard deviation σ > 0, in the units of data.

required
h float

Filtering parameter h > 0 (may be inf), in the units of data. Default: 10σ·√(K/49), K = patchᵈ, that is 10σ for 7 × 7 patches (Section 5).

None
patch int

Odd side of the patches (paper: 7).

7
search int

Odd side of the search window (paper: 21).

21
a float

Standard deviation of the kernel G_a, in pixels. Default: (patch − 1)/4.

None
kernel_norm (mean, sum)

Normalisation of G_a: mean 1 over the patch (default, a departure from the paper) or sum 1 (implied by the paper); see patch_kernel.

"mean"
ndim (2, 3)

Number of spatial dimensions (3 is not in the paper).

2
bias_correction bool

Subtract 2σ²·∑G_a, the expected distance between two patches of noise, from the patch distances, clamped at 0 (not in the paper).

False

Returns:

Type Description
Tensor

Of the shape of data.

nl_means_halo

nl_means_halo(*, patch=7, search=21)

Halo, in pixels, that makes block-wise NL-means exact.

⌊search/2⌋ + ⌊patch/2⌋ (13 for the paper's parameters): the pixels of the search window and their patches.

Parameters:

Name Type Description Default
patch int

As in nl_means.

7
search int

As in nl_means.

7

Returns:

Type Description
int

rof

rof(data, sigma=None, *, lam=None, data_term='gaussian', weights=None, axis_weights=None, ndim=2, max_iter=MAX_ITER, tol=TOL)

Total-variation denoising (Rudin, Osher & Fatemi 1992).

Each image (the last ndim dims) is denoised separately with tv_denoise. With sigma this is the model of the paper: minimise TV(u) subject to ∑ⱼ (uⱼ − fⱼ)² ≤ Mσ² (Eqs. 2.3a–c); lam, data_term, weights, axis_weights and ndim=3 are extensions (see ROF).

References

  1. Rudin LI, Osher S, Fatemi E. Nonlinear total variation based noise removal algorithms. Physica D 60(1–4):259–268, 1992. doi:10.1016/0167-2789(92)90242-F
  2. Chambolle A, Pock T. A first-order primal-dual algorithm for convex problems with applications to imaging. J Math Imaging Vis 40(1):120–145, 2011. doi:10.1007/s10851-010-0251-1
BibTeX
@article{rudin1992nonlinear,
  author  = {Rudin, Leonid I. and Osher, Stanley and
             Fatemi, Emad},
  title   = {Nonlinear total variation based noise removal
             algorithms},
  journal = {Physica D: Nonlinear Phenomena},
  volume  = {60}, number = {1--4}, pages = {259--268},
  year    = {1992}, doi = {10.1016/0167-2789(92)90242-F}
}
@article{chambolle2011first,
  author  = {Chambolle, Antonin and Pock, Thomas},
  title   = {A first-order primal-dual algorithm for convex
             problems with applications to imaging},
  journal = {Journal of Mathematical Imaging and Vision},
  volume  = {40}, number = {1}, pages = {120--145},
  year    = {2011}, doi = {10.1007/s10851-010-0251-1}
}

Parameters:

Name Type Description Default
data Tensor

(..., *spatial).

required
sigma float

Noise standard deviation σ, in the units of data.

None
lam float

Extension: weight λ of a penalised data term, instead of σ.

None
data_term (gaussian, kl)

Extension "kl": Poisson (Kullback–Leibler) data term on counts (needs lam).

"gaussian"
weights Tensor

Extension: pixel weights ω > 0, broadcasting with an image.

None
axis_weights sequence of float

Extension: weights of the differences along each spatial axis.

None
ndim (2, 3)

Number of spatial dims (3: extension).

2
max_iter int

Solver settings (see tv_denoise). One RuntimeWarning per call, with the worst gap, when images stop at max_iter above tol.

MAX_ITER
tol int

Solver settings (see tv_denoise). One RuntimeWarning per call, with the worst gap, when images stop at max_iter above tol.

MAX_ITER

Returns:

Type Description
Tensor

Of the shape of data.

Utilities

No stability promise

optix.denoise.utils holds building blocks of the denoisers above; they may change without notice.

Building blocks of optix.denoise (no stability promise).

The stages, transforms, block matching and collaborative filters of BM3D and BM4D, the patch distances of non-local means, the noise estimate, profile and quality score of ACsN, the default intensity range and the memory budget; the transform, thresholding functions and PURE system of PURE-LET; the OTF mask, cost, solver and segmentation of NCS; the total-variation solver of ROF.

Stage dataclass

Stage(transform, size, group, step, search, tau, lam, lam2d=0.0, beta=None, keep_dc=False, strict=False, pixel_distance=False, sigma_weight=True)

Parameters of one stage of BM3D or BM4D.

Attributes:

Name Type Description
transform {'bior1.5', dct}

Block transform T₂D (T₃D for cubes), separable.

size int

Block side N₁ (cube side L).

group int

Maximum group size N₂ (M).

step int

Step N_step between reference blocks, per axis.

search int

Side N_S of the search window (cube), centred on the reference.

tau float

Matching threshold τ_match on the normalised distance d = ‖·‖²/K (paper units).

lam float or None

Hard threshold λ₃D (λ₄D), in units of σ; None for the Wiener stage.

lam2d float

Pre-filter threshold λ₂D of the matching distance (0: none).

beta float or None

Kaiser window parameter β of the aggregation (None: no window).

keep_dc bool

Never threshold the DC coefficient of the group spectrum.

strict bool

Matching with d < τ (Wiener stage) instead of d ≤ τ.

pixel_distance bool

Hard-thresholding stage: match on the blocks' samples, d = ‖Z_{x_R} − Z_x‖²/K, instead of their spectra (ACsN, Mandracchia et al. 2020, Supplementary Eq. (12)). Same as the spectra for an orthonormal transform. It replaces the λ₂D pre-filter, so lam2d must be 0 (a ValueError otherwise), and it is ignored with a pilot (Wiener stage), which matches on the pilot's spectra.

sigma_weight bool

Hard-thresholding weight 1/(σ²·N_har) (BM3D, Eq. (10)) or 1/N_har (ACsN, Supplementary Eq. (15)); both are 1 when N_har = 0.

NcsResult

Bases: NamedTuple

Result of ncs_solve.

Attributes:

Name Type Description
x Tensor

Estimates μ, (B, L₁, L₂).

gradient Tensor

max |∇f| of each image at x, (B,).

n_iter Tensor

Newton iterations taken by each image, (B,).

converged Tensor

Whether the image met a stopping test of ncs_solve (gradient or step), (B,) (bool).

PureSums dataclass

PureSums(gram, cross, delta, resid, sum_y, sum_y2, sum_s, count, levels, ndim)

Sufficient statistics of PURE for a LET, mergeable over blocks.

With f(y) = Σ_k a_k·f_k(y) + f_low(y) (Eq. (21)), the PURE estimate of the MSE in the Taylor form of Eq. (6), generalised to a per-pixel Gaussian variance σ_n² (Stein's lemma applies per pixel),

ε̂ = (1/N)·(‖f − y‖² − 1ᵀy − Σσ_n²)
    + (2/N)·(yᵀ∂f + Σ_n σ_n²·(∂f_n − ∂²f_n)),

is quadratic in a:

N·ε̂(a) = aᵀ·G·a − 2·aᵀ·(b − δ) + ‖f_low − y‖² − 1ᵀy − Σσ_n²
         + 2·M_J⁻¹·Σ_n (y_n + σ_n²),

with G = [f_kᵀ f_l] (the matrix M of Eq. (22)), b = [f_kᵀ(y − f_low)] and δ_k of let_basis (f_low is linear: ∂f_low = M_J⁻¹·1, ∂²f_low = 0). Its minimiser solves the linear system of Eq. (22), G·a = ĉ = b − δ. All terms are sums over pixels or coefficients, accumulated in float64.

Attributes:

Name Type Description
gram, cross, delta Tensor

G (K, K), b and δ (K,).

resid float

‖f_low − y‖².

sum_y, sum_y2, sum_s float

Σy, Σy² and Σσ_n².

count int

Number of pixels N.

levels, ndim int

J and d.

energy property

energy

E_mean = (‖y‖² − 1ᵀy)/N − σ², an unbiased estimate of ‖x‖²/N.

from_basis classmethod

from_basis(functions, lowpass, delta, data, variance, *, levels, ndim=2)

Statistics of one block (one image or volume, core only).

Parameters:

Name Type Description Default
functions Tensor

From let_basis (no batch dims).

required
lowpass Tensor

From let_basis (no batch dims).

required
delta Tensor

From let_basis (no batch dims).

required
data Tensor

y on the core.

required
variance Tensor or float

σ² on the core, or a constant.

required
levels int

J and d.

required
ndim int

J and d.

required

Returns:

Type Description
PureSums

active

active(reliability=10.0)

Functions kept in the LET (Section III-D).

f_{j,1} is always kept; f_{j,2} only when T_j = M_j·E_mean > T (T = reliability, 10 in the paper), where the first-order Taylor approximation of PURE is reliable.

Parameters:

Name Type Description Default
reliability float

T.

10.0

Returns:

Type Description
Tensor

Boolean (K,).

risk

risk(coefficients)

PURE ε̂(a) for the LET coefficients a (zero for unused ones).

Parameters:

Name Type Description Default
coefficients Tensor

a, (K,).

required

Returns:

Type Description
float

solve

solve(reliability=10.0)

LET coefficients minimising PURE: G·a = b − δ, Eq. (22).

Restricted to the active functions; the others get a = 0. Not specified in the paper: the system is scaled to a unit diagonal and solved by its eigendecomposition, discarding eigenvalues below 10⁻¹⁰ times the largest. This is the exact solution of a well-conditioned system, and the minimum-norm minimiser of PURE when some f_k are (numerically) linearly dependent, as f_k = 0 for constant data. The sums must come from an image with at least 2^J samples along every transformed axis (as pure_let and PURELET require): on a smaller image δ is not the derivative term of PURE.

Parameters:

Name Type Description Default
reliability float

T of Section III-D.

10.0

Returns:

Type Description
Tensor

a, (K,), float64.

TVResult

Bases: NamedTuple

Result of tv_denoise.

Attributes:

Name Type Description
x Tensor

Denoised image u.

lam float

Weight λ of the data term: in the constrained model, the Lagrange multiplier of the noise constraint, the λ of Eq. 2.5a (twice the value of the printed Eq. 2.6, and with pixel spacing h = 1 where the paper has h = 1/N); 0 when a constant is feasible. Else the given λ.

n_iter int

Number of iterations (0 when a constant is feasible).

gap float

Last relative primal–dual gap (P − D)/P, with P the primal objective less the minimum of the data term (0 when a constant is feasible).

bm3d_profile

bm3d_profile(sigma, profile='normal')

Stages of the BM3D "normal" profile (Dabov et al. 2007, Table I).

Parameters:

Name Type Description Default
sigma float

Noise standard deviation in 8-bit units ([0, 255]); σ > 40 selects the high-noise column.

required
profile normal
"normal"

Returns:

Type Description
(Stage, Stage)

Hard-thresholding and Wiener stages.

bm4d_profile

bm4d_profile(profile='normal')

Stages of BM4D (Maggioni et al. 2013, Table I), data in [0, 1].

The table gives τ_match as the sum of squared differences of two cubes, ‖C₁ − C₂‖²; it is stored here divided by L³, the normalised distance d of Eq. (2).

Parameters:

Name Type Description Default
profile (normal, modified)
"normal"

Returns:

Type Description
(Stage, Stage)

Hard-thresholding and Wiener stages.

stage_halo

stage_halo(stage)

Reach of a stage: output samples depend on inputs within this.

A sample is covered by blocks at positions m within n − 1 of it, whose groups belong to references within ⌊N_S/2⌋ of m and read blocks within ⌊N_S/2⌋ of the reference: 2·⌊N_S/2⌋ + n − 1.

run_stage

run_stage(noisy, sigma, stage, *, pilot=None, origin=None)

One stage: grouping, collaborative filtering and aggregation.

Without pilot, the hard-thresholding stage (step 1) on noisy; with it, the Wiener stage (step 2) grouping in and filtering with the pilot (basic) estimate.

Parameters:

Name Type Description Default
noisy (*shape) Tensor

Image or volume, paper units.

required
sigma float

Noise standard deviation, paper units.

required
stage Stage
required
pilot (*shape) Tensor

Basic estimate (Wiener stage).

None
origin tuple of int

Global coordinates of the first sample (for the reference grid of blocks of a larger image).

None

Returns:

Type Description
(*shape) Tensor

Samples covered by no block keep their input value (noisy, or pilot in the Wiener stage).

patch_spectra

patch_spectra(x, mat)

Transform of every block of x (all positions).

Parameters:

Name Type Description Default
x (*shape) Tensor

Image or volume (2 or 3 dims).

required
mat (n, n) Tensor

1-D transform, applied along every axis of the blocks.

required

Returns:

Type Description
(∏P, nᵈ) Tensor

Spectra in row-major order of the positions P = shape − n + 1.

reference_grid

reference_grid(extent, size, step, origin=0)

Reference positions along one axis.

Positions p in [0, extent − size] with (p + origin) a multiple of step, plus the last position extent − size, so that every sample is covered.

Parameters:

Name Type Description Default
extent int
required
size int
required
step int
required
origin int

Global coordinate of sample 0 (blocks of a larger image).

0

Returns:

Type Description
Tensor of int64

block_match

block_match(spectra, positions, refs, stage, *, batch=None)

Group the blocks most similar to each reference.

For each reference x_R, the candidates are the positions x of its N_Sᵈ search window (clipped to the image), with the distance d(x_R, x) = ‖S(x_R) − S(x)‖²/K between their spectra (Dabov et al. 2007, Eqs. (4), (7); Maggioni et al. 2013, Eqs. (2), (9)). The group is made of the matched blocks (d ≤ τ, or d < τ for the Wiener stage) sorted by distance, the reference first; their number is capped at N₂ and rounded down to a power of two.

Parameters:

Name Type Description Default
spectra (∏P, K) Tensor

Spectra used for the distance (pre-filtered if λ₂D > 0).

required
positions tuple of int

Grid of positions P.

required
refs (R, d) Tensor of int64

Reference positions.

required
stage Stage
required
batch int

References per batch (default: match_batch).

None

Returns:

Name Type Description
index (R, N₂) Tensor of int64

Flat positions of the group members, best first (entries past the group size are padding).

size (R,) Tensor of int64

Group sizes (powers of two).

hard_threshold

hard_threshold(spectrum, threshold, sigma, keep_dc, sigma_weight=True)

Collaborative hard thresholding of group spectra.

Υ(c) = c·[|c| > λσ] (Dabov et al. 2007, Eq. (6)), with weight w = 1/(σ²·N_har) for N_har ≥ 1 retained coefficients, else 1 (Eq. (10)); w = 1/N_har without sigma_weight (Mandracchia et al. 2020, Supplementary Eq. (15)).

Note

The weight 1 of a group with N_har = 0 does not scale with the data, unlike 1/(σ²·N_har): in 8-bit units and σ = 20 it is at least 400 times any other weight, so such a group (all of its coefficients, the DC included, below λσ) dominates the samples it covers, where its estimate is 0. It occurs only without keep_dc, in groups whose mean is close to 0.

Parameters:

Name Type Description Default
spectrum (B, m, K) Tensor

3-D (4-D) spectra of B groups of m blocks, DC at [0, 0].

required
threshold float

λ₃D (λ₄D).

required
sigma float
required
keep_dc bool

Never threshold the DC (BM4D, Maggioni et al. 2013, Section II-B).

required
sigma_weight bool

Include σ² in the weight.

True

Returns:

Name Type Description
spectrum (B, m, K) Tensor
weight (B,) Tensor

wiener

wiener(noisy, pilot, sigma)

Collaborative empirical Wiener filtering of group spectra.

W = |T(Ŷ)|²/(|T(Ŷ)|² + σ²) from the pilot (basic) estimate, applied to the noisy spectrum, with weight w = σ⁻²·‖W‖₂⁻² (Dabov et al. 2007, Eqs. (8), (9), (11)).

Parameters:

Name Type Description Default
noisy (B, m, K) Tensor
required
pilot (B, m, K) Tensor
required
sigma float
required

Returns:

Name Type Description
spectrum (B, m, K) Tensor
weight (B,) Tensor

aggregate

aggregate(num, den, blocks, corners, offsets, weight, window)

Add weighted block estimates to the aggregation buffers.

num(x) += Σ w·κ·Ŷ(x), den(x) += Σ w·κ·χ(x) (Dabov et al. 2007, Eq. (12)), κ the Kaiser window (or 1).

Note

index_add_ is deterministic on the CPU; on CUDA its atomic additions make the sums order-dependent in the last bits.

Parameters:

Name Type Description Default
num (N,) Tensor

Flattened buffers, updated in place.

required
den (N,) Tensor

Flattened buffers, updated in place.

required
blocks (B, m, K) Tensor

Block estimates in the spatial domain.

required
corners (B, m) Tensor of int64

Flat sample index of each block's first sample.

required
offsets (K,) Tensor of int64

Flat sample offsets of the block's samples.

required
weight (B,) Tensor
required
window (K,) Tensor or None
required

clean_range

clean_range(lo, hi, count, sigma)

Default data_range: the range of the clean signal, estimated.

The extremes of noisy data overshoot those of the signal by the extremes of the noise, about √(2 ln N)·σ each for N samples. The estimate is the range of the data minus this extent,

R̂ = max(max − min − 2·√(2 ln N)·σ, (max − min)/2),

and at least half the range of the data. Not in the papers, whose images have a known range.

Parameters:

Name Type Description Default
lo float

Minimum and maximum of the data.

required
hi float

Minimum and maximum of the data.

required
count int

Number of samples N.

required
sigma float

Noise standard deviation σ, in the units of the data.

required

Returns:

Type Description
float

block_overhead

block_overhead(k)

Values per sample of a streamed block, for the memory budget.

The spectra of a stage take SPECTRA_COPIES·K values per sample, plus about eight image-sized buffers (data, estimates, aggregation buffers); the block is sized so that they fit in SPECTRA_SHARE of the budget, which leaves BATCH_SHARE to each batch.

Parameters:

Name Type Description Default
k int

Values per block K.

required

Returns:

Type Description
float

overhead of blocks.

match_batch

match_batch(candidates, k, itemsize, memory=None)

References per batch of the block matching of a stage.

A batch of b references holds about b·N_c·(2K·e + 40) bytes: the gathered candidate spectra and their differences (K values of e bytes each per candidate), plus the indices, masks and distances of the N_c candidates. It is sized to BATCH_SHARE of the budget.

Parameters:

Name Type Description Default
candidates int

Candidates per reference N_c (N_Sᵈ).

required
k int

Values per block K.

required
itemsize int

Bytes per value e.

required
memory int

Budget in bytes (default: get_config().memory).

None

Returns:

Type Description
int

filter_batch

filter_batch(group, k, itemsize, memory=None)

Groups per batch of the collaborative filtering of a stage.

A batch of b groups of m blocks holds about b·m·K·(8e + 8) bytes: up to eight temporaries of the size of the group (gathered spectra, transforms, shrinkage, block estimates, weights) and the int64 aggregation indices. It is sized to BATCH_SHARE of the budget.

Parameters:

Name Type Description Default
group int

Blocks per group m.

required
k int

Values per block K.

required
itemsize int

Bytes per value e.

required
memory int

Budget in bytes (default: get_config().memory).

None

Returns:

Type Description
int

transform_matrix

transform_matrix(name, n, *, dtype=None, device=None)

1-D transform "bior1.5", "dct" or "haar" of n samples.

Parameters:

Name Type Description Default
name ('bior1.5', dct, haar)
"bior1.5"
n int
required
dtype optional
None
device optional
None

Returns:

Type Description
(n, n) Tensor

Rows are the analysis functions, DC first.

bior15_matrix

bior15_matrix(n, *, dtype=None, device=None)

Normalised bior1.5 full dyadic wavelet transform of n samples.

Analysis filters of the biorthogonal spline wavelet bior1.5: the low-pass filter (√2/256)·[3, −3, −22, 22, 128, 128, 22, −22, −3, 3] (taps −4, …, 5 around sample 2k) and the Haar high-pass filter (x₂ₖ₊₁ − x₂ₖ)/√2, with periodic extension, iterated on the approximation down to one coefficient. Rows are the analysis functions, coarsest approximation (a constant, the DC) first, then the details from coarse to fine. Each row is scaled to unit ℓ² norm, so that white noise of variance σ² gives coefficients of variance σ².

Note

The filters are those of the bior1.5 wavelet named in Dabov et al. (2007, Table I); the periodic extension, the alignment of the filters and the row normalisation are not specified in the paper, which mentions "periodized wavelets" (Section IV) and "full dyadic" decompositions (Section IV-B). With n = 4 the transform is the orthonormal Haar transform, as stated by Maggioni et al. (2013, Section III-A).

With the periodic extension, the outer taps cancel at n = 8, the block size of the paper: in the first level, taps −4 and 4 (+3 and −3) fall on the same sample, and so do taps −3 and 5. The effective low-pass filter is the 6-tap (√2/256)·[−22, 22, 128, 128, 22, −22], and the two coarser levels are Haar. A symmetric extension would keep the ±3/256 taps.

T is not orthogonal, so a distance between coefficients, ‖T(a − b)‖², is not the distance between the samples.

Parameters:

Name Type Description Default
n int

Size, a power of two.

required
dtype optional
None
device optional
None

Returns:

Type Description
(n, n) Tensor

Forward transform T (coefficients = T·x); its inverse is torch.linalg.inv(T).

haar_matrix

haar_matrix(n, *, dtype=None, device=None)

Orthonormal full dyadic Haar transform of n samples.

Hₙ = [H_{n/2} ⊗ (1, 1)/√2; I_{n/2} ⊗ (1, −1)/√2], H₁ = 1: row 0 is the DC 1/√n, the others are Haar wavelets from coarse to fine.

Parameters:

Name Type Description Default
n int

Size, a power of two.

required
dtype optional
None
device optional
None

Returns:

Type Description
(n, n) Tensor

Hᵀ = H⁻¹.

dct_matrix

dct_matrix(n, *, dtype=None, device=None)

Orthonormal DCT-II of n samples, as rows (DC first).

The transpose of dct_basis.

Parameters:

Name Type Description Default
n int
required
dtype optional
None
device optional
None

Returns:

Type Description
(n, n) Tensor

kaiser_window

kaiser_window(n, beta, ndim=2, *, dtype=None, device=None)

Separable Kaiser window of n samples per axis, flattened.

w(i₁, …, i_d) = ∏ₖ κ_β(iₖ), with κ_β the symmetric 1-D Kaiser window I₀(β·√(1 − (2i/(n − 1) − 1)²)) / I₀(β).

Parameters:

Name Type Description Default
n int
required
beta float
required
ndim int
2
dtype optional
None
device optional
None

Returns:

Type Description
(n**ndim,) Tensor

In row-major order of the block.

ncs_mask

ncs_mask(shape, *, numerical_aperture, wavelength, pixel_size, mask='otf-weighted', dtype=None, device=None)

OTF mask m(k_x, k_y) of an image of shape (Supp. Notes 4–5).

The frequencies of an L₁ × L₂ image of pixel size Δ are k = p/(LΔ), p ∈ [−L/2, L/2 − 1] (Eq. 2), here in the order of torch.fft.fftn (zero frequency first), and k_r = √(k_x² + k_y²). The two masks of the paper are raised-cosine high-pass filters (raised_cosine) around the OTF radius 2NA/λ of an ideal system:

mask β T m = 0 below m = 1 above
"otf-weighted" (default) 1 λ/(5.6 NA) 0 5.6 NA/λ
"noise-only" 0.2 (1 − β)λ/(4 NA) 2 NA/λ 3 NA/λ

The OTF-weighted mask grows from the centre of the spectrum and also weighs the signal band a little; the noise-only mask leaves the band inside the OTF untouched (Supplementary Notes 5 and 9, Supplementary Fig. 5). A callable gives a user-defined radial mask (Supplementary Note 9).

Parameters:

Name Type Description Default
shape sequence of int

(L₁, L₂).

required
numerical_aperture float

NA of the objective.

required
wavelength float

Detection (emission) wavelength λ.

required
pixel_size float

Pixel size Δ in the object plane, in the unit of wavelength.

required
mask (otf - weighted, noise - only)

One of the paper's masks, or a function of k_r (cycles per unit of wavelength) returning m (the paper's M).

"otf-weighted"
dtype optional

Backend.

None
device optional

Backend.

None

Returns:

Type Description
Tensor

shape, values in [0, 1] for the paper's masks.

raised_cosine

raised_cosine(k, beta, period)

High-pass raised-cosine filter of the OTF mask (Supp. Note 5).

With k_lo = (1 − β)/(2T) and k_hi = (1 + β)/(2T), the mask m (the paper's M) is

m(k) = 0                                  for k < k_lo,
m(k) = ½ − ½ cos[(πT/β)(k − k_lo)]        for k_lo ≤ k ≤ k_hi,
m(k) = 1                                  for k > k_hi.

Sign of the cosine

Eq. (4) of the Supplementary Notes prints ½ + ½ cos[…] in the transition band. With that sign the mask is 0 below k_lo, jumps from 0 to 1 at k_lo, falls to 0 at k_hi and jumps from 0 to 1 above k_hi. The high-pass filter the text describes, continuous at both ends, is ½ − ½ cos[…]; it also gives the curves of Fig. SS4B (the default mask is about 0.28 at the OTF radius 2NA/λ and about 0.7 at 3.5NA/λ) and the mask height of about 0.2 at a sampling rate of 1.4 (Supplementary Note 11).

Parameters:

Name Type Description Default
k Tensor

Radial frequency k_r ≥ 0 (cycles per unit length).

required
beta float

Roll-off β ∈ [0, 1] (β = 0: a step at 1/(2T)).

required
period float

T > 0, in the unit of length of k.

required

Returns:

Type Description
Tensor

m(k), of the shape and dtype of k.

ncs_precorrect

ncs_precorrect(data, offset, variance, gain)

Pre-corrected image D and calibration γ (Supp. Notes 2, 3, 6).

Dᵢ = (Aᵢ − oᵢ)/gᵢ  (Eq. 1),  Dᵢ ← 10⁻⁶ where Dᵢ ≤ 0,
γᵢ = σᵢ²/gᵢ².

Parameters:

Name Type Description Default
data Tensor

Raw image A, in ADU.

required
offset Tensor or float

Offset o (ADU), read-noise variance σ² (ADU²) and gain g (ADU per electron); maps broadcast with data.

required
variance Tensor or float

Offset o (ADU), read-noise variance σ² (ADU²) and gain g (ADU per electron); maps broadcast with data.

required
gain Tensor or float

Offset o (ADU), read-noise variance σ² (ADU²) and gain g (ADU per electron); maps broadcast with data.

required

Returns:

Type Description
D, gamma : Tensor

In electrons and electrons², of the broadcast shape.

Raises:

Type Description
ValueError

If data or a map is not finite (NaN or ±∞), or if a gain or a variance is zero or negative.

ncs_objective

ncs_objective(x, data, gamma, mask, alpha)

Cost f = LL_s + α σ_N of each image (Supp. Note 2, step 3).

LL_s(μ) = ∑ᵢ μᵢ − (Dᵢ + γᵢ) ln(μᵢ + γᵢ)   (Eq. 7),
σ_N(μ)  = ∑_k |μ̂(k) m(k)|²                  (Eq. 3),

with μ̂ the unitary DFT of Eq. (2) (factor 1/L for an L × L image) and m the OTF mask (the paper's M).

Parameters:

Name Type Description Default
x Tensor

Estimate μ, (..., L₁, L₂), with μ + γ > 0.

required
data Tensor

D and γ of ncs_precorrect, broadcasting with x.

required
gamma Tensor

D and γ of ncs_precorrect, broadcasting with x.

required
mask Tensor

m, (L₁, L₂) in fftn order (see ncs_mask).

required
alpha float

Weight α.

required

Returns:

Type Description
Tensor

f per image, (...), in float64.

ncs_gradient

ncs_gradient(x, data, gamma, mask, alpha)

Gradient of ncs_objective.

∇f(μ) = 1 − (D + γ)/(μ + γ) + 2α F⁻¹(m² F μ).

The first two terms are the gradient of the shifted-Poisson likelihood (ShiftedPoisson with data D and variance γ).

Parameters:

Name Type Description Default
x Tensor

As in ncs_objective.

required
data Tensor

As in ncs_objective.

required
gamma Tensor

As in ncs_objective.

required
mask Tensor

As in ncs_objective.

required
alpha Tensor

As in ncs_objective.

required

Returns:

Type Description
Tensor

Of the shape of x.

ncs_solve

ncs_solve(data, gamma, mask, alpha, *, x0=None, max_iter=50, tol=None, cg_iter=100)

Minimise f = LL_s + α σ_N for a batch of images.

f is strictly convex on μ + γ > 0 (LL_s is a sum of strictly convex terms, σ_N a positive semi-definite quadratic), so the MAP estimate is unique. It is found by a damped Newton method, the paper leaving the optimiser open (Supp. Note 2: "a generic minimization routine such as fminunc"). The Hessian is

H = diag((D + γ)/(μ + γ)²) + 2α Q,  Q = F⁻¹ diag(m²) F,

and each Newton system H p = −∇f is solved by conjugate gradients preconditioned by the diagonal of H (the diagonal of Q is the mean of m²), to a residual of min(½, ‖∇f‖^½)·‖∇f‖. The step is the largest of 1, ½, ¼, … that keeps 1 % of the distance to the domain boundary μ = −γ and passes the Armijo test f(μ + tp) ≤ f(μ) + 10⁻⁴ t ∇fᵀp; the decrease is computed in closed form (with log1p), without forming f.

An image has converged when max |∇f| ≤ tol, or when a full Newton step (t = 1) changes no pixel by more than 10 ε · max(1, max|μ⁰|), for the machine epsilon ε of the dtype. The second test is relative to the signal: the rounding error of the term 2αQμ of ∇f grows as ε · 2α max|μ|, so on bright images in float32 the gradient stalls above tol while the iterate has reached the rounding floor; Newton converges quadratically, so such a step leaves an error of the order of ε · max|μ|. An image also stops, without converging, when the line search fails (round-off) or after max_iter iterations. The images of the batch are solved independently; the result of an image agrees with the result it gives alone to rounding, not bitwise (the FFT may round differently in batches of different sizes, which can also move the stopping iteration by one).

Not in the paper

The optimiser, its stopping rule and max_iter. The paper uses a generic routine, reports that the regression converges within 20 iterations (Supp. Note 2, step 4), and its software runs 15 iterations by default, with at least 10 recommended (Supp. Note 13). Here the iterations continue to the tolerance. The start is the paper's, μ⁰ = D (Supp. Note 2, step 3).

Parameters:

Name Type Description Default
data Tensor

D and γ, (B, L₁, L₂) (γ broadcasts).

required
gamma Tensor

D and γ, (B, L₁, L₂) (γ broadcasts).

required
mask Tensor

m, (L₁, L₂), in fftn order.

required
alpha float

Weight α ≥ 0.

required
x0 Tensor

Start (default: data). Must satisfy x0 + γ > 0.

None
max_iter int

Maximum number of Newton iterations.

50
tol float

Tolerance on max |∇f| (∇f is dimensionless). Default: max(100 ε, 10⁻¹⁰) (10⁻¹⁰ in float64, 1.2·10⁻⁵ in float32). The step test above applies as well.

None
cg_iter int

Maximum number of conjugate-gradient iterations per Newton step.

100

Returns:

Type Description
NcsResult

segment_bounds

segment_bounds(n, segment)

Segments [start, stop) of an axis of n pixels (Supp. Note 7).

Segments of segment = M pixels from the first pixel; when M does not divide n, the last segment also takes the remaining n mod M pixels (not in the paper), so that every segment has between M and 2M − 1 pixels (n pixels when n < M).

Parameters:

Name Type Description Default
n int

Length of the axis.

required
segment int

M.

required

Returns:

Type Description
list of (int, int)

acsn_profile

acsn_profile()

Stages of the ACsN sparse filter, in 8-bit units.

From Supplementary Notes 2.4 and 3.1 and Supplementary Fig. 12c: k × k = 8 × 8 patches, an m × m = 19 × 19 search window, groups of at most 8 patches, reference patches every 3 pixels, the pixel distance d(P, Q) = ‖P − Q‖₂²/k² (Eq. (12)) with τ_match = 2500, hard threshold λ_γ·σ_N with λ_γ = 4.0 (Eq. (14)) and aggregation weights 1/N_P (Eq. (15)); then the same grouping on the intermediate image and empirical Wiener shrinkage (Eqs. (16)-(17)).

The paper does not name the transforms; they are those of BM3D's normal profile (Dabov et al. 2007, Table I): bior1.5 then DCT for the patches, Haar along the group. For the second run, Supplementary Note 2.4 says: "This second-time process is the same as the first one with the only difference being the use of Wiener filtering". The Wiener stage departs from that text: it takes BM3D's τ_match = 400 with the strict test d < τ_match, the DCT and the weights σ⁻²‖W‖₂⁻² (Dabov et al. 2007, Table I and Eq. (11)), in place of the first run's τ_match = 2500, pixel distance and bior1.5. The paper gives τ_match = 2500 "for σ_N < 40" (Supplementary Note 3.1); it is used here for every σ_N, whereas BM3D switches to a second profile (τ_match = 5000 in the first run) above 40. The paper's aggregation has no Kaiser window, and none is used.

Returns:

Type Description
(Stage, Stage)

Hard-thresholding and Wiener stages.

acsn_noise

acsn_noise(m, pixel_size, cutoff, *, ratio='1d', sigma_fit='histogram', camera_cutoff=1.1)

Noise level σ_N of one frame, from its frequencies outside the OTF.

σ_N = ρ·σ_c, σ_c the noise of the high-pass image (highpass, sigma_from_highpass) and ρ the ratio of noise_ratio (Supplementary Eq. (11)). The noise, readout plus photon shot noise approximated as Gaussian (Supplementary Eq. (5)), is assumed white, and the signal confined within the OTF. For noise whose variance varies over the frame, σ_N² is the mean variance. With the 1-D ratio of the paper (ratio="1d"), σ_N is 1.2 to 1.9 times the standard deviation of white noise, depending on f_c/f̄ (see noise_ratio).

Parameters:

Name Type Description Default
m (H, W) Tensor

Frame corrected for offset and gain (Supplementary Eq. (4)).

required
pixel_size float

As in highpass.

required
cutoff float

As in highpass.

required
ratio Ratio

As in noise_ratio.

'1d'
camera_cutoff Ratio

As in noise_ratio.

'1d'
sigma_fit (histogram, std) "histogram"

Returns:

Type Description
float

σ_N, in the units of m.

otf_cutoff

otf_cutoff(na, wavelength)

Cutoff frequency f_c = 2·NA/λ of the incoherent OTF.

The radius of the optical transfer function of a fluorescence microscope (Supplementary Note 2.3 of Mandracchia et al. 2020: "calculate the radius of the OTF" from NA and the emission wavelength), in cycles per unit of wavelength.

Parameters:

Name Type Description Default
na float

Numerical aperture.

required
wavelength float

Emission wavelength λ (the unit of length of pixel_size).

required

Returns:

Type Description
float

highpass

highpass(x, pixel_size, cutoff)

High-pass filter that keeps the frequencies outside the OTF.

h = F⁻¹[F(x)·𝟙(|f| > f_c)] on the DFT frequencies of each frame (Supplementary Note 2.3 and Supplementary Fig. 12b: "the threshold of the filter at the OTF boundary"). The ideal (step) filter is that of the ACsN code; the paper does not specify the filter's shape.

Parameters:

Name Type Description Default
x (..., H, W) Tensor
required
pixel_size float

Pixel size in the image plane (camera pixel / magnification).

required
cutoff float

f_c, in cycles per unit of pixel_size.

required

Returns:

Type Description
(..., H, W) Tensor

Real high-pass image.

noise_ratio

noise_ratio(shape, pixel_size, cutoff, *, ratio='1d', camera_cutoff=1.1, like=None)

Ratio σ_N/σ_c of the noise to the noise of the high-pass image.

"1d" (the paper): white noise of power N₀ per unit bandwidth, recorded up to the camera cutoff f̄, has σ_N² = ∫₀^f̄ N₀ df (Eqs. (6)-(8) of Supplementary Note 2.3); the part above f_c has σ_c² = ∫_{f_c}^f̄ N₀ df (Eq. (9)), hence (Eqs. (10)-(11))

σ_N = √(f̄ / (f̄ − f_c)) · σ_c.

f̄ is the Nyquist frequency 1/(2Δ) times camera_cutoff. The paper calls f̄ the cutoff of the camera and gives no value; the default 1.1 is from the ACsN code, not in the paper. The frame must be sampled finely enough that f_c < f̄, that is a pixel size below λ/(4·NA)·camera_cutoff; otherwise a ValueError is raised.

"area" (extension): the same argument over the 2-D DFT frequencies of the frame, where white noise has the same power at every frequency: σ_N² = σ_c²·n/n_c, with n the number of frequencies and n_c the number above f_c. This is exact for white noise; the 1-D ratio is larger (for f_c at 0.8 times the Nyquist frequency, 1.91 with camera_cutoff=1.1 and √5 with 1, against 1.42).

Parameters:

Name Type Description Default
shape (H, W)

Frame shape.

required
pixel_size float

As in highpass.

required
cutoff float

As in highpass.

required
ratio ('1d', area)
"1d"
camera_cutoff float

f̄ in units of the Nyquist frequency ("1d" only; default 1.1, from the ACsN code, not in the paper).

1.1
like Tensor

Frame whose dtype and device the frequency grid of "area" takes, so that it counts the frequencies that highpass removes (default float32 on the CPU).

None

Returns:

Type Description
float

sigma_from_highpass

sigma_from_highpass(h, method='histogram')

Noise standard deviation σ_c of a high-pass image.

"histogram": the ACsN code's reading of "the intensity distribution of the pixel values in a high-pass filtered image" (Supplementary Fig. 12b): the magnitudes |h| are binned in 10 equal bins between their minimum and maximum, and a0·exp(−x²/(2σ_c²)) is fitted to the counts at the bin centres by nonlinear least squares, starting from a0 = the largest count and σ_c = the centre of bin round(k/2), k the (1-based) bin of the smallest count. "std" (extension): the root mean square of h (its mean is 0). An image whose magnitudes |h| are all equal (a constant high-pass image) has no histogram to fit, and gives 0 with "histogram".

Parameters:

Name Type Description Default
h Tensor

High-pass image (zero mean).

required
method (histogram, std)
"histogram"

Returns:

Type Description
float

quality_score

quality_score(noisy, denoised)

No-reference quality score of a denoised frame (Q-score).

Supplementary Note 7 (after Kong et al.): with the method noise image M = I − Î (Eq. (17)), the local structure similarity maps N = ρ(I, M) and P = ρ(I, Î), ρ(A, B) = (σ_AB + c)/(σ_A·σ_B + c) (Eq. (18)), and

Q = −corr(N, P)

(Eq. (19)), the Pearson correlation over the maps; Q ∈ [−1, 1], higher is better.

Choices not specified in the paper

The local statistics use the window of SSIM (Wang et al. 2004, doi:10.1109/TIP.2003.819861): 11 × 11 Gaussian of σ = 1.5, valid positions only, and c = (0.03·L)²/2 with L the range of I.

Precision

The maps are computed in the dtype of noisy (float64 for integer frames), after subtracting the mean of I from both frames, which leaves Q unchanged; the constant c and the final correlation are in float64.

Parameters:

Name Type Description Default
noisy (H, W) Tensor

I (offset- and gain-corrected) and Î.

required
denoised (H, W) Tensor

I (offset- and gain-corrected) and Î.

required

Returns:

Type Description
float

temporal_psnr

temporal_psnr(frames, neighbours=5)

PSNR of each frame against its average with the next frames.

The trigger of the video filtering of Supplementary Note 2.5: frame t is compared with the mean of frames t, …, t + neighbours, with peak the maximum of frame t,

PSNR_t = 10·log₁₀(max(x_t)² / mean((x_t − x̄_t)²)),

and the video filtering runs when the average PSNR is below 35 dB. The frames "and its 5 nearest neighbours" of the paper are the 5 following ones in the ACsN code.

Parameters:

Name Type Description Default
frames (T, H, W) Tensor

Denoised frames, T > neighbours.

required
neighbours int
5

Returns:

Type Description
(T − neighbours,) Tensor

PSNR in dB.

haar_uwt

haar_uwt(data, levels, *, ndim=2)

Undecimated separable Haar wavelet transform, valid part.

The J-band undecimated filterbank of Luisier et al. (2011, Fig. 3) with the unit-norm Haar filters H(z) = (1 + z⁻¹)/√2 and G(z) = (1 − z⁻¹)/√2, applied separably along the ndim trailing axes (Section III: "separable filters"). At level j = 1 … J, with s = 2^(j−1), the analysis filters are

H̄_j(z) = H(z)·H(z²)⋯H(z^s)          (scaling, w̄ = D̄_j y)
G̃_j(z) = H(z)·H(z²)⋯H(z^(s/2))·G(z^s)   (wavelet, w = D_j y)

in each 1-D direction; in d dimensions a level has 2^d − 1 wavelet bands (at least one direction high-pass). For the Haar filters the group-delay compensation filter of Eq. (17) is Q(z) = 1 (H(z⁻¹) = z·H(z), n₀ = 1): the scaling coefficients of a level are aligned with its wavelet coefficients without further filtering. Each coefficient at index l depends on the samples l … l + 2^j − 1 along every axis; only coefficients with their whole support inside data are returned (no boundary extension: pad data first, e.g. periodically).

Parameters:

Name Type Description Default
data Tensor

(*batch, *spatial) with ndim spatial axes.

required
levels int

Number of levels J.

required
ndim int

Number of transformed (trailing) axes d.

2

Returns:

Type Description
list of (Tensor, Tensor)

Per level j: the wavelet bands (2^d − 1, *batch, *spatial_j) and the scaling coefficients (*batch, *spatial_j), where each spatial extent is reduced by 2^j − 1.

let_threshold

let_threshold(w, wbar, beta, variance, sharpness=100.0, *, derivatives=True)

Nonlinear LET function of Eq. (20) and its partial derivatives.

θ(w, w̄) = w·exp(−(w/(3·t(w̄)))⁸), with the signal-dependent threshold of Eq. (19),

t(w̄) = √(β·|w̄| + σ²),

where |w̄| is replaced by the smooth tanh(κ·w̄)·w̄ (Section III-C, where it is called k; κ = sharpness = 100) so that the derivatives of Corollary 1 exist. Returns θ and Θ₁ = ∂θ/∂w, Θ₂ = ∂θ/∂w̄, Θ₁₁ = ∂²θ/∂w², Θ₂₂ = ∂²θ/∂w̄², Θ₁₂ = ∂²θ/∂w∂w̄ (the vectors of Corollary 1), in closed form. With u = w/(3t) and E = exp(−u⁸):

Θ₁ = E·(1 − 8u⁸),     Θ₁₁ = −(8u⁷/(3t))·E·(9 − 8u⁸),
Θ₂ = (8w·u⁸·E/t)·t′,  Θ₁₂ = (8u⁸·E/t)·(9 − 8u⁸)·t′,
Θ₂₂ = (8w·u⁸·E/t²)·(8u⁸ − 9)·t′² + (8w·u⁸·E/t)·t″,

with t′ = β·m′/(2t), t″ = β·m″/(2t) − β²·m′²/(4t³) and m(w̄) = tanh(κ·w̄)·w̄.

Choices not specified in the paper

  • t² is floored at the machine epsilon of the dtype (t = 0 occurs for pure Poisson noise on a zero background).
  • u is clipped to |u| ≤ 2, where E < e⁻²⁵⁶: θ and its derivatives are 0 to working precision there, and the clip avoids overflow.

Parameters:

Name Type Description Default
w Tensor

Wavelet coefficients.

required
wbar Tensor

Scaling coefficients of the same level (broadcast to w).

required
beta float

Scale factor β_j = M_j^(−1/2) that turns w̄ into a local mean.

required
variance Tensor or float

Gaussian variance σ² of the coefficients (a map for per-pixel noise parameters).

required
sharpness float

κ of the smooth absolute value tanh(κ·w̄)·w̄.

100.0
derivatives bool

Whether to compute the five derivatives; θ alone otherwise.

True

Returns:

Type Description
tuple of Tensor

θ, Θ₁, Θ₂, Θ₁₁, Θ₂₂, Θ₁₂; (θ,) if derivatives is False.

let_basis

let_basis(data, variance, levels, *, ndim=2, sharpness=100.0, halo=None, derivatives=True)

The LET functions f_{j,k}(y), the low-pass term and their PURE terms.

Eq. (21): f(y) = Σ_j Σ_k a_{j,k}·f_{j,k}(y) + R_{J+1}·D_{J+1}·y with, for each wavelet band j of the undecimated Haar filterbank (haar_uwt),

f_{j,1}(y) = R_j·D_j·y,       f_{j,2}(y) = R_j·θ_j(D_j·y, D̄_j·y)

(θ_{j,1}(w, w̄) = w and θ_{j,2} of Eq. (20), see let_threshold). The reconstruction is R_j = M_j⁻¹·D_jᵀ, M_j = 2^(d·j) (so that R·D = I and diag{D_j·R_j} = 1/M_j, Section III-B), with R_{J+1} = M_J⁻¹·D̄_Jᵀ for the low-pass residual, which is not thresholded.

For each function, the derivative terms of the PURE of Eq. (6) are returned as one number, the term of ĉ in Eq. (22),

δ_k = yᵀ·∂f_k(y) + Σ_n σ_n²·(∂f_{k,n} − ∂²f_{k,n})(y),

where ∂f (∂²f) holds the first (second) derivatives ∂f_n/∂y_n (∂²f_n/∂y_n²). With a constant σ² the second sum is σ²·div{f_k − ∂f_k}, Eqs. (12)-(13). They are evaluated with the closed forms of Eqs. (11)-(13), in which, for the unit-norm Haar filters and periodic boundary conditions, the transform-dependent terms reduce to (v = y or the variance map σ², per coefficient l of band j)

(D∙Rᵀ)v = M⁻³ᐟ²·D̄v,          (D̄∙Rᵀ)v = M⁻³ᐟ²·Dv,
((D∙D)∙Rᵀ)v = ((D̄∙D̄)∙Rᵀ)v = M⁻²·Dv,   ((D∙D̄)∙Rᵀ)v = M⁻²·D̄v,

because d_{l,n}² = M⁻¹ on the support of the band's filter, the scaling filter is constant there (M⁻¹ᐟ²) and the wavelet filters have zero mean. This needs the 2^j taps of each filter to fall on distinct pixels, i.e. an image with at least 2^J samples along every transformed axis: on a smaller image the circulant D_j of Eq. (16) folds several taps onto one pixel and δ below is not the derivative term of PURE. Hence

δ_k = M⁻³ᐟ²·Σ_l [Θ₁·D̄(y + σ²) + Θ₂·D(y + σ²)]
      − M⁻²·Σ_l [(Θ₁₁ + Θ₂₂)·Dσ² + 2·Θ₁₂·D̄σ²],

which for a constant σ² is Eqs. (11)-(13) with diag{DR} = 1/M, diag{D̄R} = diag{(D∙D)R} = diag{(D̄∙D̄)R} = 0 and diag{(D∙D̄)R} = M⁻³ᐟ². The Gaussian variance of the threshold of Eq. (19) is that of the coefficient, β_j·D̄σ² (σ² for a constant variance).

data holds a block with a halo of halo ≥ 2^J − 1 samples on each side of every transformed axis (pad the whole image periodically, the boundary condition of Section III-B): the functions are returned on the core, and δ sums over the coefficients l of the core, so that sums over blocks partitioning an image are the whole-image sums.

Parameters:

Name Type Description Default
data Tensor

Normalised data y (Poisson counts plus Gaussian noise), (*batch, *spatial), core plus halo.

required
variance Tensor or float

Gaussian variance σ² in the units of y: a scalar, or a map of the shape of data (per-pixel noise parameters).

required
levels int

Number of levels J.

required
ndim int

Number of transformed (trailing) axes d.

2
sharpness float

κ of the smooth absolute value tanh(κ·w̄)·w̄ (Section III-C, where it is called k).

100.0
halo int

Halo of data (default: 2^J − 1).

None
derivatives bool

Whether to compute δ.

True

Returns:

Name Type Description
functions Tensor

f_{j,k}(y) on the core, (K, *batch, *core), K = 2·(2^d − 1)·J, ordered by level, band, then k.

lowpass Tensor

R_{J+1}·D_{J+1}·y on the core.

delta Tensor or None

δ_k, (K, *batch).

patch_kernel

patch_kernel(patch, a=None, norm='mean', *, dtype=None, device=None)

1-D factor of the Gaussian kernel of the patch distance.

g(u) ∝ exp(−u²/(2a²)) for u = −r … r (r = ⌊patch/2⌋). The d-dimensional kernel G_a is the outer product of d copies. With norm="mean" each factor sums to patch, so G_a has mean 1 over the patch (it sums to patchᵈ) and the distance is a weighted sum of squared differences; with norm="sum" each factor sums to 1, so G_a sums to 1 and the distance is a weighted mean.

Choice not specified in the paper

The paper does not give a. The default a = (patch − 1)/4 is 1.5 for 7 × 7 patches (the patch spans ±2a). a = inf gives uniform weights; a has no effect for patch=1.

Departure from the paper: the default normalisation

The paper implies a kernel of sum 1 ("sum"): its identity E‖y(N_i) − y(N_j)‖²_{2,a} = ‖x(N_i) − x(N_j)‖²_{2,a} + 2σ² (Section 3) holds only then, and Sections 1 and 2.1 use a normalised Gaussian. Its setting h = 10σ (Section 5) is not consistent with that kernel: the distance is then at most R² for data of range R, so every weight is at least exp(−R²/(100σ²)) of the pixel's own (0.20 at σ = 20 on 8-bit data), whereas Section 5 and Fig. 2 describe weights that fall to nearly zero; the result is close to the mean of the search window. The default "mean" is a repair inferred from the paper's numbers, not stated in it: with a kernel of mean 1 the expected distance between two 7 × 7 patches of noise is 2·49·σ² ≈ h² = 100σ², so h = 10σ is the natural scale and the weights behave as Section 5 describes. The two normalisations differ by the factor patchᵈ (49 for 7 × 7 patches), a factor 7 on h.

Parameters:

Name Type Description Default
patch int

Odd side of the patch.

required
a float

Standard deviation of the Gaussian, in pixels (> 0, may be inf).

None
norm (mean, sum)

Normalisation of G_a: mean 1 or sum 1.

"mean"
dtype dtype | None

Of the result.

None
device dtype | None

Of the result.

None

Returns:

Type Description
Tensor

(patch,).

default_h

default_h(sigma, patch=7, ndim=2)

Default filtering parameter h = 10σ·√(K/49), K = patchᵈ.

Section 5 of the paper sets h = 10σ for 7 × 7 patches (K = 49). With the default kernel (mean 1 over the patch), the expected distance between two patches of noise is 2σ²·K, so h is scaled by √(K/49) to keep the ratio of that distance to h² at its value in the paper, 2·49/100 = 0.98. It is h = 10σ at the paper's settings.

Parameters:

Name Type Description Default
sigma float

Noise standard deviation σ.

required
patch int

Odd side of the patches.

7
ndim int

Number of spatial dimensions d.

2

Returns:

Type Description
float

search_offsets

search_offsets(search, ndim)

Offsets t of the search window, in raster order.

The window is the cube of side search (odd) centred on the pixel: t ∈ {−s … s}ᵈ with s = ⌊search/2⌋.

Parameters:

Name Type Description Default
search int

Odd side of the search window.

required
ndim int

Number of spatial dimensions d.

required

Returns:

Type Description
list of tuple of int

patch_distances

patch_distances(data, offsets, kernel, search)

Patch distances to the pixels at a set of offsets.

For each offset t and pixel i, with j = i + t,

d_t(i) = ‖y(N_i) − y(N_j)‖²_{2,a} = ∑_u G_a(u)·(y(i+u) − y(j+u))²

(Section 3 of the paper), computed from shifted copies of the image: the squared difference of y and its shift by t, then a separable weighted sum over the patch. The differences are taken pixel by pixel (no expansion of the square), so d_t ≥ 0 and d_t(i) = d_{−t}(j) to rounding.

Choices not specified in the paper

Patches that cross the border of the image are completed by reflection about the edge pixels (torch.nn.functional.pad, mode "reflect"), axis by axis; an axis of at most ⌊patch/2⌋ pixels is completed by replication (mode "replicate") instead. Offsets whose pixel j falls outside the image are invalid, which clips the search window at the border.

Parameters:

Name Type Description Default
data Tensor

(*spatial), one image or volume (d = data.ndim).

required
offsets sequence of tuple of int

K offsets, each within the search window.

required
kernel Tensor

1-D kernel of patch_kernel.

required
search int

Side of the search window (sets the padding).

required

Returns:

Name Type Description
distances Tensor

(K, *spatial); 0 where invalid.

values Tensor

(K, *spatial), y(i + t); 0 where invalid.

valid Tensor

(K, *spatial) bool, whether i + t is in the image.

offset_batch

offset_batch(pixels, itemsize, memory=None)

Offsets per batch of the vectorised NL-means.

A batch of b offsets holds about b·OFFSET_COPIES buffers of the size of the padded block (P values of e bytes); it is sized to OFFSET_SHARE of the budget.

Parameters:

Name Type Description Default
pixels int

Values P of the padded block.

required
itemsize int

Bytes per value e.

required
memory int

Budget in bytes (default: get_config().memory).

None

Returns:

Type Description
int

tv_denoise

tv_denoise(data, *, sigma=None, lam=None, data_term='gaussian', weights=None, axis_weights=None, variance=0.0, max_iter=MAX_ITER, tol=TOL, check_every=CHECK, trace=None, warn=True)

Total-variation denoising of one image or volume.

The total variation is that of the discrete forward-difference gradient with Neumann boundaries (Eqs. 2.4b and 2.9a),

TV(u) = ∑ⱼ (∑ₐ (wₐ D⁺ₐ u)ⱼ²)^½,

over all dims of data (axis weights wₐ = 1 by default). Models:

  • Gaussian, constrained (sigma; Rudin, Osher & Fatemi 1992, Eqs. 2.3a–c): minimise TV(u) subject to ∑ⱼ ωⱼ(uⱼ − fⱼ)² ≤ Mσ², M the number of samples, pixel weights ω = 1 by default.
  • Gaussian, penalised (lam): minimise TV(u) + (λ/2)∑ⱼ ωⱼ(uⱼ − fⱼ)².
  • Kullback–Leibler (Poisson; lam, data_term="kl"): minimise TV(u) + λ∑ⱼ ωⱼ(uⱼ − (fⱼ + s²) log(uⱼ + s²)), the shifted-Poisson likelihood of ShiftedPoisson with read variance s² (variance, 0: Poisson); u ≥ −s².

All three are solved with chambolle_pock (K = ∇, F = ‖·‖₂,₁, G = the data term), with the accelerated steps of its Algorithm 2 for the penalised Gaussian model (G is λ·min ω-strongly convex). The primal and dual steps are τ_p = κ/‖∇‖ and τ_d = 0.99/(κ‖∇‖), with κ a scale of the data term in data units: SPLIT·σ/√ω̄ with SPLIT = 1/8 (constrained), 1/(λω̄) (penalised) and c̄/(λω̄) (KL, c̄ the mean of f + s²). Iterations stop when the relative primal–dual gap (P − D)/(P − min G) is at most tol (checked every check_every iterations), with P = TV(u) + G(u) and D = −G*(−∇ᵀy). A run that stops at max_iter above tol emits a RuntimeWarning (with warn). Neither the solver nor the step sizes nor the stopping rule are in the paper.

In the constrained model, when a constant image is feasible (∑ⱼ ωⱼ(fⱼ − c)² ≤ Mσ² with c the ω-weighted mean of f), every feasible constant is a minimiser (TV = 0), so the solution is not unique; c is returned at once, with λ = 0, no iteration and gap 0.

The working memory is about 2d + 5 image sizes (d the number of dims; 9 for an image) for the Gaussian data terms, and about three times that for the KL term, whose gap is evaluated in float64.

Parameters:

Name Type Description Default
data Tensor

Noisy image f, all dims spatial.

required
sigma float

Noise standard deviation σ (constrained Gaussian model).

None
lam float

Weight λ > 0 of the data term (penalised models).

None
data_term (gaussian, kl)

Data term.

"gaussian"
weights Tensor

Pixel weights ω > 0, broadcasting with data. Default: 1.

None
axis_weights sequence of float

Weights wₐ > 0 of the differences along each axis. Default: 1.

None
variance Tensor or float

Read variance s² ≥ 0 of the KL term.

0.0
max_iter int

Maximum number of iterations.

MAX_ITER
tol float

Tolerance on the relative primal–dual gap.

TOL
check_every int

Iterations between two evaluations of the gap.

CHECK
trace dict None
warn bool

Warn when the run stops at max_iter with a gap above tol.

True

Returns:

Type Description
TVResult