Skip to content

Measure field distortion

Two microscopes rarely agree on geometry. A pixel size that is off by a few per cent, or a little barrel distortion from the camera optics, is invisible in one image but makes two images of the same sample drift apart towards the edges of the field. This tutorial measures both against a reference microscope with pysrx.register: the scale error and the radial distortion \(k_1\), with an independent, model-free check.

The same method measured the ZEISS Lightfield 4D and a Leica THUNDER spinning disk against an LSM 980; the results are on the light-field page.

What you need

  • Two acquisitions of the same sample, one on the microscope you want to measure and one on a reference (for example a confocal, whose scan field is usually well calibrated). The sample should be flat or thin, with texture everywhere: a tissue section such as Convallaria, a dense bead slide, or a grid or pattern slide.
  • The voxel size of each, in µm, as the acquisition software reports it. The result tells you how far the two disagree.
  • Overlapping fields. The reference field should cover as much of the other field as possible: distortion grows towards the corners, and only the region both microscopes see is measured.
  • Optionally SimpleITK for the mutual-information step (pixi add simpleitk in your project); without it, pass mutual_information=False.

Load each stack as a NumPy array, (Z, Y, X) or (C, Z, Y, X), with its (z, y, x) voxel size. Single images (Y, X) with (y, x) pixel sizes also work; then no z offset is fitted.

import numpy as np
from pysrx import register as R

ref, ref_sp = ..., (1.0, 0.5, 0.5)       # the reference stack (e.g. the confocal) and its voxel size, µm
mov, mov_sp = ..., (2.0, 0.65, 0.65)     # the microscope to measure

The numbers on this page come from a synthetic pair with a known answer, so you can see how close the fit gets. It mimics a camera microscope (312 µm field, 0.65 µm pixels) seen through a 2.5 % scale error and barrel distortion of −0.6 % at the field corner, and a confocal reference covering the central 280 µm:

Make the synthetic pair
from scipy import ndimage as ndi

rng = np.random.default_rng(0)
ref_sp, mov_sp = (1.0, 0.5, 0.5), (2.0, 0.65, 0.65)   # µm (z, y, x): confocal, camera microscope
nz, ny, nx = 12, 480, 480                              # camera microscope: a 312 µm field, 24 µm deep
fine = np.zeros((4 * nz, ny, nx), np.float32)          # blobs in a thin slab, z sampled 4x finer
n = 14000
fine[rng.normal(2 * nz, 0.4 * nz, n).clip(0, 4 * nz - 1).astype(int),
     rng.integers(0, ny, n), rng.integers(0, nx, n)] = rng.uniform(0.3, 1.0, n)
mov = ndi.gaussian_filter(fine, (3.0, 1.8, 1.8))[1::4] + 0.002 * rng.standard_normal((nz, ny, nx))
truth = R.FieldTransform.for_fields((560, 560), ref_sp, (ny, nx), mov_sp, ty=14.0, tx=18.0, theta=0.0087, tz=5.0)
truth.s, truth.k1 = 0.975, -0.006                      # 2.5 % scale error, barrel distortion
ref = np.nan_to_num(R.resample_to_ref(mov, (16, 560, 560), ref_sp, mov_sp, truth))   # the "confocal": 280 µm

1. One image per field

Registration runs on one 2D image per microscope: the channels are combined (each divided by its 99.5th percentile), and the stack is projected over its in-focus planes only, so empty planes do not dilute the texture.

ref_reg, mov_reg = R.registration_image(ref), R.registration_image(mov)   # channels -> one image
ref2d, mov2d = R.focus_mip(ref_reg), R.focus_mip(mov_reg)                 # in-focus band only

2. Fit the model

The model maps a reference point to the other microscope's field: an in-plane rotation \(\theta\) and a translation \(t\), then an isotropic scale \(s\) and a Brown-Conrady radial distortion \(k_1\) about the centre of that field,

\[ q = c + (u - c)\, s \left(1 + k_1 \frac{|u - c|^2}{r_n^2}\right), \]

