Encoderless computational microscopy: live X-Y stitching, shape-from-focus height maps and ISO 25178-style surface metrology for manual microscopes (FLOSS, GPL-3.0)
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Foad S. Farimani 5cf3fc0f28
release: 0.14.0 (stepped sweeps, knob calibration, control socket, README status) (#36)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:01:41 +01:00
.github feat: image-quality tools for still views (#27) 2026-11-28 20:24:06 +01:00
docs fix: resolve post-v0.12 audit defects across optics, live engine, and GUI (#33) 2026-11-30 20:12:25 +01:00
microtopos release: 0.14.0 (stepped sweeps, knob calibration, control socket, README status) (#36) 2026-12-04 19:01:41 +01:00
packaging feat(gui): streamline capture, setup and inspection (#31) 2026-11-29 20:43:57 +01:00
tests feat: stepped sweeps and knob calibration; camera gain priming, Reset mosaic, log file, control socket (#35) 2026-12-04 18:11:52 +01:00
tools ci: tests-bite job, strict skip policy, project lint; AGENTS.md rules (#16) 2026-11-25 17:30:31 +01:00
.gitignore fix: trustworthy measurements after a source review: verdict gate, signed Z, dataset identity, units, persistence 2026-11-05 11:09:07 +01:00
AGENTS.md ci: tests-bite job, strict skip policy, project lint; AGENTS.md rules (#16) 2026-11-25 17:30:31 +01:00
LICENSE MicroTopos 0.6: encoderless computational microscopy (GPL-3.0-or-later) 2026-11-04 00:39:49 +01:00
pyproject.toml release: 0.14.0 (stepped sweeps, knob calibration, control socket, README status) (#36) 2026-12-04 19:01:41 +01:00
README.md release: 0.14.0 (stepped sweeps, knob calibration, control socket, README status) (#36) 2026-12-04 19:01:41 +01:00
uv.lock release: 0.14.0 (stepped sweeps, knob calibration, control socket, README status) (#36) 2026-12-04 19:01:41 +01:00

MicroTopos

Encoderless computational microscopy for a manual microscope with a USB eyepiece camera. Move the X-Y stage and the view is stitched into a mosaic. Turn the fine focus through the surface and a height map, an all-in-focus image and ISO 25178-style roughness, texture and grain statistics are computed automatically. Free software (GPL-3.0-or-later); Linux, Windows and macOS.

Website, manual and tutorials: https://foadsf.github.io/microtopos/

Download

Portable executables are attached to each release; no Python installation needed. Every executable runs its own self-test on the build machine before it is published.

Platform File Requirement
Linux x86_64 microtopos-<version>-linux-x86_64 (single file; chmod +x, run) glibc 2.34+ (Ubuntu 22.04, Debian 12, Fedora 35 or newer)
Linux arm64 (e.g. Raspberry Pi 5) microtopos-<version>-linux-arm64 glibc 2.39+ (Ubuntu 24.04, Debian 13, Raspberry Pi OS Trixie)
Windows x86_64 microtopos-<version>-windows-x86_64.exe Windows 10/11 (also runs on Windows-on-ARM via emulation)
macOS Apple Silicon microtopos-<version>-macos-arm64.zip (unzip, open microtopos.app) macOS 14+
macOS Intel microtopos-<version>-macos-x86_64.zip macOS 14+

The binaries are not code-signed: on macOS right-click → Open the first time; on Windows choose "More info → Run anyway". Linux needs the usual desktop libraries (OpenGL/EGL, fontconfig) and, for camera controls, v4l-utils. A native Windows-on-ARM build is not possible yet (no OpenCV wheels for that platform). Verify a download with microtopos --selftest --quick (add --gui for the interface check).

Run from source

uv run microtopos              # GUI; picks the microscope camera if one is connected
uv run microtopos --simulator  # GUI with the synthetic specimen only
uv run microtopos-selftest     # ground-truth checks, 3 seeds; --quick for one seed, --gui adds a GUI run,
                               # --json FILE writes every row with thresholds and versions
uv run --group dev pytest      # the same checks, pipeline tests and an offscreen GUI smoke test
uv run --group dev pytest -m slow  # full generalisation matrix (tests/test_gen_*.py: seeds x objectives x
                                   # conditions, negative controls); the default run keeps a subset
uv run microtopos-record DIR   # record the camera (also: "Record raw stream" in the GUI)
uv run microtopos --replay DIR # replay a recording at its recorded timing (frames may be skipped under load)
uv run microtopos-batch DIR OUT  # analyse EVERY frame of a recording in order, reconstruct each sweep
uv run microtopos-bench        # CPU vs OpenCL focus-measure timing with a parity check, on this computer

Python 3.12 or newer (CI tests 3.12 and 3.13; development runs on 3.14). On Python 3.11 the Qt bindings abort with a reference-count error, so 3.11 is not supported.

Status (v0.14, December 2026)

v0.14.0 adds heights in µm without the even-knob-speed assumption, and makes the app observable and scriptable:

  • Stepped sweeps (Z scale step): turn the fine focus by the same number of scale divisions, let go for about a second, repeat through focus, with Start Z capture on. Each pause is detected from the focus tiles and is one z position, divisions × µm per division apart, so the speed of each turn does not matter. On simulated stepped sweeps (10×/0.25 and 40×/0.85, five seeds each, turns of 1–3 frames at random) the height slope against the truth was 0.97–0.99; the even-speed hand path, given the true total travel, gave 0.86–0.99 on the same frames. Pauses missed far out of focus shift the relief without changing it; a turn of the wrong size cannot be detected. On the real microscope it has so far been run only on the shim sweeps described under knob calibration below. microtopos-batch --stepped STEP_UM does the same for a recording. A stepped sweep must be captured with Start Z capture: a focus movement the app finds on its own ends at the first pause, so with Stepped sweeps ticked it is refused with that instruction. Turn in one direction only: turning back makes a surface go sharp twice and adds steps that were not there (seen at 10×, where a 100 µm shim then measured 140 µm). The app does not yet detect this.
  • Knob calibration: make a stepped sweep over the edge of a shim measured with a micrometer, measure Step height A→B, press Calibrate the knob from the step height… and enter the thickness. The knob's µm per division is scaled to match and the result is rescaled; stepped heights are then CALIBRATED (a typed-in value is ESTIMATED). The knob scale belongs to the stand and is kept for every objective. First calibration on the MikrOkular stand (2026-12-03, 4×/0.10, 2 divisions per step, a 0.10 mm feeler-gauge blade on a caliper beam, XY NOMINAL): the blade measured 130.3 µm at the typed-in 10 µm/division, giving 7.67 µm per division. Different choices of the two regions gave 123–130 µm, so take about ±3 %; a gap under the blade would add to its thickness and is not excluded. A check at 10×/0.25 (1 division per step) put the base 111 ± 8 µm below the blade: the base, a ground steel beam, had too little texture at 10× for more than 5–15 % valid pixels, so that check is good to about 10 % only. Between two surfaces several depths of field apart nothing is in focus and pauses there can merge; keep a calibration step within a few depths of field of the objective used (the 4× has 62.5 µm), or expect it to read short.
  • Dark image after start or replug: the MikrOkular's UVC bridge has no gain control; its automatic exposure sets a hidden analog gain that manual mode freezes. The capture thread now runs automatic exposure until the frames settle before locking manual exposure, and Set once does the same. Observed on the MikrOkular; the tests use a fake camera that models the hidden gain.
  • Reset mosaic clears the insets too, unless Keep insets on reset is ticked. Changing the objective keeps them.
  • Log file: what the GUI, the engine, the camera and the mosaic tracker do is logged to ~/.local/state/MicroTopos/logs/microtopos.log (Windows %LOCALAPPDATA%\MicroTopos\logs, macOS ~/Library/Logs/MicroTopos), rotated at 5 MB; --debug adds per-frame detail. Uncaught exceptions in any thread are logged with their traceback, and a crash inside Qt or OpenCV leaves its stack in microtopos-faults.log.
  • microtopos-ctl drives a running window over a local socket that only the same user can open: status (chips, messages, result card, camera read-back), press a button by its text (also on hidden tabs), tick a box, choose the objective or result, record, Set Z, stepped-sweep settings, step height, knob calibration, profile, export and screenshot. status includes the selected result's Report warnings and its z scale (stepped: the pauses found). There is no command that runs code. --no-control starts the GUI without it.
  • The window still opens in the light theme on a new profile (View → Dark theme switches and is remembered); a test keeps that default. On Windows the control socket no longer touches a pipe Qt has already deleted.
  • Reconstruct last sweep keeps the last real sweep: a later focus movement too small to be a sweep no longer replaces it (it did on the microscope, losing a 240-frame capture to a 92-frame refocus).

v0.13.1 fixes defects found in an audit of 0.11–0.13; no feature was removed:

  • Measurements no longer crash or hang:
    • Colour-fringe correction works when the preview size has a different rounding from the capture size (1360×768 shown at 640×361).
    • Sharpness from an edge handles a double edge, such as a stage-micrometer line, instead of failing with NaN.
    • Rolling-shutter, distortion and colour-fringe measurements cancel and re-enable their buttons when the camera, capture size or objective changes.
  • Measure camera response solves the Debevec–Malik system sparsely. OpenCV's dense solver took 263 s for 24 frames on Windows.
  • A damaged calibration file is rejected with a message instead of stopping the live view.
  • Measurements taken with the simulator are no longer saved to the calibration file.
  • Optics calibrations (colour fringes, edge PSF, distortion) now count as data when an objective is renamed over another, so they are not silently overwritten.
  • The manual documents the 0.11 and 0.12 controls.

v0.13.0 streamlined the workspace:

  • It opens in light mode; a saved theme preference is kept.
  • Start Z capture and Record raw stream are on the Live bar.
  • Specialised controls fold away until needed:
    • Preview options (colour preview, white balance)
    • Advanced camera settings (exposure, linearisation, camera response, rolling shutter, stage)
    • Super-resolution
    • Mosaic tools
    • Height tools
    • Reconstruction settings
    • Diagnostics
  • Sessions, exports and panel layout are in the File and View menus, with the same shortcuts (Ctrl+S, Ctrl+O, Ctrl+E; Space for manual capture when no control has focus).
  • Job progress and Cancel appear below the workspace whatever panel is shown.
  • With the simulator, the XY and Z chips are hidden, because its scales are simulation truth, not a camera calibration. XY is labelled at the incoming frame size.
  • The step panel now fits its widest page on every platform. Before, a page could be cut off by a few pixels (6 px on macOS) under the middle panel.

v0.12.0 added measurements of the optics themselves, each stored per objective (or per camera) and capture size, and used from then on:

  • Measure sharpness from an edge (Inspect). It runs the slanted-edge method on a straight edge (a razor blade, a stage-micrometer line) and reports MTF50 in cycles per pixel and lp/mm, against the objective's diffraction limit. Stacking and super-resolution then deconvolve with the measured blur instead of the textbook one. The previous edge fit read the blur 18 % high at σ 0.8 px. On synthetic edges the new method matches the closed form within 0.6 % in MTF50 and 0.8 % in σ.
  • Measure colour fringes (Objective) estimates how far red and blue are scaled and shifted against green (lateral chromatic aberration). It removes the fringes from the colour preview, the colour mosaic, colour sweeps and still images, never from the luma that heights come from. Synthetic fringes were recovered within 0.5 × 10⁻⁴ in scale and cut 6–9×.
  • Measure lens distortion (Lateral scale) estimates barrel or pincushion distortion from a pan, with no target, and removes it from the frames the mosaic stitches. Simulated distortion of 3 px at the corner was recovered within 5 %. Vignetting otherwise mimics barrel distortion, so the tracking runs on a high-passed image.
  • Measure rolling shutter (Camera). The OV2710 reads its rows one after another, so a fast pan skews the frame. Pairs of a still frame and a fast-pan frame give the readout time, and the mosaic stitches straightened frames. On a synthetic camera the readout fraction was recovered within 0.1 %, with the engine skipping frames (velocity per source frame, not per processed frame).
  • Stacking resamples with Lanczos-4: 11–14 % closer to the truth on simulated camera frames with hand tremor.
  • The live view's still average is aligned on the newest frame, so hand tremor no longer blurs it (display only).

Tried and not adopted, because they did not improve the result:

  • Restoring the JPEG data of focus-sweep frames recovered 0–1 % of the 4–16 % height accuracy that compression costs.
  • Reconstructing several frames jointly within every frame's quantisation intervals added nothing reliable over a Lanczos stack at realistic sizes, for 5–9 s.

These measurements ran on simulated or synthetic inputs only, with one exception: on three still 1920×1080 frames from the MikrOkular, with the objective then in use, the colour-fringe estimate took 13 s. It found no measurable lateral chromatic aberration: 0.05–0.12 px at the corner, within its uncertainty, so nothing would be stored. Edge sharpness, distortion and rolling shutter need a razor-blade edge or panning by hand on the real microscope.

v0.11.0 added image-quality tools for still views, chosen after measuring what limits the MikrOkular. The camera is an OmniVision OV2710 1920×1080 sensor behind an Alcor USB 2.0 bridge (firmware CA1.529). The bridge sends MJPEG only: JPEG quality about 43, 4:2:2 chroma, 40–190 kB per frame. It offers no uncompressed, 16-bit or full-colour mode, and no white-balance or gain control. Every objective is already sampled at least 1.9× as finely as its optics resolve (λ/4NA against 0.734 µm/px at 4×). So compression, noise and light limit the image, not the pixel count. The additions:

  • Stack still frames aligns the still frames, rejects outliers and divides out frame-to-frame brightness changes (±1.2 % on the MikrOkular), on the camera's own grid. On 16 real still frames the noise fell from 0.91 to 0.23 DN. Optional Richardson–Lucy sharpening up to the optical cutoff.
  • JPEG restoration. When the camera's JPEG data is available (live, or a raw recording), still images are rebuilt from it. The decoder's exact luma is deblocked within the quantisation limits the camera's own tables allow, and the half-resolution colour is upsampled along luma edges. Against simulator ground truth encoded like the MikrOkular, frames are 16 % closer to the truth and a 12-frame stack 7–10 % closer than a plain decode. On real frames, blockiness fell from 0.86 to 0.21.
  • Super-resolution is refused where it cannot add detail. The finest useful grid is the Nyquist pixel λ/4NA. On the MikrOkular that refuses it for every objective; stacking is offered instead.
  • White balance from the current view (grey world), applied to colour images only, never to the measurement. It is recorded with each result.
  • Estimated flat from panning. Without a blank reference, panning the specimen in two directions over 2–3 field widths separates the fixed shading from the moving specimen. The flat is stored labelled "estimated from panning". On the simulator, its known vignette (15–30 % fall-off) was recovered within 1.5 %.
  • Measured camera response and HDR stills. The exposure is stepped and the camera's tone curve measured, so "Linearise gamma" stops assuming 2.2 and results say which was used. An exposure bracket merges into relative radiance. The MikrOkular cannot be measured this way: it gives identical frames for every exposure setting from 7.8 to 20.4 ms, and its brightness drifts about 3 % for 30 frames after a change. The series is refused with that reason, and HDR needs a measured response. Both were verified against simulated cameras only, one truthful and one with quantised exposure.
  • Export still image: float TIFF of the luma (or radiance), a 16-bit or float RGB TIFF, and provenance JSON.
  • Memory: every finished background job stayed in memory with its inputs, through signal connections Python cannot collect. A long session kept every reconstructed sweep's frames, and the test suite grew to 10.6 GB, enough for the kernel to kill other applications on a 15 GB laptop. Finished jobs are now released; the heaviest test file peaks at 1.1 GB instead of 4.4 GB, and CI runs in 8–14 minutes instead of 23–60.

v0.10.3 fixes super-resolution's motion gate. Frames from a microscope nobody touched passed as having sub-pixel motion, and came back resampled and labelled as a super-resolved image. Registration noise of a few thousandths of a pixel either side of zero was counted as different sub-pixel phases. Such frames are now refused. This was found by running v0.10.2 against the MikrOkular camera: 16 still frames, with shifts of 0.00–0.01 px, had been accepted. Super-resolution with real hand motion on that camera has not been tried yet.

v0.10.2 fixes defects found in two reviews of the code added since v0.9.0 (PR #22 and PR #23). The ones that change a measurement:

  • Step height: the standard error of a step height is computed from the least-squares covariance. It was about 15× too small before. A one-pixel-wide region no longer returns a wrong step.
  • 3-point levelling: a clicked patch at the image edge no longer leaves a tilt.
  • Masking: a rectangle dragged past the image edge no longer wraps around.
  • ISO 21920 profile: the profile parameters follow the standard's conventions for the cut-off count, run-in and run-out, Rz sections and volume parameters, and Sds is 0 for a plane.
  • Reversed hand sweeps: a sweep that turns back near focus is detected at 40×.
  • Stage Z labels: an attached stage labels frames with its Z only during a Z sweep, so hand sweeps and replays can be reconstructed again.
  • Grbl report units: the Grbl driver reads the report-unit setting ($13), so positions reported in inches are converted. Before, they were read as millimetres, 25.4× too small. A feed hold, check mode or sleep is reported as an error, not as arrival. This was verified against a simulated controller only.

The camera lists the resolutions the device reports (default 1920×1080) and remembers the choice. Mosaic insets are drawn and survive an objective change. Joining two areas applies the measured offset and, with rotation tracking on, the measured rotation. An opened mosaic is tracked into only with the same objective and preview size.

Known limits: the breathing-scale correction overestimates by +3 to +20 % at small focus steps; it is an experimental option and off by default.

v0.10.1 fixes a layout regression in v0.10.0: the main window could not be made narrower than 2361 px (device-independent pixels), so on a 1920 px screen it could not be resized and a maximised window lost its telemetry panel off the screen edge. The minimum width is now 1092 px and the tool bars wrap. Screens narrower than about 1092 px still overflow. This was checked from source on one Windows machine (125 % scaling) and in CI's offscreen tests; other screens and scalings have not been tried.

v0.10.0 adds the capabilities listed under "New in v0.10.0" below (motorised stage drivers and a stage panel, colour pipeline, replay bar, mosaic bridging and insets, more ISO 25178 parameters), and fixes defects that came out of a review of the code behind them: a Grbl driver that blocked cancel and status calls during a move, dead jog buttons, complete Z sweeps thrown away because the stage moved afterwards, repeated z labels from a settling stage that left 70–90 % of height-map pixels invalid, a colour all-in-focus image that was shown but never saved, and an unsigned-integer overflow in the focus measures brenner and tile_scores. Tests no longer read or write the real user settings. Contributors: see "Contributing".

The stage, Grbl, camera-mode and mosaic additions are experimental: they have been run against the simulator and a fake Grbl controller only, never against a real stage, controller or camera. The release executables include the optional pyserial library, so the Grbl driver is present in them.

v0.9.0 adds an optional brightness stretch for dim live views and fixes raw recordings from MJPEG cameras (saved as 1-pixel strips before; old recordings still replay). Stitching follows striped specimens again, five registration and mosaic bugs found by a new generalisation test matrix are fixed, and the window header and side panel no longer jump or get cut off. See "Other cameras" for DSLRs through v4l2loopback.

v0.8.1 added a user-editable objective list (step 2, "Edit objectives…") with presets, including the Leitz NPL 5×/0.09, 10×/0.20, 20×/0.40 and Fluotar 50×/0.85 set.

Early but working. Tested with a Bresser MikrOkular Full HD eyepiece camera on Linux Mint: live capture, automatic focus-sweep detection, height maps and stitching all run on real specimens. The algorithms are validated against simulator ground truth (below); on real specimens they are not yet validated quantitatively (no calibrated reference sample measured so far), and stitching on real footage has only been checked visually. The Windows and macOS builds pass their self-tests on the build servers but have not been run on a real desktop.

New in v0.10.0

The following are exercised by the offscreen GUI tests and the default test suite (pytest; pytest -m "" adds the slow tests). The tests use the simulator and a fake Grbl controller: no real camera, stage or Grbl hardware has been used with these features.

  • Motorised stage drivers: SimulatedStageDriver (synthetic, for offline development) and GrblStageDriver (serial; opt-in via the [serial] extra / pyserial; checked against a fake Grbl only), with stage-coupled Z-readback and Z-sweep from the GUI stage panel (connect, zero, jog and multi-level Z-sweep).
  • Multi-aspect/resolution camera & calibration support; 16-bit PNG recordings are decoded (there is no Y16 capture mode); colour pipeline: RGB EDF (shown, written to the report bundle as edf_rgb.png and kept in saved sessions) and RGB mosaic.
  • Interactive replay transport bar (ReplaySource): pause/resume, seek, single-frame step, playback speed and loop, driven from the GUI replay bar — no real camera required.
  • Mosaicking: disconnected-area bridging (cross-area loop closure; with track_rotation the join also applies the measured rotation), multi-scale insets (MosaicInset: a view pinned with "Add inset", and the previous objective's mosaic after an objective change) drawn under the mosaic at their own scale, feather and multiband (a two-band blend, not a Laplacian pyramid) blending, rotational stage tracking (track_rotation), and saving and reloading the mosaic graph (LiveEngine.mosaic_state / load_mosaic_state). A mosaic records its objective and preview scale: an opened one is shown at its own scale, and live frames of another objective or camera mode are not tracked into it. An inset's place in a new mosaic assumes parcentred objectives and a stage that does not move during the change.
  • 3D reconstruction & compute: experimental focus-breathing correction (estimate_breathing_scales, off by default), strip-wise (tiled) Z-stack reconstruction that bounds peak working memory (allow_tiling), an optical depth-of-field ruler (theoretical_fwhm_um, an estimate), and expanded OpenCL (cv2.UMat) focus metrics and guided filter.
  • Metrology: ISO 21920 1D profile filtering (Ra, Rq, Rz, …), ISO 25178 Sdq, volume parameters (Vmp, Vmc, Vvc, Vvv), feature parameters (Sds, Ssc, Spd, Spc, S5p, S5v, S10z), interactive 3-point levelling, exclusion-mask ROI, step-height ROIs, topographic grain segmentation, and configurable super-resolution.

The Windows-on-ARM caveat is unchanged: a native Windows-on-ARM build is not possible yet (no OpenCV wheels for that platform); Windows x86_64 runs on Windows-on-ARM via emulation.

Other cameras

Any camera that appears as a video device (V4L2 on Linux) can feed MicroTopos. One user runs a Canon EOS 50D DSLR on a Nikon MM-11 with a BD Plan 5×/0.10: gphoto2 reads the live view over USB, ffmpeg converts it, and v4l2loopback publishes it as a virtual webcam that MicroTopos opens like any other (issue #2). Three things differ from a USB eyepiece camera:

  • No camera controls. MicroTopos cannot lock the exposure or switch off sharpening through a loopback device, so set manual exposure and no sharpening on the camera itself.
  • Recordings are PNG, not MJPEG. The loopback device delivers decoded frames, so "Record raw stream" saves lossless PNG frames, which are larger.
  • A motorised focus gives real Z. If a stepper drives the focus knob, state each sweep's travel (steps × step size) and direction with "Set Z…" for heights in µm.

v0.8 follows an external source review (November 2026). It adds:

  • a self-test gate that cannot pass a failing NumPy verdict;
  • signed hand-sweep heights with source-frame spacing;
  • result, calibration and mosaic identity;
  • unit-safe mosaics and repeatability;
  • validated recordings with a deterministic batch mode;
  • atomic exports with validity masks;
  • versioned sessions;
  • several metrology edge-case fixes.

Workflow

The left panel is a checklist; each step shows a status chip.

  1. Camera: exposure is locked (manual) and in-camera sharpening, automatic white balance and gain are switched off, because they corrupt focus measurement. The settings are re-applied by the capture thread after the stream starts and after a reconnect, and the device's actual values are read back and shown. "Set once" picks a manual exposure just below saturation. View rotation turns the 2D views when the camera sits rotated in the eyepiece tube; "Measure from X pan" sets it from a move of the X knob alone (display only).
  2. Objective (keys 1–9, in list order): sets NA, depth of field, focus window and the roughness S-filter. Edit objectives… holds the objectives on your nosepiece (name, magnification, NA, immersion index, cover-glass note, maker/series) with validation, or loads a preset such as Leitz NPL 5×/10×/20×/50× Fluotar. The list is saved as objectives.json next to the calibration; calibrations stay with the objective's name (renaming carries them along, removing keeps them). The lateral scale still needs a stage micrometer for each objective.
  3. Dark & flat (optional): 24-frame averages, stored per objective, capture size and exposure. Without a blank, "Estimate flat while panning" derives the flat from a pan in two directions (stored as estimated).
  4. Lateral scale: drag the blue line over a stage micrometer interval and enter its length. Until then all lateral lengths are labelled NOMINAL.
  5. Z scale: the knob has no encoder. A hand sweep's heights are relative focus progression in camera frames (constant knob speed assumed), with an unknown direction unless you state it. Set Z… binds the knob travel and direction to one sweep (CALIBRATED, that sweep only). A stored µm-per-frame value, or the experimental DOF ruler, is applied to later sweeps as ESTIMATED. With Stepped sweeps ticked, a sweep made of equal turns and pauses is measured in µm from the knob's µm per division (typed in: ESTIMATED; calibrated against a shim step: CALIBRATED); the page shows the step as a fraction of the objective's depth of field (about 0.3 is good).
  6. Inspect: move X-Y to grow the mosaic; turn the fine focus slowly from clearly below to clearly above the surface and stop. The sweep is detected, checked for completeness and reconstructed in the background (or only kept, with "Reconstruct sweeps automatically" off; "Reconstruct last sweep" builds it on demand). The view stays on the current tab; the result line under the coach describes the selected map (its own objective, X-Y and Z status, valid area, warnings), separately from the live capture in the header. Space starts/stops a manual capture. "Repeat sweep here" measures repeatability (σ_inst). On a still view, "Stack still frames", super-resolution (where the camera undersamples the optics) and "HDR still" (with a measured camera response) make a still image; "Export still image…" saves it with provenance.

Tabs: Live (with in-focus outlines and magenta stripes on clipped pixels; "Move slower" hint on fast pans), Mosaic (image mosaic with the stitched height maps as an adjustable colour overlay, or heights alone; live camera box), All-in-focus (with grain boundaries, experimental super-resolution), Height (height / raw / confidence, profile tool), 3D, Report. Exports: Gwyddion .gsf, 32-bit TIFF (NaN = no depth), binary STL (visualisation), each with a validity mask and a provenance JSON; report bundle (strict JSON, CSV, PNG, mask), written completely or not at all; versioned session files (schema 2), also for a mosaic alone.

Pipeline

Stage Method
Capture MJPG via V4L2 (Linux, v4l2-ctl for controls) or OpenCV; latest-frame pull model for the live view; every frame keeps its source sequence number and time
Recording / replay one writer (MJPEG bytes, or lossless PNG when the backend decodes), checked writes, a manifest with per-frame file, sequence, time, size and CRC; replay validates the manifest, skips damaged frames as gaps; an ordered mode with back-pressure for exhaustive, deterministic analysis (microtopos-batch)
Motion state phase correlation + sharpness trend on a 320 px copy, every feature normalised by its own quiet-time noise, entry/exit hysteresis, scene-cut detection that first checks for a fast (blurred) pan with a band-pass match
Mosaic band-pass phase correlation refined by ECC (motion blur splits the phase-only peak), verified by normalised cross-correlation, motion-predicted acceptance of weaker matches, keyframe pose graph with consistency-checked loop closures, unbounded 512 px tiles, relocalisation after tracking loss, separate areas when a view cannot be placed
Height mosaic every height map pinned to its keyframe (moves with pose-graph corrections) in the mosaic it was captured in; least-squares levelling and feathered blending only among maps of the same height quantity (unit, sign, scale basis); others are kept as separate groups; .gsf export with mask; display rendering bounded to ~1600 px; sparse pose-graph solve
Sweep monotonic segmentation from z labels or from tiles that come into focus twice (reversal); pause removal when z is unknown; hand-sweep z = source frames of knob movement × the sweep's scale × its stated sign
Registration translation-only ECC between consecutive frames (parallel), chained; failed pairs inherit ECC-valid neighbour motion; unobservable motion (no texture) is zero, never an invented shift; pixels not observed in every frame are excluded from depth
Depth focus volume (DoG band-pass default), Gaussian peak fit (log-parabola, 5 samples) on the actual z values, confidence from peak prominence and curve noise, NaN where unreliable, confidence-weighted guided filter with outlier rejection
All-in-focus streaming Laplacian-pyramid fusion with softmax weights at full capture resolution
Metrology polynomial form removal (0 = mean only … 3 = cubic), ISO 16610-61 Gaussian S/L filters (σ = 0.1874 λ; refused below 4 px per cut-off), Sa Sq Sp Sv Sz Ssk Sku, triangulated Sdr (µm only), Sk Spk Svk Smr1 Smr2 (40 % secant, tie-safe crossings), Sal Str Std (lag-support-aware autocorrelation), radial PSD slope and fractal dimension (only for 2 < β < 4); height groups withheld when < 30 % of pixels are reliable, with the reason per group. GLCM texture and h-minima watershed regions (Feret, Heyn intercept, ASTM E112-style G) come from the all-in-focus image and are labelled image-based
Still images one preparation for every still product (stills.prepare): frames rebuilt from the camera's JPEG data when present (exact decoder luma, quantisation-constrained deblocking, luma-guided 4:2:2/4:2:0 chroma), dark/flat and linearisation as live, white balance on colour only
Stacking ECC translation registration, Lanczos-4 resampling, per-frame brightness gain (ratio of means), per-pixel sigma-clipped mean about the median (MAD scale, floored at the unresampled noise), per-pixel frame count instead of border fill, temporal noise estimate, optional Richardson–Lucy
Super-resolution drizzle (true drop-overlap weights) onto a 2× (linear) grid of still frames with ECC sub-pixel shifts, Richardson–Lucy with a discrepancy stop; frames without a valid registration are dropped, too little sub-pixel motion is refused, and so is a grid finer than the Nyquist pixel λ/4NA; experimental
Camera response / HDR Debevec–Malik (sparse least squares, samples spread over the scene's brightness), monotonic and still-scene checks, refusal when a longer exposure does not brighten the frames; hat-weighted two-pass bracket merge to relative radiance
Estimated flat pairwise log ratios of panned frames at their measured shift, a degree-4 polynomial of log shading, readiness from pairs, travel and direction spread
Edge sharpness slanted-edge method: sub-pixel line fit to the edge, 4× oversampled edge spread function, windowed line spread function, MTF with the bin boxes divided out, MTF50; Gaussian blur fitted with the projected pixel aperture removed
Colour fringes R and B against G: isotropic scale about the centre plus shift, from translation ECC of 32 px tiles on band-passed planes after a Lanczos pre-warp, least squares, significance from the tile scatter
Lens distortion Brown radial k1, k2 about the centre (r = 1 at the half-diagonal), from forward–backward-checked feature tracks of panned frames on a high-passed log image, robust least squares with a free translation per pair
Rolling shutter affine ECC between a still and a fast-pan frame; the shear and stretch terms are linear in the readout fraction; deskew about the middle row with velocities per source frame
Compute CPU reference; optional OpenCL DoG focus measure (ZSettings.backend), CPU fallback, parity-checked; jobs check their memory need against available RAM before starting

Verified (microtopos-selftest, seeds 11/22/33: 130 checks passed, 0 failed, 30 informational)

Measured 2026-11-05 on an i5-8365U laptop (4 cores, Linux Mint, Python 3.14, NumPy 2.5, OpenCV 5.0); --json FILE records every row with thresholds and versions. The gate counts every failing verdict, NumPy booleans included; an exception, an empty check or a non-boolean verdict is a failure; CI checks that a deliberately failing row makes the command exit 1.

Simulator ground truth (every instrument parameter randomised per seed):

  • Depth at 40×/0.85 with known z: Pearson r 0.994–0.998, height slope 0.979–0.994, RMSE 0.07–0.08 µm (0.1 DOF), 94–97 % valid pixels. At 10×/0.25: r 0.990–0.996, slope 0.972–0.985.
  • Signed step (two terraces, +1.60 µm, rendered with a blur law independent of the reconstruction's optics model): known z up and down, a hand sweep with the direction stated, the same frames reversed, and every other frame kept all give +1.60 µm (±0.003). A reversed sweep without a stated direction is flagged as unknown orientation; the old index spacing, kept as a negative control, halves the step (+0.80 µm).
  • Hand sweep with unknown z (variable speed, pause) and the direction stated: signed rank correlation 0.994–0.998.
  • Registration on informative frames: 0.09–0.16 px RMS; identical blank frames give no motion (the old code returned half the frame size) and super-resolution refuses them. Mosaic loop: 0.45–0.89 px RMS.
  • Tracking loss (jump to unmapped ground and back): every tile within about 1.1 px of its true place.
  • Fast hand pans with motion blur (30 and 60 px/frame at 640 px): no false view changes, one mosaic area, end position error 0.5–1.2 px. At 90 px/frame tracking holds but drifts 8–21 px (measured for v0.7, not rerun).
  • Metrology on synthetic surfaces: Voronoi grain count within 25 %, 50 µm grid intercept within 5 µm, Sdr exact on a tilted plane, Std of grooves along their direction, Str < 0.3 for grooves and > 0.5 isotropic, plateau surface Svk > 3 Spk. Edge cases: patterned missing pixels withhold Sal/Str; a flat field gives no Std and no numeric warning; form order 0 keeps the tilt; Gaussian transmission 0.502 at 4 px and 0.500 at 8 px, refused below 4 px; an exact and a 1e-6-perturbed plateau give the same Smr2 (90 %) and Svk; Vollath F4/F5 have no wrap-around; the DOF ruler gives no estimate on a blank crop.
  • µm and focus-frame maps are never blended in the height mosaic; "um" and "µm" are the same unit.
  • No false Z sweeps in 300 still or 200 panning frames; reversals found within 2 frames; objective change detected for an instant switch and a turret with dark frames.
  • Textureless patch: 91–97 % masked. ISO Gaussian filter: 0.500 transmission at the cutoff.
  • 48 frames at 1920×1080: 4.1 s end to end on this laptop (target ≤ 15 s; 2.8–4.2 s in earlier runs).

Pipeline tests (pytest): recordings (raw JPEG and decoded PNG modes, a non-JPEG buffer refused, a non-empty folder refused, a failed write visible with the manifest marked incomplete), legacy manifests with a count mismatch, damaged replay frames as sequence gaps with the engine still running, an engine error that does not stop the engine, dark frames cancelled by a source or size change, a late height map not pinned into a restarted mosaic, a source switch that does not skip the new source's first frame, exact keyframe correction, strict report JSON, an encoder failure that leaves no partial bundle, session round trip (original arrays and warnings) and validation, export masks and provenance, a deterministic batch run, and sign/scale rescaling.

Real specimen (--real recordings/…, texture and noise from the Bresser camera on a metallurgical sample):

  • Stitching along a known path: 40/40 frames tracked, 0.21 px RMS.
  • Depth over a known synthetic relief (real texture blurred by the optical model): r 0.986, slope 0.993, RMSE 0.91 µm (0.09 DOF), 80 % valid.
  • Camera: MJPG 1920×1080 at 12.5 fps (it advertises 25), all frames processed; 3 min still: 2,236 frames, no false detections, memory flat. These real-camera numbers are from v0.6/v0.7 runs; the recording itself is not in the repository.

Known limits (stated, not hidden)

  • Manual Z: a hand sweep assumes a constant knob speed while moving; its scale holds for that sweep only, and its sign is unknown unless stated. A stepped sweep removes the speed assumption but relies on every turn being the stated number of divisions and every pause lasting at least 3 frames; a hesitation of 3 frames inside a turn counts as a pause. Its knob calibration is only as good as the shim's thickness, its flatness on the base, and the step fit (reported as a standard error). A measured Z (the stage drivers) removes this, but it has only been exercised with the simulator and a fake Grbl, and a stage that settles or jitters in z is handled only for repeated labels: equal z runs are merged into one frame, jitter inside a position is not modelled.

  • Physical accuracy, uncertainty and ISO/ASTM equivalence are not established: no certified flatness, step-height, pitch-grid or roughness reference has been measured, and no clause-by-clause standards audit was done. The simulator shares the reconstruction's optics model; the new signed-step control uses an independent blur law.

  • The optional OpenCL focus measure matched the CPU (relative L2 1e-7) and was 4 % faster than the best CPU setting for one 960×540 frame on an Intel UHD 620 (i5-8365U laptop). That is not a measured end-to-end gain, so the CPU stays the default. CUDA, Vulkan, SYCL and NPU paths are not implemented.

  • The reconstruction holds the input frames in memory (one preallocated stack per stage and an admission check). Strip-wise tiling bounds the working memory of the focus computation, but there is no spill to disk, so a very long sweep can still exceed memory.

  • The GUI has not had a usability study, a keyboard-only walkthrough or native high-DPI checks; the offscreen smoke test drives it programmatically only. The window fits 1280×720 with both panels.

  • Super-resolution beat a bicubic single frame on all three seeds in this run (nRMSE 0.29–0.46 vs 0.37–0.50) but tied on one seed earlier; it is experimental, reported and not gated. Its 2× is per axis (4× the pixels), and a real resolution gain on optical targets has not been measured.

  • The DOF ruler's µm/frame estimate was off by −34 % to +13 % in simulation; it is stored as an ESTIMATED scale.

  • Image-quality tools (v0.11): JPEG restoration and stacking gains were measured against simulator ground truth. On real frames only internal figures exist (noise, blockiness); there is no optical target. The estimated flat, the camera response and HDR ran on simulated cameras only. A 1080p stack of 16 frames with JPEG restoration takes about 20 s on a laptop CPU.

  • JPEG compression costs height accuracy that no restoration recovers. Simulated sweeps encoded like the MikrOkular (quality 43, 4:2:2) had 4–16 % higher height RMSE than uncompressed ones (4×, 10× and 40×, three seeds each). Every usable focus measure lost 8–20 % at 10×, and DoG band-pass stayed the most accurate. Restoring each frame from its JPEG data recovered 0–1 %, so sweeps are not restored: the lost detail was removed by the camera's quantisation. A camera that sends uncompressed frames is the remedy.

  • Focus breathing (magnification change with focus) is not corrected by default: two estimators were biased by defocus more than the breathing itself (about 1 px at the image edges in far-defocused frames). The opt-in correction on the 3D tab is experimental and caps the excursion it applies at 1.5 % over a sweep.

  • The magnification guess after an objective change is a texture-scale heuristic and is not validated; the prompt always offers all objectives in the list.

  • The simulator scales its relief to each objective's depth of field so every objective can be demonstrated.

  • Not implemented: Laplacian-pyramid blending (the multiband option is a two-band blend; feathering is the default).

  • A lateral calibration covers capture modes with the aspect ratio it was measured at; another aspect ratio gets no guessed scale and needs its own calibration. Calibrations saved without a recorded frame size (older files) are scaled by image width for every mode, as before.

  • Mosaic keyframes are placed on whole pixels, so a keyframe sits up to half a pixel from its tracked position (0.25, 0.5 and 0.25 px at fractions 0.25, 0.5 and 0.75, measured on a blob). Sub-pixel resampling would soften the tiles and has to keep the un-splat used by the graph relaxation exact; it is not done.

  • Focus measures convert integer frames to float before differencing; the intensity scale is preserved, not normalised, so a uint16 frame holding 257 times the values of a uint8 frame scores 257 times higher in amplitude.

  • OpenCV 5.0's phaseCorrelate modifies its inputs when given a window; all calls go through a wrapper that avoids this (registration.phase_shift).

Contributing

Read AGENTS.md first; it applies to people and AI agents alike. In short: every new or changed test must fail on the base branch (tools/tests_bite.py, run by CI on every pull request) or carry @pytest.mark.characterization("reason"); tests may not skip themselves, and CI turns any skip whose reason is not an absent capability into a failure; documentation must say only what the code does, and what was verified only against a simulator must say so.