where \(u\) is the rotated and translated point, \(c\) the field centre and \(r_n\) the distance from the centre to the field corner. Normalising by \(r_n\) makes \(k_1\) the fractional distortion at the corner: negative is barrel, positive is pincushion. The fit runs in steps, each starting from the last:

ty, tx = R.coarse_xy(ref2d, mov2d, ref_sp, mov_sp)                        # step 1: template matching
theta, ty, tx = R.fine_xy(ref2d, mov2d, ref_sp, mov_sp, ty, tx)           # step 2: mutual information
rigid = R.FieldTransform.for_fields(ref2d.shape, ref_sp, mov2d.shape, mov_sp, ty=ty, tx=tx, theta=theta)
tf = R.fit_distortion(ref2d, mov2d, ref_sp, mov_sp, rigid)                # step 3: NCC over ty, tx, θ, s, k1
tf.tz = R.search_z(ref_reg, mov_reg, ref_sp, mov_sp, tf)                  # step 4: z offset
  1. coarse_xy finds the translation by template matching at 1 µm/px: (13.0, 18.0) µm here.
  2. fine_xy refines it with a rigid fit by mutual information (SimpleITK, Euler2D, 0.5 µm/px): 0.521°, (13.69, 17.75) µm. A rigid fit cannot absorb a scale error, so it is still off.
  3. fit_distortion maximises the normalised cross-correlation (NCC) over the translation, rotation, \(s\) and \(k_1\) with a Powell search (on the GPU when CuPy is available).
  4. search_z scans the z offset that maximises the mean plane-wise NCC.
\(s\) \(k_1\) \(\theta\) \(t_z, t_y, t_x\) NCC
fitted 0.9751 −0.0066 0.499° 5.04, 14.00, 18.00 µm 0.415 → 0.991
truth 0.975 −0.006 0.498° 5, 14, 18 µm

The NCC column is the projection's agreement before step 3 (rigid) and after it. register runs all four steps and the check below in one call:

tf, field = R.register(ref, mov, ref_sp, mov_sp)    # mutual_information=False without SimpleITK

3. Check it without the model

A fitted model only finds what it is allowed to find. The check measures the displacement field directly: displacement_field resamples the other image through the rigid transform (no scale, no \(k_1\)), cuts both into 48 µm tiles every 24 µm, and measures the shift of each tile by phase correlation. Tiles with too little texture, outside the field, or a poor match after the shift are dropped. radial_displacement takes the component of each shift along the radius from the field centre.

field = R.displacement_field(ref2d, mov2d, ref_sp, mov_sp, rigid, tile_um=48.0)
r, dr = R.radial_displacement(field, tf)          # radius from the field centre, radial displacement (µm)

99 tiles passed. If the model is right, dr follows the model's radial displacement \(r\,(s\,(1 + k_1 r^2 / r_n^2) - 1)\) with only measurement scatter left over.

4. Read the result

summary = R.distortion_summary(tf, field)
here truth what it means
scale_error_pct −2.49 % −2.5 % \(100\,(s - 1)\): distances in the measured image are this much shorter (negative) or longer than in the reference. Usually a pixel-size calibration; it grows linearly with the distance from the centre.
k1_pct_at_corner −0.66 % −0.60 % \(100\,k_1\): the radial distortion at the field corner on top of the scale. Negative: barrel; positive: pincushion.
k1_shift_at_corner_um −1.45 µm −1.32 µm \(k_1 r_n\): how far the distortion alone moves the field corner. Compare it with the pixel size.
corner_radius_um 220.6 µm \(r_n\), the centre-to-corner distance of the measured field.
measured_radius_max_um 164.5 µm the largest radius with a measured tile; beyond it the model is extrapolated.
fit_rms_um 0.30 µm RMS of the tiles' radial displacement about the model: the scatter the model leaves. Well under a pixel means the model explains the field.
n_tiles 99 tiles that passed the quality checks.

The scale is recovered to 0.01 %. \(k_1\) is off by 0.06 %, 0.13 µm at the corner: the reference reaches only 164 µm of the 221 µm corner radius, and over that range a little more barrel and a little less scale look almost the same. The total displacement, which is what moves the pixels, agrees with the truth to 0.03 µm everywhere inside the measured region.

5. Plot it

The radial displacement against the radius shows the measurement and the model together:

import matplotlib.pyplot as plt

rr = np.linspace(0, tf.rn, 200)
inside = rr <= summary["measured_radius_max_um"]
fig, ax = plt.subplots(figsize=(5.5, 3.6))
ax.scatter(r, dr, s=10, alpha=0.6, lw=0, label="measured tiles")
ax.plot(rr[inside], tf.radial_model(rr[inside]), "k", lw=2, label="fit (scale + k₁)")
ax.plot(rr[~inside], tf.radial_model(rr[~inside]), "k--", lw=2, label="extrapolated")
ax.axhline(0, color="0.6", lw=0.8)
ax.set(xlabel="radius from field centre (µm)", ylabel="radial displacement (µm)")
ax.legend(frameon=False, loc="lower left")
fig.savefig("fd_radial.png", dpi=160, bbox_inches="tight")

Radial displacement of 99 measured tiles against the radius from the field centre, with the fitted scale and k1 model, dashed beyond the measured region

The scale error is the straight part of the curve, \(k_1\) the bend towards the edge. Dashed: beyond the last measured tile, the model is extrapolated.

A distorted grid shows the shape of \(k_1\), exaggerated so that it is visible:

E = 10                                                 # exaggeration
H, W = mov2d.shape[0] * mov_sp[1], mov2d.shape[1] * mov_sp[2]
t = np.linspace(0, max(H, W), 200)
fig, ax = plt.subplots(figsize=(4.2, 4.2))
for g in np.arange(0, max(H, W) + 1e-6, 50.0):
    for y, x in ((np.full_like(t, g), t), (t, np.full_like(t, g))):
        keep = (y <= H) & (x <= W)
        dy, dx = y[keep] - tf.dcy, x[keep] - tf.dcx
        f = tf.k1 * (dy**2 + dx**2) / tf.rn**2               # k1 alone; scale left out
        ax.plot(dx, dy, color="0.75", lw=0.6)
        ax.plot(dx * (1 + E * f), dy * (1 + E * f), color="C1", lw=1.0)
corners_y, corners_x = np.array([0, 0, 1, 1, 0]) * ref2d.shape[0] * ref_sp[1], np.array([0, 1, 1, 0, 0]) * ref2d.shape[1] * ref_sp[2]
_, ym, xm = tf.map(0, corners_y, corners_x)                  # the reference field, in the moving frame
ax.plot(xm - tf.dcx, ym - tf.dcy, "k--", lw=1)
ax.set(xlabel="x from field centre (µm)", ylabel="y from field centre (µm)", aspect="equal")
ax.invert_yaxis()
fig.savefig("fd_grid.png", dpi=160, bbox_inches="tight")

A 50 µm grid over the measured field (grey) and the same grid with the fitted barrel distortion exaggerated ten times (orange); dashed, the reference field

A 50 µm grid (grey) and the fitted \(k_1\), exaggerated ten times (orange). Dashed: the region the reference covers, rotated as fitted.

The light-field page shows the same two plots for four real acquisitions against an LSM 980.

Caveats

  • Flat sample. Tilt is not fitted. A thick or tilted sample puts different depths in focus across the field and can read as distortion; use a thin section or a slide, and the in-focus projection.
  • Enough texture everywhere. The fit and the tiles need structure all over the field. Empty regions give no tiles, and the corners, where the distortion is largest, matter most.
  • Field coverage. Only the region both microscopes see is measured. With a small reference field, scale and \(k_1\) trade against each other (as above); move the sample and repeat to cover the corners.
  • \(k_1\) beyond the measured region is extrapolated, and so is the shift at the corner. Read measured_radius_max_um alongside it.
  • Relative, not absolute. The result says how two microscopes differ, not which is right. Use a calibrated reference (or a stage micrometer) to decide.
  • Fit RMS well above a pixel means something the model does not include: tilt, a decentred optical axis, or a wrong match. Look at the radial plot.