From 3135505d6318f13ae3e244afd33b6534909f0f8e Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Thu, 26 Nov 2026 00:16:03 -0800 Subject: [PATCH] egocap: calibration library, command line, and rectification tables at launch Add the station-side calibration code of the Ego Capture example: a library under recording/egocap/calibration, a command line (recording/tools/calibrate_station.py), and a launcher that starts the camera bridge with a rectification table. Camera calibration - Lens calibration from a ChArUco board take under a pinhole or a fisheye model, graded excellent, acceptable or bad; the grade decides what may be installed. - The head camera's position on the headset (hand-eye), with a search for the camera's lag against tracking. - Head tracking that fails during the take is told from the head track: where the position stops following the head's turning its samples are left out, and where the position leaps the take is split and the longest sound stretch is solved. The record and the log state what the take read. - A live guide a caller feeds pictures and head poses: views, coverage, head motion and head-tracking health, each with what it asks for. Controller-to-glove offsets - The least-squares fit and the projection a labelling tool draws. Rectification - A planner with explicit geometry: output size, balance, field-of-view scale or a stated output camera matrix, and optional oversampling. A plan that would leave pixels without a source is refused unless borders are allowed. - It writes the remap table the bridge's rectify step loads, and an offline rectified copy of a take. - tools/start_system.py reads the station's plan, writes a table per planned stream, starts the bridge with it and records what it applied. --no-rectify starts without correction. Station files - One home for file names and readers; installs are atomic, archive what they replace and are logged with who installed them. In a session recorded with correction each camera's intrinsics file describes the recorded picture, and the lens calibration is kept beside it. Aligner - Camera times are moved by the lag calibration measured before aligning, and the aligned episode records what was taken off. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/recording/README.md | 71 +- .../recording/egocap/calibration/__init__.py | 5 + .../recording/egocap/calibration/board.py | 282 ++ .../egocap/calibration/camera_lag.py | 128 + .../egocap/calibration/camera_model.py | 350 +++ .../egocap/calibration/camera_pipeline.py | 869 ++++++ .../egocap/calibration/extrinsics.py | 890 ++++++ .../recording/egocap/calibration/files.py | 313 ++ .../recording/egocap/calibration/frames.py | 52 + .../recording/egocap/calibration/grading.py | 536 ++++ .../recording/egocap/calibration/guidance.py | 956 ++++++ .../recording/egocap/calibration/hand_view.py | 333 +++ .../egocap/calibration/intrinsics.py | 557 ++++ .../egocap/calibration/rectification_files.py | 456 +++ .../recording/egocap/calibration/rectify.py | 1035 +++++++ .../egocap/calibration/rectify_take.py | 447 +++ .../egocap/calibration/station_store.py | 388 +++ .../recording/egocap/calibration/take.py | 259 ++ .../egocap/calibration/wrist_offset.py | 461 +++ .../egocap/recording/aligned_writer.py | 97 +- .../recording/egocap/recording/alignment.py | 43 +- .../egocap/recording/tools/align_episode.py | 8 +- .../recording/tools/calibrate_station.py | 1018 +++++++ .../unit/calibration_rectify_helpers.py | 218 ++ .../recording/unit/calibration_synthetic.py | 443 +++ .../unit/calibration_wrist_helpers.py | 202 ++ .../recording/unit/test_align_kept_episode.py | 84 + .../recording/unit/test_aligned_camera_lag.py | 565 ++++ .../recording/unit/test_aligned_writer.py | 49 + .../recording/unit/test_calibration_board.py | 255 ++ .../unit/test_calibration_camera_lag.py | 141 + .../unit/test_calibration_camera_model.py | 548 ++++ .../unit/test_calibration_camera_pipeline.py | 1584 ++++++++++ .../unit/test_calibration_extrinsics.py | 1318 +++++++++ .../recording/unit/test_calibration_files.py | 390 +++ .../recording/unit/test_calibration_frames.py | 50 + .../unit/test_calibration_grading.py | 1302 +++++++++ .../unit/test_calibration_guidance.py | 1688 +++++++++++ .../unit/test_calibration_hand_view.py | 593 ++++ .../unit/test_calibration_intrinsics.py | 1126 +++++++ .../test_calibration_rectification_files.py | 715 +++++ .../unit/test_calibration_rectify.py | 1907 ++++++++++++ .../unit/test_calibration_rectify_take.py | 1147 ++++++++ .../unit/test_calibration_station_store.py | 991 +++++++ .../recording/unit/test_calibration_take.py | 413 +++ .../unit/test_calibration_wrist_offset.py | 738 +++++ .../tests/tools/test_calibrate_station.py | 2594 +++++++++++++++++ .../egocap/tests/tools/test_start_system.py | 965 +++++- examples/egocap/tools/start_system.py | 376 ++- 49 files changed, 29917 insertions(+), 39 deletions(-) create mode 100644 examples/egocap/recording/egocap/calibration/__init__.py create mode 100644 examples/egocap/recording/egocap/calibration/board.py create mode 100644 examples/egocap/recording/egocap/calibration/camera_lag.py create mode 100644 examples/egocap/recording/egocap/calibration/camera_model.py create mode 100644 examples/egocap/recording/egocap/calibration/camera_pipeline.py create mode 100644 examples/egocap/recording/egocap/calibration/extrinsics.py create mode 100644 examples/egocap/recording/egocap/calibration/files.py create mode 100644 examples/egocap/recording/egocap/calibration/frames.py create mode 100644 examples/egocap/recording/egocap/calibration/grading.py create mode 100644 examples/egocap/recording/egocap/calibration/guidance.py create mode 100644 examples/egocap/recording/egocap/calibration/hand_view.py create mode 100644 examples/egocap/recording/egocap/calibration/intrinsics.py create mode 100644 examples/egocap/recording/egocap/calibration/rectification_files.py create mode 100644 examples/egocap/recording/egocap/calibration/rectify.py create mode 100644 examples/egocap/recording/egocap/calibration/rectify_take.py create mode 100644 examples/egocap/recording/egocap/calibration/station_store.py create mode 100644 examples/egocap/recording/egocap/calibration/take.py create mode 100644 examples/egocap/recording/egocap/calibration/wrist_offset.py create mode 100755 examples/egocap/recording/tools/calibrate_station.py create mode 100644 examples/egocap/tests/recording/unit/calibration_rectify_helpers.py create mode 100644 examples/egocap/tests/recording/unit/calibration_synthetic.py create mode 100644 examples/egocap/tests/recording/unit/calibration_wrist_helpers.py create mode 100644 examples/egocap/tests/recording/unit/test_aligned_camera_lag.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_board.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_camera_lag.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_camera_model.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_camera_pipeline.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_extrinsics.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_files.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_frames.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_grading.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_guidance.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_hand_view.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_intrinsics.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_rectification_files.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_rectify.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_rectify_take.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_station_store.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_take.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_wrist_offset.py create mode 100644 examples/egocap/tests/tools/test_calibrate_station.py diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index 59a9f1c677..5e71b5b992 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -6,11 +6,11 @@ SPDX-License-Identifier: Apache-2.0 # recording -The recording module library: configuration I/O, episode storage/layout, video writers, QC and -studio/task-library lookups. A Python module library, not a runnable application — nothing here -is launched, it's imported, by the recording service (`recording_service/`) and the backend. See -the root [`README.md`](../README.md) for install, and [`../DESIGN.md`](../DESIGN.md) for how -this fits into the overall architecture. +The recording module library: configuration I/O, episode storage/layout, video writers, QC, +station calibration and studio/task-library lookups. A Python module library, not a runnable +application — nothing here is launched, it's imported, by the recording service +(`recording_service/`) and the backend. See the root [`README.md`](../README.md) for install, and +[`../DESIGN.md`](../DESIGN.md) for how this fits into the overall architecture. This package never opens a physical camera or reads a device SDK directly — a camera is a JPEG byte stream and tracking is a sample, both arriving over CaptureServer's own WebSocket protocol @@ -49,6 +49,8 @@ Calibration copying is best-effort either way: a file simply absent at that loca with a warning, recording still proceeds. Calibration files are optional unless the deployment requires them: the web backend holds a station in use from recording over a missing file only while its operator setting `require_calibration` is on (see [`backend/README.md`](../backend/README.md)). +The files are made and installed by the calibration tools +(see [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md)). `video_sources`/`numeric_sources` declare the *recorded dataset*, not how to open a device — no device handle, index, or launcher path belongs in them. See @@ -79,7 +81,32 @@ actually having data to work with. Provisioning real/fixture CSVs is a deploymen `episode_store.py`'s `EpisodeStore` owns per-episode Zarr/MP4 storage: appending numeric rows and video frames, and the dataset-level `studio`/Mid-Train `inverse`/`props` zarr attrs. Images -are recorded as received, with no rectification applied. +are stored as they are received; nothing in this package corrects one. What is received need not be +what the lens delivered: a camera that reaches the station through the camera bridge is recorded as +the bridge publishes it, which is corrected (rectified) when the launcher applied the station's +rectification plan to its stream. A session recorded in such a run says so in its files: the +corrected camera's intrinsics file describes the recorded, corrected pictures, the lens they were +corrected from is kept beside it under a lens name, and `rectification.json` names the corrected +cameras with everything that was done. A rectified copy of a take can also be written offline, +outside the recording, by `tools/calibrate_station.py rectify`. See +[`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#what-is-recorded). + +`aligned_writer.py` writes the time-aligned copy of a kept episode into a session of its own. It +pairs each picture with the tracking of the moment the picture shows: when the head-camera +extrinsics file the session carries states the camera's lag (`camera_latency_s`, found by the +headset calibration), that lag is taken off the times of every camera of the episode before +anything is paired, moved by what the recorder's tracking latency has changed by since the lag was +measured when the file states that too. An aligned episode that had a lag taken off records it in +its `camera_lag` attribute: `taken_off_s`, the `cameras` it came off, the `source` file and the +values it was made from (`camera_latency_s`, `tracking_latency_s`, `take_tracking_latency_s`). Its +`valid_timestamps` are then the index frames' recorded times less `taken_off_s`, the moments the +pictures show on the tracking's time base, while each camera's own `capture_time` stays as +recorded. An episode without the attribute was aligned on its recorded times: its session had no +such file, or one that states no usable lag or was not made with this project's tracking. An +episode whose session states a lag for a stated tracking latency, while the take does not say which +latency it was recorded under, is refused. The session's calibration files, the lens files and +`rectification.json` among them, are carried into the aligned session as they are. See +[`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#camera-lag-in-aligned-takes). `episode_layout.py` owns the on-disk layout: pending/final directory naming, studio/timestamp routing (`assign_output`/`finalize_episode_dir` route each finalized episode to @@ -94,6 +121,18 @@ rest of the package's atomic writes build on. failure to `/errors.jsonl` — a tail-able, greppable record independent of the Zarr store. +## Calibration — `egocap/calibration/` + +Camera intrinsics under OpenCV's radial-tangential (`pinhole`) or `fisheye` lens model, the head +camera's position on the headset, the controller-to-glove wrist offset, and installing the results +into the station's calibration directory; the rule for a stored camera lag, which the glove tool +and the time aligner share; and rectification: the gates on a calibration, the plan of a corrected +picture from an explicit geometry and oversample, the remap table file the camera bridge's GPU step +loads, and the offline corrected copy of a take. The backend's calibration tools, +`tools/calibrate_station.py` and the launcher (`../tools/start_system.py`) are built on it. What each +module does, the limits it applies and how an operator uses the tools are in +[`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md). + ## Analytics — `egocap/analytics/` - `station_status_log.py`'s `StationStatusTracker` is a per-station, per-day active/inactive @@ -142,6 +181,9 @@ What the recording service writes into each routed group: │ ├── head_camera_intrinsics.json, head_camera_extrinsics.json │ ├── left_wrist_camera_intrinsics.json, right_wrist_camera_intrinsics.json │ ├── wrist_calibration_offsets.json +│ ├── rectification.json # only when the run corrected a camera's video +│ ├── head_camera_lens_intrinsics.json # only for a camera whose video was corrected; +│ │ # likewise left_wrist_... and right_wrist_camera_lens_intrinsics.json │ ├── episode_0/, episode_1/, ... │ └── ... └── _unmatched/ # descriptions matching no known studio @@ -150,7 +192,11 @@ What the recording service writes into each routed group: Calibration files appear only when present at `EGOCAP_CALIBRATION_DIR` (which always has a resolved value, see above -- absence there is a skip, not a configuration requirement); the -service does not write a separate `data_check_config.yaml`. +service does not write a separate `data_check_config.yaml`. In a run whose capture stack corrects a +camera's video the web backend supplies required assets for it: `rectification.json`, the +corrected camera under the role's intrinsics file name, and the station's lens file under the +role's lens name. A session is not opened without them, and a session that has no +`rectification.json` holds no corrected video. The per-group `config.yaml` carries the source declarations time alignment reads (the `video_sources`/`numeric_sources` names, frame types and recording defaults); a data-loading @@ -179,6 +225,13 @@ hardware (see `capture_server/README.md`'s "implemented but not exercised on har Calibration assets are copied into every session under their established filenames when available: head camera intrinsics and extrinsics, left/right wrist camera intrinsics (wrist -cameras have no separate extrinsics file), and the wrist-to-hand `wrist_calibration_offsets.json`; +cameras have no separate extrinsics file), and the controller-to-glove wrist offsets, +`wrist_calibration_offsets.json`; a session recorded without calibration present still produces valid video/tracking data, just -without those sidecar files. +without those sidecar files. A session's intrinsics file describes the video the session holds. For +a camera recorded as received that is the station's lens calibration. For a camera listed in the +session's `rectification.json` the recorded pictures are corrected ones, and the session's +intrinsics file for that role is the corrected camera, a pinhole camera without distortion; the +lens the pictures were corrected from is in the role's lens file +(`head_camera_lens_intrinsics.json`, `left_wrist_camera_lens_intrinsics.json`, +`right_wrist_camera_lens_intrinsics.json`), which does not describe the recorded pictures. diff --git a/examples/egocap/recording/egocap/calibration/__init__.py b/examples/egocap/recording/egocap/calibration/__init__.py new file mode 100644 index 0000000000..9c75e5cb5e --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Station calibration: camera intrinsics, head-camera extrinsics, controller-to-glove offsets, rectification.""" diff --git a/examples/egocap/recording/egocap/calibration/board.py b/examples/egocap/recording/egocap/calibration/board.py new file mode 100644 index 0000000000..924496643b --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/board.py @@ -0,0 +1,282 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The ChArUco calibration board: describing it, finding it in an image, and judging an image's sharpness. + +A ChArUco board is a chessboard with an ArUco marker in every white square. Its inner chessboard corners are +identified one by one, so a view showing only part of the board is still usable. Lengths are in meters and +image points in pixels. +""" + +from __future__ import annotations + +import math +import numbers +from dataclasses import dataclass +from typing import Any + +import cv2 +import numpy as np + +#: Fewest squares along a side that still leaves inner corners to find. +_MIN_SQUARES = 3 +#: More squares than any printed board has; larger values are typing mistakes. +_MAX_SQUARES = 64 +#: Corners a layout must find in a frame before that frame says anything about which layout is printed. +_LOCK_MIN_CORNERS = 8 +#: Wins in a row after which the detector stops trying the other layout. +_LOCK_AFTER_WINS = 3 +#: Colour of drawn corners (BGR), chosen to stand out on a black-and-white board. +_CORNER_COLOUR = (0, 255, 0) + + +class CalibrationError(ValueError): + """A calibration that cannot be done, for a reason an operator can act on. + + The message is shown to the operator as written, so it never contains a directory path. + """ + + +class BoardError(CalibrationError): + """A board description that no printed board could have.""" + + +def _is_length(value: Any) -> bool: + """Whether a value is a finite real number, which a bool is not.""" + return isinstance(value, numbers.Real) and not isinstance(value, bool) and math.isfinite(value) + + +@dataclass(frozen=True) +class BoardSpec: + """The printed board: its squares (columns, rows), their size, the marker size and the marker dictionary.""" + + squares: tuple[int, int] = (14, 9) + square_length_m: float = 0.04 + marker_length_m: float = 0.03 + dictionary: str = "DICT_5X5_1000" + + def __post_init__(self) -> None: + """Refuse a description OpenCV would accept silently and then never detect.""" + squares = self.squares + # A bool is an int to Python, and a board is not True squares wide. + counted = isinstance(squares, (tuple, list)) and len(squares) == 2 and all(type(n) is int for n in squares) + if not counted or not all(_MIN_SQUARES <= n <= _MAX_SQUARES for n in squares): + raise BoardError(f"the board needs between {_MIN_SQUARES} and {_MAX_SQUARES} squares along each side") + # A record read from JSON carries a list; the spec is hashable only with a tuple. + object.__setattr__(self, "squares", (squares[0], squares[1])) + # A square of a meter or more is a length typed in the wrong unit, not a board. + if not _is_length(self.square_length_m) or not 0 < self.square_length_m < 1: + raise BoardError("the square length must be more than 0 and less than 1 meter") + # A marker filling its square has no white margin left to be told apart by. + if not _is_length(self.marker_length_m) or not 0 < self.marker_length_m < self.square_length_m: + raise BoardError("the marker length must be more than 0 and less than the square length") + # Plain floats, so the record serialises whatever numeric type the lengths arrived as. + object.__setattr__(self, "square_length_m", float(self.square_length_m)) + object.__setattr__(self, "marker_length_m", float(self.marker_length_m)) + # OpenCV holds both lengths in single precision and, when they are no longer a positive marker inside a + # longer square there, fails in a way that corrupts its heap: such a board must never reach it. + if not np.float32(self.square_length_m) > np.float32(self.marker_length_m) > 0: + raise BoardError("the square and marker lengths are too small or too close together to tell apart") + name = self.dictionary + # OpenCV names its dictionaries by integer constants; nothing else in the module is one. + known = isinstance(name, str) and name.startswith("DICT_") and type(getattr(cv2.aruco, name, None)) is int + if not known: + raise BoardError(f"{name!r} is not an ArUco dictionary OpenCV knows") + # OpenCV builds a board whose markers run past the dictionary without complaint; none of it detects. + needed = squares[0] * squares[1] // 2 + available = int(self._dictionary().bytesList.shape[0]) + if needed > available: + raise BoardError( + f"{name} has {available} markers but a {squares[0]}x{squares[1]} board needs {needed}" + ) + + def _dictionary(self) -> cv2.aruco.Dictionary: + """OpenCV's marker dictionary of this board.""" + return cv2.aruco.getPredefinedDictionary(getattr(cv2.aruco, self.dictionary)) + + @property + def max_corners(self) -> int: + """Inner chessboard corners the whole board shows.""" + return (self.squares[0] - 1) * (self.squares[1] - 1) + + def charuco_board(self, legacy: bool = False) -> cv2.aruco.CharucoBoard: + """OpenCV's model of the board, in the current layout or the one older generators printed.""" + board = cv2.aruco.CharucoBoard( + self.squares, self.square_length_m, self.marker_length_m, self._dictionary() + ) + board.setLegacyPattern(legacy) + return board + + def to_record(self) -> dict[str, Any]: + """The board as the keys a calibration file stores it under.""" + return { + "charuco_squares": list(self.squares), + "square_length_m": self.square_length_m, + "marker_length_m": self.marker_length_m, + "aruco_dict": self.dictionary, + } + + @classmethod + def from_record(cls, record: dict[str, Any]) -> BoardSpec: + """The board a calibration file or a request describes; a missing key is a ``BoardError``.""" + keys = ("charuco_squares", "square_length_m", "marker_length_m", "aruco_dict") + # Anything but an object has none of the keys. + missing = [key for key in keys if not isinstance(record, dict) or key not in record] + if missing: + raise BoardError(f"the board description is missing {', '.join(missing)}") + return cls(*(record[key] for key in keys)) + + +@dataclass(frozen=True, eq=False) +class Detection: + """The board's corners found in one image.""" + + #: Pixel coordinates, shape (n, 2), float32. + corners: np.ndarray + #: Which inner corner of the board each one is, shape (n,). + ids: np.ndarray + #: Whether the legacy layout found them. + legacy: bool + + +@dataclass(frozen=True, eq=False) +class BoardView: + """One frame's view of the board, as a solver needs it: matching image and board points.""" + + #: The frame's index in its video. + frame: int + #: Which inner corner of the board each point is, shape (n,). + ids: np.ndarray + #: Pixel coordinates, shape (n, 2), float32. + image_points: np.ndarray + #: The same corners on the board, shape (n, 3), float32, in meters with Z zero. + object_points: np.ndarray + + @property + def corners(self) -> int: + """How many corners the view shows.""" + return len(self.image_points) + + @property + def spans_plane(self) -> bool: + """Whether the corners fix the board's pose: at least four, and not all along one line of the board. + + A board hanging off the edge of the image often shows a single row of corners, from which neither a + homography nor a pose follows. Board points that are not numbers span nothing. + """ + if self.corners < 4: + return False + board = self.object_points[:, :2].astype(np.float64) + # Said here, where a caller asks, and not by the decomposition below, which raises on them. + if not np.all(np.isfinite(self.object_points)): + return False + # The second singular value is how far the corners reach across their best-fitting line. + centred = board - board.mean(axis=0) + spread = np.linalg.svd(centred, compute_uv=False) + return bool(spread[1] > 1e-3 * spread[0]) + + +class BoardDetector: + """Finds the board in grayscale images, whichever of the two ChArUco layouts it was printed in. + + Generators before OpenCV 4.6 placed the markers on the other squares when the board has an even number + of rows. The inner corners and their ids are the same either way, so views from both layouts mix freely. + + Trying both layouts costs two detections per image, so the detector settles on one. Where the two layouts + are the same pattern it uses the standard one from the start. Otherwise a frame is a win for the layout + that finds more corners in it, provided it finds at least ``_LOCK_MIN_CORNERS`` (or the whole of a smaller + board); after ``_LOCK_AFTER_WINS`` wins in a row the other layout is no longer tried. A physical board + has one layout, so this never needs undoing. + """ + + def __init__(self, spec: BoardSpec) -> None: + """Build a detector per layout for ``spec``.""" + self.spec = spec + self._boards = {legacy: spec.charuco_board(legacy) for legacy in (False, True)} + self._detectors = {legacy: cv2.aruco.CharucoDetector(board) for legacy, board in self._boards.items()} + # Compared through the boards themselves so the rule for when the layouts differ stays OpenCV's. + markers = {legacy: np.asarray(board.getObjPoints()) for legacy, board in self._boards.items()} + self._settled: bool | None = False if np.array_equal(markers[False], markers[True]) else None + self._lock_corners = min(_LOCK_MIN_CORNERS, spec.max_corners) + self._leader: bool | None = None + self._wins = 0 + + @property + def legacy_layout(self) -> bool | None: + """The layout detection has settled on: True for legacy, False for standard, None while undecided.""" + return self._settled + + def _detect_layout(self, gray: np.ndarray, legacy: bool) -> Detection: + """One layout's corners in the image; an empty detection when it finds none.""" + corners, ids, _, _ = self._detectors[legacy].detectBoard(gray) + if ids is None: + return Detection(np.zeros((0, 2), np.float32), np.zeros(0, np.int32), legacy) + return Detection(corners.reshape(-1, 2).astype(np.float32), ids.reshape(-1).astype(np.int32), legacy) + + def _note_win(self, best: Detection) -> None: + """Count a frame's better layout towards settling on it; a frame with too few corners says nothing.""" + if len(best.ids) < self._lock_corners: + return + # A win for the other layout starts the count again, so one stray decode cannot decide it. + self._wins = self._wins + 1 if self._leader == best.legacy else 1 + self._leader = best.legacy + if self._wins >= _LOCK_AFTER_WINS: + self._settled = best.legacy + + def detect(self, gray: np.ndarray) -> Detection | None: + """The board's corners in a grayscale image, from the layout that finds more; None when none are found.""" + if self._settled is not None: + best = self._detect_layout(gray, self._settled) + else: + standard, legacy = self._detect_layout(gray, False), self._detect_layout(gray, True) + # A tie goes to the standard layout, the one current generators print. + best = legacy if len(legacy.ids) > len(standard.ids) else standard + self._note_win(best) + return best if len(best.ids) else None + + def object_points(self, detection: Detection) -> np.ndarray: + """Where the detected corners are on the board, shape (n, 3), from the layout that detected them.""" + board = self._boards[detection.legacy] + points, _ = board.matchImagePoints(detection.corners.reshape(-1, 1, 2), detection.ids.reshape(-1, 1)) + return np.asarray(points, dtype=np.float32).reshape(-1, 3) + + def view(self, frame: int, detection: Detection) -> BoardView: + """A detection in frame ``frame`` as the matched points a solver takes.""" + return BoardView(int(frame), detection.ids, detection.corners, self.object_points(detection)) + + +def as_gray(image: np.ndarray) -> np.ndarray: + """A grayscale copy of a BGR image; a grayscale image is returned as it is.""" + return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if image.ndim == 3 else image + + +def sharpness(gray: np.ndarray) -> float: + """How crisp the edges of a grayscale image are: about 1 for a step between two pixels, towards 0 as it smears. + + Along each image axis this is the energy of the second difference over that of the first, halved, which + for an edge spread over ``k`` pixels is about ``1 / k`` whatever the edge's contrast and however many + edges the image holds. The weaker axis is returned: motion blur smears along one direction and leaves the + edges that run along it crisp. An image with no edges at all scores 0. + """ + image = gray.astype(np.float64) + scores = [] + for axis in (0, 1): + first = np.diff(image, axis=axis) + energy = float(np.square(first).sum()) + # A flat image has no edge to be crisp or smeared. + scores.append(0.5 * float(np.square(np.diff(first, axis=axis)).sum()) / energy if energy else 0.0) + return min(scores) + + +def draw_corners(image_bgr: np.ndarray, corners: np.ndarray, ids: np.ndarray) -> np.ndarray: + """Draw detected corners and their ids onto a BGR image, in place; returns the image.""" + # OpenCV refuses an empty corner list. + if len(corners): + cv2.aruco.drawDetectedCornersCharuco( + image_bgr, + np.asarray(corners, dtype=np.float32).reshape(-1, 1, 2), + np.asarray(ids, dtype=np.int32).reshape(-1, 1), + _CORNER_COLOUR, + ) + return image_bgr diff --git a/examples/egocap/recording/egocap/calibration/camera_lag.py b/examples/egocap/recording/egocap/calibration/camera_lag.py new file mode 100644 index 0000000000..296565cfee --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/camera_lag.py @@ -0,0 +1,128 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""How far a take's camera pictures lag its tracking: the one rule for every program that pairs the two. + +The headset calibration finds the lag of the head camera's pictures against the tracking times of its own take +and stores it in the head camera's extrinsics record, with the latency the recorder had taken off those +tracking times when the take stated it. A station can change that latency, and every tracking time moves with +it, so the lag of another take is the stored one moved by what the latency has changed by. A positive lag +means a picture is that much older than its recorded time says: it comes off the camera's times. +""" + +from __future__ import annotations + +import logging +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +from .board import CalibrationError +from .files import HEAD_EXTRINSICS +from .take import MAX_TRACKING_LATENCY_S + +__all__ = [ + "CAMERA_LAG_KEY", + "LATENCY_UNKNOWN", + "MAX_CAMERA_LAG_S", + "TRACKING_LATENCY_KEY", + "CameraLag", + "CameraLagError", + "camera_lag_of_take", +] + +logger = logging.getLogger("isaaccapture.egocap.camera_lag") + +#: Where the head-camera extrinsics record states how far the camera's pictures lag the head tracking, and the +#: largest lag believed: a camera lags by tens of milliseconds, so more than this is a damaged value, and +#: shifting pictures by it would pair them with the poses of another moment. +CAMERA_LAG_KEY = "camera_latency_s" +MAX_CAMERA_LAG_S = 1.0 +#: Where the same record states the latency the recorder had taken off the tracking times that lag was measured +#: against, in seconds. The lag holds for takes recorded under that latency and no other. +TRACKING_LATENCY_KEY = "tracking_latency_s" + +#: Why a stored lag is not carried over to a take, in words for an operator. +LATENCY_UNKNOWN = ( + "The take does not say which tracking latency it was recorded under, so the camera lag stored with the " + "headset calibration cannot be applied to it. Record the take again." +) + + +class CameraLagError(CalibrationError): + """A stored camera lag that cannot be carried over to a take; the message is a sentence for an operator.""" + + +@dataclass(frozen=True) +class CameraLag: + """How far one take's camera pictures lag its tracking, with what the figure was made from.""" + + #: Seconds to take off the take's camera times before they are paired with tracking; zero when the + #: extrinsics record states no lag. + seconds: float + #: The lag as the extrinsics record states it; None when it states none, or none that is believed. + stored_s: float | None = None + #: The tracking latency the record says its lag was measured under; None when it does not say, and the + #: lag is then used as stored. + solved_under_s: float | None = None + #: The tracking latency the take was recorded under, as the caller read it from the take; None when the + #: take does not say. + recorded_under_s: float | None = None + + @property + def stated(self) -> bool: + """Whether the record states a lag at all. Without one nothing is known to take off, which a reader + of derived data must be able to tell from a measured lag of zero.""" + return self.stored_s is not None + + +def _seconds(value: Any, low: float, high: float) -> float | None: + """A JSON value as seconds when it is a number from ``low`` to ``high``, else None; a bool is not a number.""" + # The range also rejects NaN and the infinities, which compare false, and whole numbers no float can hold. + return float(value) if type(value) in (int, float) and low <= value <= high else None + + +def _stored_lag_s(extrinsics: Mapping[str, Any]) -> float | None: + """The lag the head camera's extrinsics record states, in seconds; None when it states none, or none that + is plausible.""" + stated = extrinsics.get(CAMERA_LAG_KEY) + lag = _seconds(stated, -MAX_CAMERA_LAG_S, MAX_CAMERA_LAG_S) + # Said in the log: pairing still works without the lag, only less well, and nothing else would show why. + # A file made before the lag was measured, or by another tool, states none and has nothing wrong with it. + if lag is None and stated is not None: + logger.warning( + "%s states no usable %s; pictures are paired with tracking unshifted", HEAD_EXTRINSICS, CAMERA_LAG_KEY + ) + return lag + + +def camera_lag_of_take(extrinsics: Mapping[str, Any], recorded_under_s: float | None) -> CameraLag: + """How far a take's camera pictures lag its tracking, from the head camera's extrinsics record. + + ``recorded_under_s`` is the latency the recorder took off the take's tracking times + (``CalibrationTake.tracking_latency_s()``), None when the take does not say. A record that states no lag + gives zero seconds. A lag stored with the latency it was measured under is moved by what the latency has + changed by, and is a ``CameraLagError`` for a take that does not say its own; a lag stored without it is + used as it is. + """ + stored_s = _stored_lag_s(extrinsics) + # With no lag to move, pictures are paired with tracking as they are stamped, whatever the take says. + if stored_s is None: + return CameraLag(0.0) + solved_under_s = _seconds(extrinsics.get(TRACKING_LATENCY_KEY), 0.0, MAX_TRACKING_LATENCY_S) + # A record that does not say what its lag was measured against cannot be held against the take: the lag + # is taken as it is, which is right as long as the station's tracking latency has not been changed. + if solved_under_s is None: + logger.info( + "%s does not state the %s its camera lag was measured under; the lag is used as stored", + HEAD_EXTRINSICS, + TRACKING_LATENCY_KEY, + ) + return CameraLag(stored_s, stored_s, None, recorded_under_s) + # Guessing that the take was recorded under the same latency would pair its pictures with the poses of + # another moment whenever the guess is wrong, and nothing would show it. + if recorded_under_s is None: + raise CameraLagError(LATENCY_UNKNOWN) + # Tracking times moved earlier by a latency leave the camera's times that much later against them. + return CameraLag(stored_s + (recorded_under_s - solved_under_s), stored_s, solved_under_s, recorded_under_s) diff --git a/examples/egocap/recording/egocap/calibration/camera_model.py b/examples/egocap/recording/egocap/calibration/camera_model.py new file mode 100644 index 0000000000..7c68176cd6 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/camera_model.py @@ -0,0 +1,350 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What depends on a camera's lens model: where a point lands in the picture, which way a pixel looks, and how +the board stands in front of the camera. + +``files`` names the two models, OpenCV's radial-tangential one (pinhole) and its fisheye one; a corrected +picture is a pinhole camera whose coefficients are all zero. Each model has its own OpenCV functions, and one +model's coefficients fed to the other's give a plausible wrong answer, so every other module comes here with +an ``Intrinsics`` and none calls OpenCV's projection, undistortion or pose functions for a calibrated camera. + +Points are in the camera's optical frame (X right, Y down, Z along the view), in meters; pixels are (u, v). +""" + +from __future__ import annotations + +import math +from typing import Any + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +from .board import BoardView +from .files import FISHEYE, Intrinsics +from .frames import homogeneous + +#: A point nearer the camera plane than this, or behind it, has no pixel. +_MIN_DEPTH_M = 1e-6 +#: How far, in pixels, a pixel's ray may land from the pixel when projected again and still be believed. +_ROUND_TRIP_PX = 0.5 +#: Halvings of a radial curve's interval: each gains a bit, and a double has 52. +_BISECTIONS = 52 +#: How near the radial curve must come to a pixel's radius, as a share of it, for the pixel to lie on the +#: curve's rising part: far above what the halving leaves, far below a pixel. +_ON_CURVE = 1e-9 +#: Newton steps from the radial curve's answer to the whole radial-tangential model's. The tangential terms +#: move a ray by a few percent of its length, and each step squares what is left of that. +_NEWTON_STEPS = 6 +#: Columns of OpenCV's radial-tangential projection Jacobian that say how a pixel moves with its point +#: across the view: those of the translation's first two parts. +_PINHOLE_ACROSS_COLUMNS = slice(3, 5) +#: Columns of OpenCV's fisheye projection Jacobian: the camera's numbers first, then the pose. +_FISHEYE_CAMERA_COLUMNS = slice(0, 8) +_FISHEYE_POSE_COLUMNS = slice(8, 14) +#: Columns of its radial-tangential one: the pose first, then the camera's numbers. +_PINHOLE_POSE_COLUMNS = slice(0, 6) + + +def _smallest_positive_root(coefficients: np.ndarray) -> float: + """The smallest positive real root of a polynomial given lowest power first; infinity when it has none.""" + roots = np.roots(coefficients[::-1]) + real = roots.real[(np.abs(roots.imag) < 1e-9) & (roots.real > 0.0)] + return float(real.min()) if real.size else math.inf + + +def field_limit_deg(intrinsics: Intrinsics) -> float: + """The angle from the optical axis at which a model's radial curve stops rising, and 90 degrees at most. + + Past it the model folds the scene back over the picture: a point further out lands nearer the centre + than one before it. The tangential and thin-prism terms of the radial-tangential model are left out; + they bend the curve by a hair and move no turning point by more. + """ + dist = np.asarray(intrinsics.dist, dtype=np.float64) + # Coefficients that are not numbers describe no lens, and nothing is within its reach. + if not np.all(np.isfinite(dist)): + return 0.0 + if intrinsics.model == FISHEYE: + # The picture radius is theta (1 + k1 theta^2 + ...); its slope, in powers of theta squared. + slope = np.array([1.0, 3.0 * dist[0], 5.0 * dist[1], 7.0 * dist[2], 9.0 * dist[3]]) + return math.degrees(min(math.sqrt(_smallest_positive_root(slope)), math.pi / 2.0)) + # The picture radius is r N(r^2) / D(r^2) with r the tangent of the angle. OpenCV takes this model's + # vector at several lengths, and the terms a shorter one leaves out are zero. + k1, k2, _, _, k3, k4, k5, k6 = np.concatenate([dist, np.zeros(8)])[:8] + numerator = np.polynomial.Polynomial([1.0, k1, k2, k3]) + denominator = np.polynomial.Polynomial([1.0, k4, k5, k6]) + square = np.polynomial.Polynomial([0.0, 2.0]) + # The slope's sign is that of (N + 2 s N') D - 2 s N D', in s = r^2; the curve also ends where D is zero. + slope = (numerator + square * numerator.deriv()) * denominator - square * numerator * denominator.deriv() + turn = min(_smallest_positive_root(slope.coef), _smallest_positive_root(denominator.coef)) + return math.degrees(math.atan(math.sqrt(turn))) + + +def project(points_camera: Any, intrinsics: Intrinsics) -> np.ndarray: + """Pixels (N, 2) of points in the camera's frame; NaN for a point the model cannot place. + + That is a point at or behind the camera plane, which both of OpenCV's projections mirror through the + principal point as though it were in front, and one further off the axis than ``field_limit_deg``. + """ + points = np.asarray(points_camera, dtype=np.float64).reshape(-1, 3) + pixels = np.full((len(points), 2), np.nan) + limit = field_limit_deg(intrinsics) + reach = math.tan(math.radians(limit)) if limit < 90.0 else math.inf + depth = points[:, 2] + with np.errstate(invalid="ignore"): + # A NaN point compares false and stays NaN, as a joint the glove left out must. + placed = (depth > _MIN_DEPTH_M) & (np.hypot(points[:, 0], points[:, 1]) < reach * depth) + if placed.any(): + still = np.zeros(3) + if intrinsics.model == FISHEYE: + projected, _ = cv2.fisheye.projectPoints( + points[placed].reshape(1, -1, 3), still, still, intrinsics.K, intrinsics.dist + ) + else: + projected, _ = cv2.projectPoints(points[placed], still, still, intrinsics.K, intrinsics.dist) + pixels[placed] = projected.reshape(-1, 2) + return pixels + + +def project_world(points_world: Any, T_camera_world: np.ndarray, intrinsics: Intrinsics) -> np.ndarray: + """Pixels (N, 2) of world points seen by a camera at a pose; NaN as for ``project``.""" + points = np.asarray(points_world, dtype=np.float64).reshape(-1, 3) + return project(points @ T_camera_world[:3, :3].T + T_camera_world[:3, 3], intrinsics) + + +def posed_projection( + object_points: np.ndarray, rvec: np.ndarray, tvec: np.ndarray, intrinsics: Intrinsics +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Pixels (N, 2) of an object's points at a pose, and how they move with the pose and with the camera. + + The pose is a rotation vector and a translation. The two Jacobians have a row per pixel coordinate (u + then v of each point): six columns for the pose, and for the camera its focal lengths, its principal + point and its distortion coefficients, in that order. No point is left out: this is for a solver walking + towards a pose, which needs a number everywhere. + """ + points = np.asarray(object_points, dtype=np.float64).reshape(-1, 3) + rvec, tvec = np.asarray(rvec, dtype=np.float64).reshape(3), np.asarray(tvec, dtype=np.float64).reshape(3) + unknowns = 4 + len(intrinsics.dist) + if intrinsics.model == FISHEYE: + projected, jacobian = cv2.fisheye.projectPoints( + points.reshape(1, -1, 3), rvec, tvec, intrinsics.K, intrinsics.dist + ) + pose, camera = jacobian[:, _FISHEYE_POSE_COLUMNS], jacobian[:, _FISHEYE_CAMERA_COLUMNS] + else: + projected, jacobian = cv2.projectPoints(points, rvec, tvec, intrinsics.K, intrinsics.dist) + pose, camera = jacobian[:, _PINHOLE_POSE_COLUMNS], jacobian[:, 6 : 6 + unknowns] + return projected.reshape(-1, 2), pose, camera + + +def _fisheye_radius(angle: np.ndarray, dist: np.ndarray) -> np.ndarray: + """The fisheye model's radial curve: how far from the principal point, in focal lengths, a ray at an + angle from the axis (radians) lands.""" + square = angle * angle + return angle * (1.0 + square * (dist[0] + square * (dist[1] + square * (dist[2] + square * dist[3])))) + + +def _fisheye_rays(points: np.ndarray, intrinsics: Intrinsics) -> np.ndarray: + """The directions of pixels (N, 2) under the fisheye model; NaN past where its radial curve stops rising. + + Do not use ``cv2.fisheye.undistortPoints`` for this. It clamps the curve's value at 90 degrees, which a + lens that spreads its rim reaches well inside its field, and from there on returns a finite direction + that is wrong: on 3 of 40 synthetic lenses sound to 90 degrees it was off from 76 to 79 degrees outward + (OpenCV 4.12). The curve rises up to ``field_limit_deg``, so halving that interval cannot go astray. + """ + K, dist = intrinsics.K, np.asarray(intrinsics.dist, dtype=np.float64) + # Skew is left out, as OpenCV's fisheye projection leaves it out. + plane = (points - [K[0, 2], K[1, 2]]) / [K[0, 0], K[1, 1]] + radius = np.hypot(plane[:, 0], plane[:, 1]) + low, high = np.zeros(len(radius)), np.full(len(radius), math.radians(field_limit_deg(intrinsics))) + reached = radius < _fisheye_radius(high, dist) + for _ in range(_BISECTIONS): + middle = 0.5 * (low + high) + beyond = _fisheye_radius(middle, dist) > radius + low, high = np.where(beyond, low, middle), np.where(beyond, middle, high) + angle = 0.5 * (low + high) + # At the principal point the direction is the axis itself, whatever zero over zero would say. + scale = np.divide(np.tan(angle), radius, out=np.ones(len(radius)), where=radius > 0.0) + rays = np.full(plane.shape, np.nan) + rays[reached] = plane[reached] * scale[reached, None] + return rays + + +def _pinhole_radius(tangent: np.ndarray, dist: np.ndarray) -> np.ndarray: + """The radial-tangential model's radial curve: how far from the principal point, in focal lengths, a ray + lands whose angle from the axis has this tangent. The tangential and thin-prism terms are left out.""" + # OpenCV takes this model's vector at several lengths, and the terms a shorter one leaves out are zero. + k1, k2, _, _, k3, k4, k5, k6 = np.concatenate([dist, np.zeros(8)])[:8] + square = tangent * tangent + numerator = 1.0 + square * (k1 + square * (k2 + square * k3)) + return tangent * numerator / (1.0 + square * (k4 + square * (k5 + square * k6))) + + +def _pinhole_rays(points: np.ndarray, intrinsics: Intrinsics) -> np.ndarray: + """The directions of pixels (N, 2) under the radial-tangential model; NaN past where its radial curve + stops rising. + + Do not use ``cv2.undistortPoints`` for this. It iterates a fixed point, which does not settle where the + curve rises more than twice as steeply as its chord, however many rounds it is given: under a lens whose + curve turns upward (radial coefficients of -0.3 and 0.1 at 120 degrees across) it left 40% of a 640x480 + picture's pixels without a direction that projects back onto them (OpenCV 4.12). The radial curve is + therefore inverted by halving, as the fisheye one is, and the terms it leaves out by Newton's method + from there, on the projection itself. + """ + K, dist = intrinsics.K, np.asarray(intrinsics.dist, dtype=np.float64) + # Skew is left out, as OpenCV's projection leaves it out. + plane = (points - [K[0, 2], K[1, 2]]) / [K[0, 0], K[1, 1]] + radius = np.hypot(plane[:, 0], plane[:, 1]) + low, high = np.zeros(len(radius)), np.full(len(radius), math.radians(field_limit_deg(intrinsics))) + for _ in range(_BISECTIONS): + middle = 0.5 * (low + high) + beyond = _pinhole_radius(np.tan(middle), dist) > radius + low, high = np.where(beyond, low, middle), np.where(beyond, middle, high) + tangent = np.tan(0.5 * (low + high)) + # A pixel further out than the curve ever rises to is left at the curve's end, short of its radius; one + # that is no number, or infinitely far, is on no curve. + short = np.abs(_pinhole_radius(tangent, dist) - radius) + reached = np.isfinite(radius) & (short <= _ON_CURVE * np.maximum(radius, 1.0)) + rays = np.full(plane.shape, np.nan) + # OpenCV refuses an empty list. + if not reached.any(): + return rays + # At the principal point the direction is the axis itself, whatever zero over zero would say. + scale = np.divide(tangent, radius, out=np.ones(len(radius)), where=radius > 0.0) + still, wanted, found = np.zeros(3), points[reached], plane[reached] * scale[reached, None] + for _ in range(_NEWTON_STEPS): + projected, jacobian = cv2.projectPoints( + np.column_stack([found, np.ones(len(found))]), still, still, K, dist + ) + error = wanted - projected.reshape(-1, 2) + slope = jacobian[:, _PINHOLE_ACROSS_COLUMNS].reshape(-1, 2, 2) + # Where the curve is level the slope cannot be inverted, and a ray thrown anywhere from there is + # caught by the caller: it does not project back onto its pixel. + with np.errstate(divide="ignore", invalid="ignore", over="ignore"): + determinant = slope[:, 0, 0] * slope[:, 1, 1] - slope[:, 0, 1] * slope[:, 1, 0] + step = np.column_stack( + [ + slope[:, 1, 1] * error[:, 0] - slope[:, 0, 1] * error[:, 1], + slope[:, 0, 0] * error[:, 1] - slope[:, 1, 0] * error[:, 0], + ] + ) + found = found + step / determinant[:, None] + rays[reached] = found + return rays + + +def normalised_rays(pixels: Any, intrinsics: Intrinsics) -> np.ndarray: + """The direction each pixel looks along, as (x / z, y / z) in the camera's frame, shape (N, 2); NaN for a + pixel the model has no sound direction for. + + That is a pixel past the model's reach: at or beyond 90 degrees, or further out than its radial curve + rises (``field_limit_deg``). Each model's curve is inverted on its rising part, and a direction is kept + only when projecting it again lands within ``_ROUND_TRIP_PX`` of the pixel it came from. + """ + points = np.asarray(pixels, dtype=np.float64).reshape(-1, 2) + # Nothing to invert, and OpenCV refuses an empty list. + if not len(points): + return np.zeros((0, 2)) + # A lens that reaches nowhere, as one whose coefficients are not numbers does, looks nowhere either. + if field_limit_deg(intrinsics) <= 0.0: + return np.full((len(points), 2), np.nan) + rays = _fisheye_rays(points, intrinsics) if intrinsics.model == FISHEYE else _pinhole_rays(points, intrinsics) + back = project(np.column_stack([rays, np.ones(len(rays))]), intrinsics) + # Written so that a NaN, from the inversion or from a ray the projection would not place, is lost too. + rays[~(np.linalg.norm(back - points, axis=1) <= _ROUND_TRIP_PX)] = np.nan + return rays + + +def field_angle_deg(pixels: Any, intrinsics: Intrinsics) -> np.ndarray: + """The angle from the optical axis each pixel looks along, in degrees, shape (N,); NaN where + ``normalised_rays`` has no direction.""" + rays = normalised_rays(pixels, intrinsics) + return np.degrees(np.arctan(np.hypot(rays[:, 0], rays[:, 1]))) + + +def picture_corner_angle_deg(intrinsics: Intrinsics) -> float | None: + """How far off the optical axis the picture's furthest corner looks under the model, in degrees; None + when the model does not reach every corner of its own picture.""" + width, height = intrinsics.image_size_wh + corners = [[0.0, 0.0], [width - 1.0, 0.0], [0.0, height - 1.0], [width - 1.0, height - 1.0]] + angles = field_angle_deg(corners, intrinsics) + return float(angles.max()) if np.all(np.isfinite(angles)) else None + + +def reprojection_rms(view: BoardView, T_camera_board: np.ndarray, intrinsics: Intrinsics) -> float: + """Root-mean-square distance in pixels between a view's corners and the board projected at a pose; NaN + when the model cannot place one of them there.""" + board = view.object_points.astype(np.float64) + projected = project(board @ T_camera_board[:3, :3].T + T_camera_board[:3, 3], intrinsics) + residual = view.image_points.astype(np.float64) - projected + return float(np.linalg.norm(residual) / np.sqrt(len(residual))) + + +def _refined_pose( + object_points: np.ndarray, image_points: np.ndarray, rvec: np.ndarray, tvec: np.ndarray, intrinsics: Intrinsics +) -> tuple[np.ndarray, np.ndarray]: + """A pose moved to where the corners fit best in pixels, from a pose that is near it. + + A pose found from directions weighs a corner by how far off the axis it is: at 75 degrees a pixel of + error counts 15 times what it does at the centre. Measured on synthetic fisheye views with 0.3 px of + corner noise, for views reaching 70 to 80 degrees: the pose's turn error at the 90th percentile fell + from 0.13 to 0.16 degrees to 0.09. + """ + + def residuals(pose: np.ndarray) -> np.ndarray: + """Each corner's pixel error at a pose, u then v.""" + return (posed_projection(object_points, pose[:3], pose[3:], intrinsics)[0] - image_points).ravel() + + def jacobian(pose: np.ndarray) -> np.ndarray: + """How those errors move with the pose.""" + return posed_projection(object_points, pose[:3], pose[3:], intrinsics)[1] + + start = np.concatenate([np.asarray(rvec).reshape(3), np.asarray(tvec).reshape(3)]) + # Levenberg-Marquardt only ever takes a step that lowers the error, so the start is the worst it returns. + solution = least_squares(residuals, start, jac=jacobian, method="lm") + return solution.x[:3], solution.x[3:] + + +def board_pose(view: BoardView, intrinsics: Intrinsics) -> tuple[np.ndarray, float] | None: + """The board's pose in the camera from one view (``T_camera_board``) and its reprojection RMS in pixels; + None when the view gives no pose. + + Under the fisheye model the pose is found from the corners' directions, since OpenCV poses a board + through the radial-tangential model only, and then refined in pixels. A corner without a sound direction + (``normalised_rays``) is left out, of the pose and of the RMS. + """ + # Corners along one line fit the board at any tilt about that line. + if not view.spans_plane: + return None + board = view.object_points.astype(np.float64) + corners = view.image_points.astype(np.float64) + if intrinsics.model == FISHEYE: + rays = normalised_rays(corners, intrinsics) + sound = np.all(np.isfinite(rays), axis=1) + view = BoardView(view.frame, view.ids[sound], view.image_points[sound], view.object_points[sound]) + # What is left once the rim's corners are gone has to fix a pose too. + if not view.spans_plane: + return None + board, corners = board[sound], corners[sound] + solved, rvec, tvec = cv2.solvePnP( + board.reshape(-1, 1, 3), rays[sound].reshape(-1, 1, 2), np.eye(3), None, flags=cv2.SOLVEPNP_ITERATIVE + ) + else: + solved, rvec, tvec = cv2.solvePnP( + board.reshape(-1, 1, 3), + corners.reshape(-1, 1, 2), + intrinsics.K, + intrinsics.dist, + flags=cv2.SOLVEPNP_ITERATIVE, + ) + # OpenCV reports a pose it could not find by its return value, not by raising. + if not solved: + return None + if intrinsics.model == FISHEYE: + rvec, tvec = _refined_pose(board, corners, rvec, tvec, intrinsics) + rotation, _ = cv2.Rodrigues(np.asarray(rvec, dtype=np.float64).reshape(3, 1)) + pose = homogeneous(rotation, np.asarray(tvec, dtype=np.float64).reshape(3)) + rms = reprojection_rms(view, pose, intrinsics) + # A pose under which the model cannot place the view's own corners was fitted to something else. + return (pose, rms) if math.isfinite(rms) else None diff --git a/examples/egocap/recording/egocap/calibration/camera_pipeline.py b/examples/egocap/recording/egocap/calibration/camera_pipeline.py new file mode 100644 index 0000000000..a6b7f37e43 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/camera_pipeline.py @@ -0,0 +1,869 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""One camera's calibration from one recorded take: pick frames, solve, grade. + +The take is read and never written. Anything kept for review goes to a separate directory the caller names. +Every failure an operator can cause is a ``CalibrationError`` whose message is meant for them. The one such +failure that is returned instead of raised is that of the extrinsics in a run that also solved intrinsics: +the intrinsics are still a result, and the message comes back beside them. +""" + +from __future__ import annotations + +import json +import logging +import os +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from .board import BoardDetector, BoardSpec, BoardView, CalibrationError, as_gray, draw_corners +from .extrinsics import ( + TRACK_FROZEN_M_PER_DEG, + HeadTrackReader, + ViewsDisagreeError, + board_position_spread_m, + head_motion_problem, + solve_with_head_direction_check, + solve_with_latency_search, +) +from .files import FISHEYE, PINHOLE, Intrinsics, intrinsics_from_record +from .grading import grade_calibration +from .intrinsics import MIN_CORNERS, PICTURE_CORNERS, corner_reach, solve_intrinsics, usable_for +from .take import CalibrationTake + +logger = logging.getLogger("isaaccapture.egocap.camera_pipeline") + +#: Frames picked from a take by default, under either lens model. Measured on synthetic fisheye takes within +#: the grade's limits on reach, coverage, tilt and focal uncertainty: from 30 views 0 of 233 solves were over +#: 5 px off at the picture's corners, from 40 views 1 of 250, so more picks buy nothing. +DEFAULT_PICKS = 30 +#: The fewest corners a picked frame shows when no lens model's solver asks for more. +DEFAULT_MIN_CORNERS = MIN_CORNERS[PINHOLE] +#: What a run solves: both parts, or one of them. +MODES = ("both", "intrinsic", "extrinsic") +#: How far either side of no lag a solve looks for the camera's lag when the caller leaves the lag to it. A +#: camera lags tracking by tens of milliseconds. The page's solve and the command line's both use it. +DEFAULT_LAG_SEARCH_S = 0.2 +#: A frame inside a tracking gap longer than this has no trustworthy head pose: the recorder writes no +#: tracking row while tracking is lost, and a pose interpolated across the hole is a guess. +MAX_TRACKING_GAP_S = 0.25 +#: Step between the moments at which a take's head track is read to see whether its positions are sound, in +#: seconds. The track is told by the paths of its poses as recorded; read between them this finely, the +#: figure comes out within about 2% of theirs (measured on tracks of 60 and 90 poses a second). +_TRACK_STEP_S = 0.002 + +#: Files written to the review directory; each picked frame is saved beside them as a JPEG. +PICKS_FILE = "picks.json" +INTRINSICS_FILE = "intrinsics.json" +EXTRINSICS_FILE = "extrinsics.json" +SUMMARY_FILE = "summary.json" + +#: Share of a run's progress given to scanning the video, by far its longest step. +_SCAN_SHARE = 0.85 +#: Where the extrinsics begin in a run's progress: halfway through what the scan leaves. +_EXTRINSICS_START = (1.0 + _SCAN_SHARE) / 2.0 + +#: Called with the fraction done (0 to 1) and a short message for the operator. +Progress = Callable[[float, str], None] + + +@dataclass(frozen=True) +class PickedViews: + """The frames picked from a take: the views to solve from, and a summary of the search for review.""" + + views: list[BoardView] + summary: dict[str, Any] + + +@dataclass(frozen=True) +class CameraCalibrationResult: + """What one calibration run produced.""" + + camera: str + mode: str + #: The intrinsics record, None when the run did not solve them. + intrinsics: dict[str, Any] | None + #: The head-camera extrinsics record, None when the run did not solve them. + extrinsics: dict[str, Any] | None + #: The grade, install decisions and advice, as ``grading.grade_calibration`` returns them. + grade: dict[str, Any] + #: The summary of the frame search. When the extrinsics' views were picked apart from the intrinsics', + #: the summary of their search is inside it as ``extrinsics_search``. + picks: dict[str, Any] + #: The lines an operator would want to read, in order. + log: list[str] + #: Why a run of both parts solved the intrinsics but not the extrinsics, for the operator; None otherwise. + extrinsics_problem: str | None = None + + def to_record(self) -> dict[str, Any]: + """The whole result as a JSON-serialisable dict.""" + return { + "camera": self.camera, + "mode": self.mode, + "intrinsics": self.intrinsics, + "extrinsics": self.extrinsics, + "grade": self.grade, + "picks": self.picks, + "log": list(self.log), + "extrinsics_problem": self.extrinsics_problem, + } + + +class _Search: + """Targets spread evenly along the frames that may be picked, and the best view found near each. + + A target's best view is the one showing most of the board, which near the rim of a wide lens is never + the one that reaches furthest out: a board taken into a corner of the picture hangs partly out of frame. + A fisheye solve is graded on how far out its corners were seen (``grading.INTRINSICS_REACH``), so for + one the search also keeps, per corner of the picture, the view that reaches furthest into it + (``intrinsics.corner_reach``). Measured on 240 synthetic fisheye takes of one to two minutes that carry + the board whole over the middle of the picture and dip it into each corner for 1 to 2.4 s: solved from + the targets' views alone none was excellent and 173 were refused for their reach; with the four views + that reach furthest every solve was excellent, graded on a reach within 0.01 of the take's own, and none + was over 5 px off at the picture's corners. + """ + + def __init__( + self, + total: int, + n_picks: int, + scan_step: int, + usable: np.ndarray | None, + wider: _Search | None = None, + picture_wh: tuple[int, int] | None = None, + ) -> None: + """Lay out the targets over the ``usable`` frames of ``total`` (all of them, when None). + + ``wider`` is a search over frames that include this one's and that shares its scan: this search then + looks at the frames that one steps through, not at every ``scan_step``-th of its own. ``picture_wh`` + is the picture's size when the views reaching furthest into its corners are to be kept as well. + """ + # Fewer would leave no target to pick for, or a scan that never moves on. + if n_picks < 1 or scan_step < 1: + raise ValueError("n_picks and scan_step must be at least 1") + self.total = total + self.scan_step = scan_step + # Places along the usable frames, not frame numbers, are what is spread over: a stretch without + # head tracking then costs no picks. + self.frames = np.flatnonzero( + np.ones(total, dtype=bool) if usable is None else np.asarray(usable, dtype=bool) + ) + self.stride = max(len(self.frames) // n_picks, 1) + self.radius = max(self.stride // 2, 1) + self.targets = list(range(0, len(self.frames), self.stride)) + # The step is what bounds a scan, the slow part of a run. Two searches each stepping through its own + # frames fall on different ones, and their scan would read nearly twice what the step allows. + stepped = (self if wider is None else wider).frames[::scan_step] + #: The frames this search looks at, each with its place along the usable frames. + self.places = { + int(self.frames[place]): place + for place in np.flatnonzero(np.isin(self.frames, stepped)).tolist() + if self._slot(place) is not None + } + # Per target: how good its best frame so far is, that frame's view, and whether the legacy layout + # found it. + self._best: dict[int, tuple[tuple[int, int], BoardView, bool]] = {} + self._picture_wh = picture_wh + # Per corner of the picture, in the order of ``PICTURE_CORNERS``: how far into it the furthest view + # so far reaches, and that view. + self._furthest: dict[int, tuple[float, BoardView]] = {} + + def _slot(self, place: int) -> int | None: + """The target a place competes for; None for one past the last target's reach.""" + slot = min((place + (self.stride - 1) // 2) // self.stride, len(self.targets) - 1) + return slot if abs(place - self.targets[slot]) <= self.radius else None + + def offer(self, view: BoardView, legacy: bool) -> None: + """Let a frame's view compete for its target, when this search looks at that frame at all.""" + place = self.places.get(view.frame) + # A scan shared with another search also passes frames only that one may pick. + if place is None: + return + slot = self._slot(place) + # More corners first, then nearer the target. + rank = (view.corners, -abs(place - self.targets[slot])) + # Strictly better only, so of two equal frames the one seen first, the earlier, is kept. + if slot not in self._best or rank > self._best[slot][0]: + self._best[slot] = (rank, view, legacy) + if self._picture_wh is not None: + for corner, reach in enumerate(corner_reach([view], self._picture_wh).tolist()): + # Strictly further only, as above; a view with no corner in a quarter reaches nowhere in it. + if reach > self._furthest.get(corner, (0.0, view))[0]: + self._furthest[corner] = (reach, view) + + def reaching(self) -> list[BoardView]: + """The views kept for reaching furthest into a corner of the picture, in frame order, less those a + target picked anyway.""" + taken = {view.frame for _, view, _ in self._best.values()} + further = {view.frame: view for _, view in self._furthest.values() if view.frame not in taken} + return [further[frame] for frame in sorted(further)] + + def picked(self, camera: str, min_corners: int) -> PickedViews: + """The views found for the targets, in frame order, with the summary of the search.""" + picks = [] + for slot, target in enumerate(self.targets): + view = self._best[slot][1] if slot in self._best else None + picks.append( + { + "target": int(self.frames[target]), + "found": view is not None, + "frame": None if view is None else view.frame, + "corners": 0 if view is None else view.corners, + "image": None, + } + ) + # One entry per corner of the picture a view reached into, whether or not a target picked that view. + reach_picks = [ + { + "corner": PICTURE_CORNERS[corner], + "frame": view.frame, + "corners": view.corners, + "reach": reach, + "image": None, + } + for corner, (reach, view) in sorted(self._furthest.items()) + ] + summary = { + "camera": camera, + "frames": self.total, + "usable_frames": len(self.frames), + "stride": self.stride, + "radius": self.radius, + "scan_step": self.scan_step, + "min_corners": min_corners, + "frames_scanned": len(self.places), + "targets": len(self.targets), + "found": len(self._best), + "legacy_layout": any(legacy for _, _, legacy in self._best.values()), + "picks": picks, + "reach_picks": reach_picks, + } + return PickedViews([self._best[slot][1] for slot in sorted(self._best)], summary) + + +def _scan( + take: CalibrationTake, + camera: str, + detector: BoardDetector, + searches: Sequence[_Search], + min_corners: int, + progress: Progress | None, + model: str | None = None, +) -> None: + """Decode the video once, front to back, and offer every usable view of the board to each search. + + ``model`` is the lens model the views are solved under, when intrinsics are solved from them: a view + its solver would leave out is then worth no pick. + """ + # Decoding and detection are by far the slowest step, so a frame several searches look at is read once. + frames = sorted(set().union(*(search.places for search in searches))) + percent = -1 + for done, (frame, image) in enumerate(take.frames(camera, frames), start=1): + detection = detector.detect(as_gray(image)) + # Reported per whole percent, so a long video does not flood the caller. + if progress is not None and 100 * done // len(frames) != percent: + percent = 100 * done // len(frames) + progress(done / len(frames), f"Looking for the board: frame {done} of {len(frames)}") + # Too little of the board to be worth a pick. + if detection is None or len(detection.ids) < min_corners: + continue + view = detector.view(frame, detection) + # Corners along one line fix no pose, however many there are; a solver may ask for more than a pose. + if not (view.spans_plane if model is None else usable_for(view, model)): + continue + for search in searches: + search.offer(view, detection.legacy) + + +def pick_views( + take: CalibrationTake, + camera: str, + detector: BoardDetector, + *, + n_picks: int = DEFAULT_PICKS, + min_corners: int = DEFAULT_MIN_CORNERS, + scan_step: int = 1, + usable: np.ndarray | None = None, + progress: Progress | None = None, +) -> PickedViews: + """Pick up to about ``n_picks`` frames spread over a camera's video, each the best view near its place. + + The usable frames are taken in order and targets spaced evenly along them (``stride = max(count // + n_picks, 1)``). Each target takes the frame within ``max(stride // 2, 1)`` places of it that shows the + most corners, the nearest to the target on a tie. A frame counts only with at least ``min_corners`` + corners that are not all on one line. Every frame belongs to its nearest target (the earlier one when + halfway), so the video is decoded once, front to back, and no frame is picked twice. + + ``usable`` masks the frames that may be picked (all, when None); ``scan_step`` looks at every n-th usable + frame only, trading thoroughness for time. + """ + search = _Search(take.frame_count(camera), n_picks, scan_step, usable) + _scan(take, camera, detector, [search], min_corners, progress) + return search.picked(camera, min_corners) + + +def _review_dir(episode_dir: Path | str, work_dir: Path | str | None) -> Path | None: + """Where review files go, resolved; refused when writing there would touch the recorded session the take + belongs to, or would mix with what the folder already holds.""" + # Without a review folder the run writes nothing at all. + if work_dir is None: + return None + # Resolved first, so a link into the recording is caught as the recording. + episode, work = Path(episode_dir).resolve(), Path(work_dir).resolve() + if work == episode or episode in work.parents or work in episode.parents: + raise CalibrationError("The review folder cannot be the take itself, inside it or around it.") + # The session holds the take and every take recorded beside it; whatever is around the take is around + # the session too, so what is left to refuse here is a folder elsewhere inside the session. + if episode.parent in work.parents: + raise CalibrationError( + "The review folder cannot be inside the recorded session the take belongs to. Name a folder " + "outside the session." + ) + # A run leaves no file for a part it did not solve, so in a used folder an earlier run's files would + # pass for this one's. + if os.path.lexists(work) and (not work.is_dir() or any(work.iterdir())): + raise CalibrationError( + f"The review folder {work.name} already holds files. Name a new or an empty folder: review " + "files are never replaced." + ) + return work + + +def _write_json(directory: Path, name: str, record: dict[str, Any]) -> None: + """Write one record into the review directory.""" + directory.mkdir(parents=True, exist_ok=True) + (directory / name).write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + + +def _write_picks( + directory: Path, + take: CalibrationTake, + camera: str, + picked: PickedViews, + position: PickedViews, + reaching: Sequence[BoardView], +) -> None: + """Save each picked frame with its corners drawn, and the search summary naming those images. + + ``position`` is the set picked for the extrinsics, which is ``picked`` itself unless the two were + picked apart; its frames are saved beside the others and named in its own summary. ``reaching`` are the + views kept beside the targets' for how far into the picture's corners they reach. + """ + directory.mkdir(parents=True, exist_ok=True) + views = {view.frame: view for view in (*picked.views, *position.views, *reaching)} + names = {} + # The scan kept no images, so the picked frames are decoded again; they are few. + for frame, image in take.frames(camera, sorted(views)): + names[frame] = f"pick_{frame:05d}.jpg" + draw_corners(image, views[frame].image_points, views[frame].ids) + # Encoded in memory and written as bytes, so a write that fails raises rather than returning False. + _, encoded = cv2.imencode(".jpg", image) + (directory / names[frame]).write_bytes(encoded.tobytes()) + # A target that found no frame keeps no image name. + for pick in (*picked.summary["picks"], *position.summary["picks"], *picked.summary["reach_picks"]): + pick["image"] = names.get(pick["frame"]) + _write_json(directory, PICKS_FILE, picked.summary) + + +def _installed_camera(installed: Intrinsics | None, size: tuple[int, int]) -> Intrinsics: + """The installed camera an extrinsics-only run solves against, under whichever lens model it holds.""" + # Board poses come from the camera matrix; without one there is nothing to solve the extrinsics against. + if installed is None: + raise CalibrationError( + "Solving only the extrinsics needs the camera's installed intrinsics, and there are none. " + "Calibrate the intrinsics first." + ) + # A matrix solved at another image size describes other pixels. + if tuple(installed.image_size_wh) != size: + raise CalibrationError( + f"The installed intrinsics are for a {installed.image_size_wh[0]}x{installed.image_size_wh[1]} image " + f"but this take is {size[0]}x{size[1]}. Calibrate the intrinsics again at this size." + ) + return installed + + +def _board_not_found(camera: str, spec: BoardSpec, tracked_only: bool) -> str: + """The operator's message for a search that found the board nowhere; ``tracked_only`` when only the + frames that have a head pose were searched, and they are not the whole take.""" + board = f"the {spec.squares[0]}x{spec.squares[1]} {spec.dictionary} board" + if tracked_only: + return ( + f"The board was not found in any frame of {camera} that has head tracking. Check it is {board}, " + "and that it is in view while the headset and both controllers are tracked." + ) + return ( + f"The board was not found in any frame of {camera}. Check it is {board}, and that it is in view, sharp " + "and well lit." + ) + + +@dataclass(frozen=True) +class _HeadTrack: + """What a take's head tracking lets the camera's position be solved from. + + A headset that loses its position goes on reporting poses (``extrinsics.HeadTrackReader``), so the + frames that have a head pose are not yet the frames whose head pose is right. What was recorded while + the position was lost is left out, and where the position leapt into another frame the position is + solved from the longest stretch of sound tracking alone. + """ + + #: Which frames of the camera have a head pose at all, and which have one from the stretch kept. + tracked: np.ndarray + usable: np.ndarray + #: The moments the track was read at, and which of them lie in the stretch kept. + moments: np.ndarray + sound: np.ndarray + #: How many times the position could not be used, how far into the take it first could not (seconds; + #: None when it always could), for how many seconds in all, and how many stretches the take is split into. + lost: int + first_lost_s: float | None + lost_s: float + stretches: int + #: How many seconds the take's tracking and the stretch kept come to. + tracked_s: float + sound_s: float + #: How far the head's position moved for each degree it turned, in mm, over the take's windows of + #: turning: the lowest figure and the median one. None when the head turned too little in every window. + lowest_mm_per_degree: float | None + median_mm_per_degree: float | None + + def sound_at(self, times: np.ndarray) -> np.ndarray: + """Whether each time lies in the stretch of sound tracking kept.""" + nearest = np.rint((np.asarray(times, dtype=np.float64) - self.moments[0]) / _TRACK_STEP_S).astype(int) + inside = (nearest >= 0) & (nearest < len(self.moments)) + return inside & self.sound[np.clip(nearest, 0, len(self.moments) - 1)] + + def record(self) -> dict[str, Any]: + """What the extrinsics record says of the take's head tracking.""" + return { + "lost": self.lost, + "first_lost_s": self.first_lost_s, + "tracked_s": self.tracked_s, + "sound_s": self.sound_s, + "lost_s": self.lost_s, + "stretches": self.stretches, + "lowest_mm_per_degree": self.lowest_mm_per_degree, + "median_mm_per_degree": self.median_mm_per_degree, + } + + def lines(self) -> list[str]: + """The log lines on the take's head tracking: how its position followed its turning, which is what + a lost position is told by, and what became of a take that lost it.""" + limit = 1000.0 * TRACK_FROZEN_M_PER_DEG + if self.lowest_mm_per_degree is None: + lines = ["No two seconds of the take hold enough turning to say how the head's position followed it."] + else: + lines = [ + f"While the head turned, its position moved {self.lowest_mm_per_degree:.1f} mm for each degree " + f"at the least and {self.median_mm_per_degree:.1f} mm at the median: under {limit:g} mm the " + "position counts as lost." + ] + if self.lost: + lines.append(f"{self._lost_words()} and {int(self.usable.sum())} of the frames.") + return lines + + def _lost_words(self) -> str: + """What became of a take whose headset lost its position, up to how much of it is solved from.""" + lost = f"Head tracking lost its position during the take, first {self.first_lost_s:.0f} s in" + # A position that leapt left stretches nothing ties together; one that did not cost only its own time. + if self.stretches > 1: + return ( + f"{lost}, and found it again somewhere else: the camera's position is solved from the longest " + f"stretch of sound tracking, {self.sound_s:.0f} s" + ) + return ( + f"{lost}, for {self.lost_s:.0f} s in all: what was recorded meanwhile is left out, and the camera's " + f"position is solved from the other {self.sound_s:.0f} s" + ) + + def refusal(self, error: CalibrationError) -> CalibrationError: + """What to tell the operator of a position that could not be solved: the failure itself, unless the + headset lost its position. Then that comes first, with what keeps a headset from losing it, and views + that disagree are not put down to a board that moved.""" + if not self.lost: + return error + lost = f"Head tracking lost its position during the take, first {self.first_lost_s:.0f} s in" + left = f"the {self.sound_s:.0f} s of sound tracking that are left" + stand = ( + "about a meter from the board, with part of the room in the headset's view: close up, with the " + "board filling its view, the headset loses its position. Stop the take when it does." + ) + if isinstance(error, ViewsDisagreeError): + return CalibrationError( + f"{lost}, and the views from {left} do not agree on where the board stands, so the camera's " + f"position was not solved. Record again standing {stand}" + ) + # The solve's own sentence stays: what it asks for is still wanted of the next take. + return CalibrationError( + f"{lost}, and the camera's position could not be solved from {left}: {error} Stand {stand}" + ) + + +def _head_track(take: CalibrationTake, camera: str, latency_s: float, search_s: float | None) -> _HeadTrack: + """A take's head tracking as the camera's position can be solved from it; refused when the head was not + tracked or did not move. + + ``latency_s`` is the camera lag the frames are placed at, and ``search_s`` how far either side of it a + lag search will look, so that the track is read wherever a frame may be placed. + """ + times = take.camera_times(camera, latency_s) + poses, tracked = take.head_poses_at(times, max_gap_s=MAX_TRACKING_GAP_S) + # The recorder leaves out a tracking row whenever the headset or a controller is not tracked, which is + # why the message names the controllers too. + if not tracked.any(): + raise CalibrationError( + "The take has no head tracking at the camera's frames. Check the headset and the controllers were " + "on and tracked, and record again." + ) + reach = _TRACK_STEP_S + (0.0 if search_s is None else search_s) + moments = np.arange(times.min() - reach, times.max() + reach, _TRACK_STEP_S) + read, known = take.head_poses_at(moments, max_gap_s=MAX_TRACKING_GAP_S) + reader = HeadTrackReader() + reader.add(moments[known], read[known]) + # A moment without a head pose belongs to no stretch, like one whose position was lost. + stretch = np.full(len(moments), -1) + stretch[known] = reader.stretches(moments[known]) + nearest = np.rint((times - moments[0]) / _TRACK_STEP_S).astype(int) + at_frames = np.where(tracked, stretch[nearest], -1) + # The stretch most frames lie in is the one kept; with no sound frame at all there is none. + counts = np.bincount(at_frames[at_frames >= 0]) + sound = stretch == int(np.argmax(counts)) if counts.size else np.zeros(len(moments), dtype=bool) + spans = reader.unusable_spans + readings = 1000.0 * reader.readings + track = _HeadTrack( + tracked=tracked, + usable=tracked & sound[nearest], + moments=moments, + sound=sound, + lost=len(spans), + # The track is read from a step before the first frame, which is still the take's start. + first_lost_s=max(0.0, float(spans[0][0] - times.min())) if spans else None, + lost_s=float(sum(end - start for start, end in spans)), + stretches=reader.stretch_count, + tracked_s=float(known.sum() * _TRACK_STEP_S), + sound_s=float(sound.sum() * _TRACK_STEP_S), + lowest_mm_per_degree=float(readings.min()) if readings.size else None, + median_mm_per_degree=float(np.median(readings)) if readings.size else None, + ) + # A cheap early refusal, before the slow scan: a head that never moved while its tracking was sound cannot + # have moved over the views of the board. One that did move may still have held still while the board was + # in view, which the solve judges over the views it uses. + problem = head_motion_problem(poses[track.usable]) + if problem is not None: + raise track.refusal(CalibrationError(problem)) + return track + + +def _say(log: list[str], line: str) -> None: + """Add a line to the run's log, and to the process log as it happens.""" + log.append(line) + logger.info("%s", line) + + +def _latency_line(search: dict[str, Any]) -> str: + """The log line saying what a search for the camera's lag found.""" + if not search["adopted"]: + return ( + f"Camera lag: no clearly better lag found within {1000.0 * search['half_range_s']:.0f} ms either way." + ) + lag_ms = 1000.0 * search["best_s"] + when = f"{abs(lag_ms):.0f} ms {'before' if lag_ms >= 0 else 'after'} their recorded times" + stillness = f"{1000.0 * search['spread_at_best_m']:.1f} mm" + # A lag found where the search stopped looking is the best of what was tried, not known to be the lag. + # The lag taken can lie a step or two inside the range with its end no worse, so no more is claimed. + searched = f"{1000.0 * search['half_range_s']:.0f} ms" + beyond = ( + f" That is at or next to the end of the {searched} searched: the true lag may lie beyond it." + if search["at_range_end"] + else "" + ) + # At the given lag there is either a spread to set this against, or nothing that could be solved. + if search["spread_at_given_m"] is None: + return ( + f"Camera lag: frames taken {when} give the stillest board ({stillness}; unsolvable as recorded)." + f"{beyond}" + ) + given = f"{1000.0 * search['spread_at_given_m']:.1f} mm" + return f"Camera lag: frames taken {when} give the stillest board ({stillness} against {given}).{beyond}" + + +def _result_lines( + intrinsics: dict[str, Any] | None, extrinsics: dict[str, Any] | None, grade: dict, problem: str | None +) -> list[str]: + """The lines of the log that describe what was solved, what was not (``problem``), and how it graded.""" + lines = [] + if intrinsics is not None: + lines.append( + f"Intrinsics: RMS {intrinsics['rms_calibrate_camera']:.3f} px from {intrinsics['num_views_used']} " + f"views ({intrinsics['num_views_outlier_removed']} dropped as outliers, " + f"{intrinsics['num_views_skipped']} unusable), graded {grade['intrinsics']['grade']}." + ) + lines.append(grade["intrinsics"]["field_of_view"]) + if extrinsics is not None: + # Before the solve it explains: the lag decides which head pose each frame was solved against. + if extrinsics["camera_latency_search"] is not None: + lines.append(_latency_line(extrinsics["camera_latency_search"])) + forward, left, up = (1000.0 * extrinsics["T_headset_camera"][axis][3] for axis in range(3)) + lines.append( + f"Extrinsics: best solver {extrinsics['best_method']} over {extrinsics['n_views']} views, board " + f"position spread {1000.0 * board_position_spread_m(extrinsics):.1f} mm, pose fit " + f"{extrinsics['mean_pnp_reproj_rms_px']:.2f} px, head poses " + f"{'inverted' if extrinsics['invert_head'] else 'as recorded'}, graded {grade['extrinsics']['grade']}." + ) + lines.append(f"Camera on the headset: {forward:+.1f} mm forward, {left:+.1f} mm left, {up:+.1f} mm up.") + # Said where the extrinsics would have stood, so the overall grade below is read as the intrinsics' alone. + if problem is not None: + lines.append(f"Extrinsics were not solved: {problem}") + lines.append(f"Overall: {grade['overall']}.") + return lines + grade["feedback"] + + +def _under_tracking_latency(record: dict[str, Any], take: CalibrationTake) -> dict[str, Any]: + """An extrinsics record with the latency the recorder took off the take's tracking times, when the take + states it. + + The camera's lag is measured against those times, so it holds for takes recorded under the same latency + and no other: a reader moves the lag by what the latency has changed by since. A take that does not say + leaves the key out, and its lag is then used as it stands. + """ + latency_s = take.tracking_latency_s() + return record if latency_s is None else record | {"tracking_latency_s": latency_s} + + +def _solve_extrinsics( + take: CalibrationTake, + camera: str, + views: list[BoardView], + intrinsics: Intrinsics, + spec: BoardSpec, + latency_s: float, + search_s: float | None, + report: Progress, + track: _HeadTrack, +) -> dict[str, Any]: + """The extrinsics record from the picked views and the take's head poses at their frames. + + The head poses are looked up with the camera's frames taken to be ``latency_s`` older than recorded, or, + with ``search_s``, at whichever lag within that much of it leaves the board stillest. Either way the + record says which lag it used (``camera_latency_s``), what a search found (``camera_latency_search``), + what became of the take's head tracking (``head_tracking``: ``_HeadTrack.record``) and, when the take + states it, the latency its tracking times were recorded under (``tracking_latency_s``). + """ + recorded = take.camera_times(camera)[[view.frame for view in views]] + + def head_poses_at_lag(lag_s: float) -> tuple[np.ndarray, np.ndarray]: + """The head pose at each picked frame under a camera lag, and which frames have one that can be + used: under another lag a frame beside a loss of tracking falls inside it.""" + poses, known = take.head_poses_at(recorded - lag_s, max_gap_s=MAX_TRACKING_GAP_S) + return poses, known & track.sound_at(recorded - lag_s) + + report(_EXTRINSICS_START, "Solving the extrinsics") + if search_s is None: + # Every picked frame was chosen for having a head pose that can be used at this lag. + poses, _ = head_poses_at_lag(latency_s) + record = solve_with_head_direction_check(views, poses, intrinsics, spec) + return _under_tracking_latency( + record + | { + "camera_latency_s": float(latency_s), + "camera_latency_search": None, + "head_tracking": track.record(), + }, + take, + ) + record = solve_with_latency_search( + views, + head_poses_at_lag, + intrinsics, + spec, + given_s=latency_s, + half_range_s=search_s, + progress=lambda fraction, message: report( + _EXTRINSICS_START + (1.0 - _EXTRINSICS_START) * fraction, message + ), + ) + return _under_tracking_latency(record | {"head_tracking": track.record()}, take) + + +def run_camera_calibration( + episode_dir: Path | str, + camera: str, + *, + mode: str, + spec: BoardSpec = BoardSpec(), + model: str = PINHOLE, + n_picks: int = DEFAULT_PICKS, + min_corners: int | None = None, + scan_step: int = 1, + camera_latency_s: float = 0.0, + installed_intrinsics: Intrinsics | None = None, + progress: Progress | None = None, + work_dir: Path | str | None = None, + latency_search_s: float | None = None, +) -> CameraCalibrationResult: + """Calibrate one camera from one recorded take. + + ``mode`` is ``"both"`` (intrinsics, then extrinsics solved with them), ``"intrinsic"`` or ``"extrinsic"`` + (against ``installed_intrinsics``, which must be for the video's image size). ``model`` is the lens + model the intrinsics are solved under, ``files.PINHOLE`` or ``files.FISHEYE``; a run that solves none + uses the installed intrinsics' own. ``min_corners`` is by default what that model's solver asks of a + view (``intrinsics.MIN_CORNERS``), and ``DEFAULT_MIN_CORNERS`` when no intrinsics are solved. + + The extrinsics are the camera's pose on the headset, so they need the take's head tracking and a head + that moved. When ``"both"`` solves the intrinsics but cannot solve the extrinsics, the result carries the + intrinsics, no extrinsics, and the reason as ``extrinsics_problem``; every other failure is raised. + + The extrinsics are solved from frames that have a head pose. The intrinsics need none, so in a run of + both parts whose tracking covers only part of the take they are solved from views picked over every + frame, and the extrinsics from views picked over the tracked frames, both found in one scan of every + ``scan_step``-th frame of the take. Under the fisheye model the intrinsics are solved, beside the + picked views, from the scanned frame that shows the board furthest into each corner of the picture + (the summary's ``reach_picks``); the extrinsics are not. + + ``camera_latency_s`` is subtracted from the camera's frame times before head poses are looked up. With + ``latency_search_s`` the extrinsics are also solved at lags up to that far either side of it, and the lag + that leaves the board clearly stillest is used instead (see ``extrinsics.solve_with_latency_search``). + ``work_dir``, when given, receives the search summary, the solved records and each picked frame with its + corners drawn. It must lie outside the recorded session the take belongs to (not the session, inside it + or around it) and be new or empty. Nothing else is written anywhere. + """ + # These are chosen by the caller's code, not typed by an operator, so a wrong one is a plain error. + if mode not in MODES: + raise ValueError(f"mode must be one of {', '.join(MODES)}") + if model not in MIN_CORNERS: + raise ValueError(f"model must be {PINHOLE} or {FISHEYE}") + if latency_search_s is not None and not latency_search_s > 0: + raise ValueError("latency_search_s must be more than 0") + report = progress if progress is not None else (lambda fraction, message: None) + # Opened first: what is no recorded take has no session to keep the review folder out of. + take = CalibrationTake(episode_dir) + review = _review_dir(episode_dir, work_dir) + size = take.image_size(camera) + log: list[str] = [] + _say(log, f"{camera}: {take.frame_count(camera)} frames of {size[0]}x{size[1]}.") + + # What a view must show is its solver's to say; with no intrinsics to solve, a board pose is all a view + # is for. + if min_corners is None: + min_corners = DEFAULT_MIN_CORNERS if mode == "extrinsic" else MIN_CORNERS[model] + + # Everything that can refuse the take cheaply comes before the scan, which is the slow part. + lens = _installed_camera(installed_intrinsics, size) if mode == "extrinsic" else None + track, tracked, head_problem = None, None, None + if mode != "intrinsic": + try: + track = _head_track(take, camera, camera_latency_s, latency_search_s) + # The frames the position may be solved from: those with a head pose from sound tracking. + tracked = track.usable + _say(log, f"Head tracking covers {int(track.tracked.sum())} of the frames.") + for line in track.lines(): + _say(log, line) + except CalibrationError as error: + # Only the extrinsics need the head. A run of both parts still solves the intrinsics, from every + # frame, and reports this beside them. + if mode == "extrinsic": + raise + head_problem = str(error) + + # Only the extrinsics are held to frames with a head pose. A run of both parts whose tracking covers part + # of the take therefore picks two sets of views, so that neither solve pays for what the other needs. + apart = mode == "both" and tracked is not None and not tracked.all() + total = take.frame_count(camera) + # Views are held to what the intrinsics' solver can use only when intrinsics are solved from them, and + # the ones reaching furthest out are kept only for the solve that is graded on its reach. + solved_under = None if mode == "extrinsic" else model + search = _Search( + total, + n_picks, + scan_step, + tracked if mode == "extrinsic" else None, + picture_wh=size if solved_under == FISHEYE else None, + ) + tracked_search = _Search(total, n_picks, scan_step, tracked, wider=search) if apart else search + _scan( + take, + camera, + BoardDetector(spec), + [search, tracked_search] if apart else [search], + min_corners, + lambda fraction, message: report(_SCAN_SHARE * fraction, message), + solved_under, + ) + picked = search.picked(camera, min_corners) + reaching = search.reaching() + position = picked + layout = " (printed in the legacy layout)" if picked.summary["legacy_layout"] else "" + _say(log, f"Board found near {picked.summary['found']} of {picked.summary['targets']} targets{layout}.") + if reaching: + frames = "frame" if len(reaching) == 1 else "frames" + _say(log, f"Kept {len(reaching)} more {frames} for showing the board furthest into the picture's corners.") + if apart: + position = tracked_search.picked(camera, min_corners) + picked.summary["extrinsics_search"] = position.summary + _say( + log, + f"For the extrinsics, board found near {position.summary['found']} of " + f"{position.summary['targets']} targets among the frames with head tracking.", + ) + # Written before solving, so a take that then fails to solve can still be looked at. + if review is not None: + _write_picks(review, take, camera, picked, position, reaching) + if not picked.views: + raise CalibrationError(_board_not_found(camera, spec, mode == "extrinsic" and not tracked.all())) + + intrinsics, extrinsics, solve_problem = None, None, None + if mode != "extrinsic": + report(_SCAN_SHARE, "Solving the intrinsics") + # The position below is solved from the targets' views alone: a board hanging out of frame is posed + # less surely, and adds nothing there. + lens_views = sorted([*picked.views, *reaching], key=lambda view: view.frame) + intrinsics = solve_intrinsics(lens_views, size, spec, model=model) + lens = intrinsics_from_record(intrinsics, INTRINSICS_FILE) + if tracked is not None: + try: + # Only views picked apart can be none at this point. Raised here, to be handled as any other + # failure of the extrinsics is. + if not position.views: + raise CalibrationError( + "The board was not seen in any frame that has head tracking. Keep the headset and both " + "controllers tracked while the board is in view, and record again." + ) + extrinsics = _solve_extrinsics( + take, camera, position.views, lens, spec, camera_latency_s, latency_search_s, report, track + ) + except CalibrationError as error: + # A position that fails after the headset lost its own is told as that. + told = track.refusal(error) + # Intrinsics already solved are still a result; with none, the failure is all there is to report. + if intrinsics is None: + raise told from None + solve_problem = str(told) + # At most one of the two is set: without head poses the extrinsics are never attempted. + problem = head_problem or solve_problem + # One stamp for both records, so the files of one run can be seen to belong together. + stamp = {"calibrated_at": datetime.now().astimezone().isoformat(timespec="seconds"), "camera": camera} + for record in filter(None, (intrinsics, extrinsics)): + record.update(stamp) + grade = grade_calibration(intrinsics, extrinsics) + for line in _result_lines(intrinsics, extrinsics, grade, problem): + _say(log, line) + if review is not None: + summary = {"camera": camera, "mode": mode, "grade": grade, "log": log, "extrinsics_problem": problem} + # A part the run did not solve leaves no file, rather than an empty one. + for name, record in ( + (INTRINSICS_FILE, intrinsics), + (EXTRINSICS_FILE, extrinsics), + (SUMMARY_FILE, summary), + ): + if record is not None: + _write_json(review, name, record) + report(1.0, "Done") + return CameraCalibrationResult(camera, mode, intrinsics, extrinsics, grade, picked.summary, log, problem) diff --git a/examples/egocap/recording/egocap/calibration/extrinsics.py b/examples/egocap/recording/egocap/calibration/extrinsics.py new file mode 100644 index 0000000000..622d78c50c --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/extrinsics.py @@ -0,0 +1,890 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Where the head camera sits on the headset, by hand-eye calibration against the recorded head pose. + +A board stands still while the operator looks at it from many places. Each view gives the board's pose in the +camera (from its corners) and the headset's pose in the world (from tracking). The camera-on-headset +transform sought is the one that puts the board at the same place in the world in every view, and how far +the board still wanders under it is the measure of the fit. + +A still board is not yet a right answer: seen from a head that hardly turned, or turned about one axis only, +it stands still under many camera poses. Such views are refused, and the record says how well the views +kept pin the camera's position. + +Nor is a head pose that arrives a head pose that is right. A headset that loses sight of the room goes on +reporting where it looks, with a position that no longer follows the head, and finds its place again with a +leap, often into another frame than it left. ``HeadTrackReader`` reads that from the track itself, so that +a caller can keep to the head poses of one stretch of sound tracking. + +``T_a_b`` maps a point in frame ``b`` to frame ``a``. The headset frame here is forward-left-up. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Sequence +from typing import Any + +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation + +from .board import BoardSpec, BoardView, CalibrationError +from .camera_model import board_pose +from .files import OPENXR_POSES, POSE_SOURCE_KEY, Intrinsics +from .frames import R_OPENXR_FROM_FLU, homogeneous, invert_pose + +#: Fewest views a hand-eye solve takes: two motions between them. +MIN_VIEWS = 3 +#: A view is kept when the board it implies stands within this many times the views' median distance from +#: their median board position. Measured on 150 synthetic takes of 30 views with tracking right to a +#: millimeter, two of the views' head positions 4 cm off: a fixed limit of 5 cm kept those views, 127 takes +#: graded bad and 7 of the 23 that could be installed were over 10 mm off; three medians dropped them, and +#: all 150 graded excellent with none over 10 mm off. Of 150 sound takes 6 lost a view, none more than two. +_BOARD_SHIFT_MEDIANS = 3.0 +#: ...a limit never under this, the wander the grade calls excellent, so that views which agree that well are +#: not told apart, and never over this, whatever the views' scatter... +MIN_BOARD_SHIFT_M = 0.005 +MAX_BOARD_SHIFT_M = 0.05 +#: ...and within this angle of the mean board orientation. +MAX_BOARD_TURN_DEG = 10.0 +#: The head counts as having moved when its position varies at least this much along some axis... +MIN_HEAD_POSITION_STD_M = 0.03 +#: ...or some rotation differs from the first by at least this Frobenius distance (about 20 degrees). +MIN_HEAD_ROTATION_FROBENIUS = 0.5 +#: Least the head must turn over the views of the board, as a root-mean-square angle about the axis it turned +#: most about. Measured on 30 views at 1 mm / 0.1 degree of tracking noise: under 2 degrees about every axis +#: the solved position was 11 to 33 mm off (median of 40 takes each) with the board wandering under 3 mm. +MIN_HEAD_TURN_DEG = 2.0 +#: ...and about the next axis. Measured the same way: a head turned 11 degrees one way and under 1 degree +#: about a second axis left the position 16 to 49 mm off, almost all of it along the axis it turned about. +MIN_HEAD_SECOND_TURN_DEG = 1.0 +#: Share of the views, those that turned furthest off the main axis, left out of the turning information. +#: Measured: 4 views of a head turning about two axes among 24 of a still head left 27% of 200 takes over +#: 10 mm off; counting every view put 161 of them under the 10 mm limit, leaving out a tenth put 1. +_TURN_TRIM = 0.1 +#: Turning information, in squared radians, below which the views say nothing about some direction. +_NO_TURN_INFORMATION = 1e-12 + +#: How many times stiller the board must stand with the head poses inverted for that reading to be kept. +_INVERSION_MARGIN = 2.0 + +# A headset reports a pose whether or not it still knows where it is. One that has lost its position goes on +# reporting where it looks, and a position carried by its turning alone: about a millimeter for each degree, +# where a tracked head's moves several times as far, by its own motion and by the jitter of tracking. When +# the position is found again it leaps there. The limits of the lost position are from measurements on a +# headset of this kind, in the measure they were taken in: the path of the position over the path of the +# turning, each summed over the poses as they were recorded. What a sound sweep reads on the pose stream +# these takes record is not measured yet, which is why a solve's record carries its take's readings. + +#: The time over which a head track's position is set against its turning, in seconds, and the step from one +#: such window to the next. +TRACK_WINDOW_S = 2.0 +_TRACK_WINDOW_STEP_S = 0.25 +#: A position that follows the head's turning by less than this over a window, in meters per degree, is lost. +TRACK_FROZEN_M_PER_DEG = 0.002 +#: Least the head must turn in a window, in degrees, for the window to say anything of the position. +TRACK_MIN_TURN_DEG = 4.0 +#: A step from one pose to the next that takes longer than this, in seconds, is a hole in the track: what +#: the head did in it is not known, and it counts for neither path. +_TRACK_GAP_S = 0.25 +#: A step in a head's position is a jump from this size, in meters... +HEAD_JUMP_M = 0.01 +#: ...when it is this many times what the head moved in the same time just before it and just after it. A +#: head that speeds up has moved as far after as during, and one that jerks out and back has not moved. +_JUMP_FACTOR = 3.0 +#: The time a jump is looked for in, in seconds: longer than the step between two tracking samples. And the +#: shares of it that one is looked for in as well: a head moving fast hides a small leap in the whole time, +#: and poses that come slowly spread a leap beyond the shorter one. +_JUMP_S = 0.04 +_JUMP_SHARES = (1.0, 0.5) +#: Step between the moments a jump is looked for at, in seconds. +_JUMP_STEP_S = 0.01 +#: For how long after a jump, or after a position was found again, the position is not yet used, in seconds. +_SETTLE_S = 0.2 +#: Stretches of a track whose jumps add up to within this of each other, in meters, are in one frame. +_SAME_FRAME_M = 0.005 + +#: Spacing of the camera lags tried by a latency search. +LATENCY_STEP_S = 0.01 +#: Lags whose board spread is within this factor of the smallest are not told apart by the data. +_LATENCY_TIE_RATIO = 1.1 +#: A lag other than the given one is adopted only when it cuts the board spread by this share and this much. +_LATENCY_MIN_GAIN_RATIO = 0.2 +_LATENCY_MIN_GAIN_M = 0.001 + +#: OpenCV's hand-eye solvers, all of which are run and compared. +_SOLVERS = { + "TSAI": cv2.CALIB_HAND_EYE_TSAI, + "PARK": cv2.CALIB_HAND_EYE_PARK, + "HORAUD": cv2.CALIB_HAND_EYE_HORAUD, + "ANDREFF": cv2.CALIB_HAND_EYE_ANDREFF, + "DANIILIDIS": cv2.CALIB_HAND_EYE_DANIILIDIS, +} +_T_OPENXR_FROM_FLU = homogeneous(R_OPENXR_FROM_FLU, np.zeros(3)) + +_FRAME_CONVENTION = ( + "T_headset_camera maps a point in the camera's optical frame (X right, Y down, Z along the view) into " + "the headset frame with X forward, Y left and Z up, in meters. T_headset_camera_openxr is the same camera " + "pose with the headset in OpenXR axes (X right, Y up, Z backward)." +) + + +class ViewsDisagreeError(CalibrationError): + """Too few views of the board agree on where it stands for a solve. + + A board that was moved does that, and so do head poses that are wrong. The solve cannot tell which, and + says the first; a caller that knows the head tracking failed can say the second. + """ + + +def head_motion_problem(head_poses: np.ndarray) -> str | None: + """Why these head poses cannot carry a hand-eye solve, for the operator; None when the head moved enough. + + The head barely moved when its position varies less than ``MIN_HEAD_POSITION_STD_M`` along every axis and + no rotation is further than ``MIN_HEAD_ROTATION_FROBENIUS`` from the first: a headset left on a table, or + tracking that froze. + """ + poses = np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4) + # A single pose shows no motion at all. + if len(poses) > 1: + position_std = float(poses[:, :3, 3].std(axis=0).max()) + rotation_change = float(np.linalg.norm(poses[:, :3, :3] - poses[0, :3, :3], axis=(1, 2)).max()) + if position_std >= MIN_HEAD_POSITION_STD_M or rotation_change >= MIN_HEAD_ROTATION_FROBENIUS: + return None + return ( + "The headset hardly moved during the take, so the camera's place on it cannot be solved. Record again " + "while moving and turning your head around the board. If you did move, check the headset was tracked." + ) + + +def _runs(flags: np.ndarray) -> list[tuple[int, int]]: + """Each run of true values in a mask, as its first index and the index past its last.""" + edges = np.flatnonzero(np.diff(np.concatenate([[False], flags, [False]]).astype(np.int8))) + return list(zip(edges[::2].tolist(), edges[1::2].tolist())) + + +def _steps(poses: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """How far the position moves, in meters, and how far the head turns, in degrees, from each pose of a + track to the next.""" + # One pose, or none, has no step. + if len(poses) < 2: + return np.zeros(0), np.zeros(0) + turns = Rotation.from_matrix(poses[:, :3, :3]) + turned = np.degrees((turns[:-1].inv() * turns[1:]).magnitude()) + return np.linalg.norm(np.diff(poses[:, :3, 3], axis=0), axis=1), turned + + +def head_motion_per_degree( + times_s: np.ndarray, head_poses: np.ndarray, *, longest_step_s: float = _TRACK_GAP_S +) -> float | None: + """How far a head track's position moves for each degree the head turns, in meters per degree: the + length of the position's path over the length of the turning's, each summed from pose to pose over the + samples given. None when the head turned under ``TRACK_MIN_TURN_DEG`` in all. + + The figure is one of the track as it was recorded: taken over fewer poses it loses the jitter of + tracking, which is part of what a tracked position's path is made of. A step longer than + ``longest_step_s`` is a hole in the track and counts for neither path. + """ + times = np.asarray(times_s, dtype=np.float64).reshape(-1) + moved, turned = _steps(np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4)) + counted = np.diff(times) <= longest_step_s + turning = float(turned[counted].sum()) + return float(moved[counted].sum()) / turning if turning >= TRACK_MIN_TURN_DEG else None + + +class HeadTrackReader: + """Reads a head track as its poses arrive: where the position was lost, where it leapt, and from those + which stretch of sound tracking a moment belongs to. + + The position is lost over a window of ``TRACK_WINDOW_S`` in which the head turned ``TRACK_MIN_TURN_DEG`` + and the position followed by less than ``lost_below_m_per_deg`` (``head_motion_per_degree``). A leap is + a step of ``HEAD_JUMP_M`` that the motion around it does not account for. Windows and leaps are looked + for at moments fixed on the track's own clock, each once, so that a track read as it arrives and one + read whole are read alike; only the poses still needed for that are held. + """ + + def __init__( + self, *, lost_below_m_per_deg: float = TRACK_FROZEN_M_PER_DEG, longest_step_s: float = _TRACK_GAP_S + ) -> None: + """Start reading a track. The limits are those of a track given as densely as it was recorded; a + caller with fewer poses passes limits that hold for those.""" + self._limit = lost_below_m_per_deg + self._longest_step_s = longest_step_s + # The poses still to be read from. + self._times = np.zeros(0) + self._poses = np.zeros((0, 4, 4)) + # What was found: the spans the position was lost over, the leaps, and each turning window's figure. + self._lost: list[list[float]] = [] + self._jumps: list[tuple[float, np.ndarray]] = [] + self._readings: list[float] = [] + # Where the reading stands: the number of the next moment a leap is looked for at and of the next + # window, the leap being found (where it began, its size, time and vector so far), and the time up + # to which leaps are known. + self._moment: int | None = None + self._window: int | None = None + self._run: tuple[float, float, float, np.ndarray] | None = None + self._settled_s = -math.inf + + @property + def readings(self) -> np.ndarray: + """The figure of every window read so far in which the head turned enough, in meters per degree.""" + return np.asarray(self._readings) + + @property + def lost_spans(self) -> list[tuple[float, float]]: + """The spans of time the position was lost over, in order, each as its first and last moment.""" + return [(start, end) for start, end in self._lost] + + @property + def unusable_spans(self) -> list[tuple[float, float]]: + """Every span of time whose position cannot be used, in order: those the position was lost over + and the leaps, each with the ``_SETTLE_S`` after it, and one span where they run into each other.""" + spans = [(start, end + _SETTLE_S) for start, end in self._lost] + spans += [(at - 0.5 * _JUMP_S, at + 0.5 * _JUMP_S + _SETTLE_S) for at, _ in self._jumps] + merged: list[tuple[float, float]] = [] + for start, end in sorted(spans): + if merged and start <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(merged[-1][1], end)) + else: + merged.append((start, end)) + return merged + + def add(self, times_s: np.ndarray, head_poses: np.ndarray) -> None: + """Take in the poses (world from head) that arrived, in time order. One that is not later than the + last pose taken in is left out: the paths are summed in the order of time.""" + times = np.asarray(times_s, dtype=np.float64).reshape(-1) + poses = np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4) + latest = self._times[-1] if len(self._times) else -math.inf + later = times > np.maximum.accumulate(np.concatenate([[latest], times]))[:-1] + self._times = np.concatenate([self._times, times[later]]) + self._poses = np.concatenate([self._poses, poses[later]]) + # Without a pose there is no clock to place a moment on. + if not len(self._times): + return + self._find_jumps() + self._read_windows() + # Held from here on: the next window, the next moment's reach back, and the window up to now. + first_moment = self._moment * _JUMP_STEP_S - 1.5 * _JUMP_S + needed = min(self._window * _TRACK_WINDOW_STEP_S, first_moment, self._times[-1] - TRACK_WINDOW_S) + # One pose before that stays, for what is interpolated between it and the next. + first = max(int(np.searchsorted(self._times, needed, side="right")) - 1, 0) + self._times, self._poses = self._times[first:], self._poses[first:] + + def _find_jumps(self) -> None: + """Look for a leap at each moment the poses now reach far enough past.""" + # A leap is not looked for within its reach of the track's start, where what came before is not known. + if self._moment is None: + self._moment = math.ceil((self._times[0] + 1.5 * _JUMP_S) / _JUMP_STEP_S) + last = math.floor((self._times[-1] - 1.5 * _JUMP_S) / _JUMP_STEP_S) + if last < self._moment: + return + moments = np.arange(self._moment, last + 1) * _JUMP_STEP_S + positions = self._poses[:, :3, 3] + + def moved(start_s: float, span_s: float) -> np.ndarray: + """How far the position goes in ``span_s`` from ``start_s`` after each moment.""" + at = [ + np.column_stack( + [np.interp(moments + offset, self._times, positions[:, axis]) for axis in range(3)] + ) + for offset in (start_s, start_s + span_s) + ] + return at[1] - at[0] + + found = np.zeros(len(moments), dtype=bool) + size, leap = np.zeros(len(moments)), np.zeros((len(moments), 3)) + for span in (share * _JUMP_S for share in _JUMP_SHARES): + before, across, after = moved(-1.5 * span, span), moved(-0.5 * span, span), moved(0.5 * span, span) + step = np.linalg.norm(across, axis=1) + around = np.maximum(np.linalg.norm(before, axis=1), np.linalg.norm(after, axis=1)) + seen = (step >= HEAD_JUMP_M) & (step >= _JUMP_FACTOR * around) + # Seen over both times, a leap is as large as the larger sight of it. + larger = seen & (step > size) + size[larger], leap[larger] = step[larger], (across - 0.5 * (before + after))[larger] + found |= seen + # A leap being found when the poses last ran out has ended if the first new moment does not find it. + if self._run is not None and not found[0]: + self._jumps.append((self._run[2], self._run[3])) + self._run = None + for first, past in _runs(found): + # One leap is found from every moment near it; the one it is largest from sits on it. + on = first + int(np.argmax(size[first:past])) + best = (float(size[on]), float(moments[on]), leap[on]) + began = float(moments[first]) + if self._run is not None: + began = self._run[0] + best = max((self._run[1:], best), key=lambda leap: leap[0]) + # A run that reaches the last moment may go on in the poses still to come. + if past == len(found): + self._run = (began, *best) + else: + self._jumps.append(best[1:]) + self._run = None + self._moment = last + 1 + # Leaps are looked for up to the last moment, or to where one still being found began. One found + # later takes the steps half its time before it out of the paths, so those are not settled yet. + looked_to = float(moments[-1]) if self._run is None else self._run[0] - _JUMP_STEP_S + self._settled_s = looked_to - 0.5 * _JUMP_S + + def _counted_steps(self) -> tuple[np.ndarray, np.ndarray]: + """The steps of the poses held, as ``_steps`` gives them, with nothing for a step that is a hole in + the track or a leap: neither is the head's own motion.""" + moved, turned = _steps(self._poses) + counted = np.diff(self._times) <= self._longest_step_s + for at, _ in self._jumps: + counted &= (self._times[1:] < at - 0.5 * _JUMP_S) | (self._times[:-1] > at + 0.5 * _JUMP_S) + return np.where(counted, moved, 0.0), np.where(counted, turned, 0.0) + + def _read_windows(self) -> None: + """Read each window that the leaps are now known for to its end.""" + # The first window is the first to begin with a pose in hand. + if self._window is None: + self._window = math.ceil(self._times[0] / _TRACK_WINDOW_STEP_S) + # None is read before the leaps are known to the end of the next one. + if self._settled_s < self._window * _TRACK_WINDOW_STEP_S + TRACK_WINDOW_S: + return + last = math.floor((self._settled_s - TRACK_WINDOW_S) / _TRACK_WINDOW_STEP_S) + starts = np.arange(self._window, last + 1) * _TRACK_WINDOW_STEP_S + moved, turned = (np.concatenate([[0.0], np.cumsum(steps)]) for steps in self._counted_steps()) + # The poses of each window, and the steps between them. + first = np.searchsorted(self._times, starts, side="left") + end = np.maximum(np.searchsorted(self._times, starts + TRACK_WINDOW_S, side="left") - 1, first) + path, turning = moved[end] - moved[first], turned[end] - turned[first] + told = turning >= TRACK_MIN_TURN_DEG + self._readings.extend((path[told] / turning[told]).tolist()) + for window in np.flatnonzero(told & (path < self._limit * turning)).tolist(): + # A window reads as lost once most of it is, so the loss may reach a step beyond it either way. + span = [ + float(self._times[first[window]]) - _TRACK_WINDOW_STEP_S, + float(self._times[end[window]]) + _TRACK_WINDOW_STEP_S, + ] + # Windows overlap, so a loss is found in several: one span holds them. + if self._lost and span[0] <= self._lost[-1][1]: + self._lost[-1][1] = max(self._lost[-1][1], span[1]) + else: + self._lost.append(span) + self._window = max(self._window, last + 1) + + def reading(self) -> float | None: + """The figure of the last ``TRACK_WINDOW_S`` up to the newest pose, in meters per degree; None when + the head turned too little in them to say anything.""" + moved, turned = self._counted_steps() + lately = ( + self._times[:-1] >= self._times[-1] - TRACK_WINDOW_S if len(self._times) else np.zeros(0, dtype=bool) + ) + turning = float(turned[lately].sum()) + return float(moved[lately].sum()) / turning if turning >= TRACK_MIN_TURN_DEG else None + + def _frames(self) -> list[int]: + """The stretch that follows each leap, in the order of the leaps. + + A leap in tracked motion moves the frame by the leap, so what follows belongs with an earlier + stretch where the leaps since undo each other, as when a position leaps away and back. A leap made + while the position was lost, or as it was found again, begins a frame nothing ties to any before. + """ + frames: list[tuple[int, np.ndarray]] = [(0, np.zeros(3))] + epoch, shift = 0, np.zeros(3) + following = [] + for at, vector in self._jumps: + if any(start - _SETTLE_S <= at <= end + _SETTLE_S for start, end in self._lost): + epoch, shift = epoch + 1, np.zeros(3) + else: + shift = shift + vector + same = [ + label + for label, (begun, moved) in enumerate(frames) + if begun == epoch and np.linalg.norm(moved - shift) <= _SAME_FRAME_M + ] + if not same: + frames.append((epoch, shift)) + following.append(same[0] if same else len(frames) - 1) + return following + + @property + def stretch_count(self) -> int: + """How many stretches of sound tracking the track has been split into so far: one, while no leap + has begun another.""" + return max([0, *self._frames()]) + 1 + + def stretches(self, times_s: np.ndarray) -> np.ndarray: + """Which stretch of sound tracking each time belongs to: 0, 1, 2 and so on in the order they begin, + and -1 for a time whose position cannot be used: one in a span the position was lost over, in a + leap, or within ``_SETTLE_S`` after either. A lost span by itself splits nothing: what lies before + and after it is one stretch unless the position leapt. + + A time the track has not been read up to yet is taken for sound. + """ + times = np.asarray(times_s, dtype=np.float64).reshape(-1) + # How many leaps lie before each time says which stretch it is in. + leaps = np.asarray([at for at, _ in self._jumps]) + labels = np.asarray([0, *self._frames()])[np.searchsorted(leaps, times, side="left")] + for start, end in self.unusable_spans: + labels[(times >= start) & (times <= end)] = -1 + return labels + + +def head_track_stretches(times_s: np.ndarray, head_poses: np.ndarray) -> np.ndarray: + """Which stretch of sound position tracking each sample of a head track belongs to: 0, 1, 2 and so on in + the order they begin, and -1 for a sample whose position cannot be used (``HeadTrackReader.stretches``). + + ``head_poses`` are the head's poses (world from head) at ``times_s``, in time order, as densely as they + were recorded. Head poses of one stretch can be solved from together; those of two cannot. + """ + reader = HeadTrackReader() + reader.add(times_s, head_poses) + return reader.stretches(times_s) + + +def _turn_vectors(head_poses: np.ndarray) -> np.ndarray: + """Each head pose's turn away from the poses' mean orientation, as a rotation vector in radians, centred.""" + rotations = Rotation.from_matrix(head_poses[:, :3, :3]) + vectors = (rotations.mean().inv() * rotations).as_rotvec() + return vectors - vectors.mean(axis=0) + + +def head_turn_spread_deg(head_poses: np.ndarray) -> np.ndarray: + """How far three or more head poses turn from their mean orientation: the root-mean-square angle in + degrees about the axis they turn most about, about the next, and about the last. + + A hand-eye solve finds the camera's offset along an axis only from turns about the other two, so the + second figure is what a head that only turned one way lacks. + """ + poses = np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4) + return np.degrees(np.linalg.svd(_turn_vectors(poses), compute_uv=False) / np.sqrt(len(poses))) + + +def head_turn_problem(head_poses: np.ndarray) -> str | None: + """Why the head poses at the views of the board cannot carry a hand-eye solve, for the operator; None + when the head turned enough, and about more than one axis. + + Unlike ``head_motion_problem`` this judges turning alone, since moving without turning fixes nothing, + and only the poses it is given: the views a solve is about to use, not the whole take. + """ + most, second, _ = head_turn_spread_deg(head_poses) + # Asked first: a head that hardly turned is not to be told it turned about one axis only. + if most < MIN_HEAD_TURN_DEG: + return ( + "The headset hardly turned while the board was in view, so the camera's place on it cannot be " + "solved. Record again, turning your head in every direction while you look at the board." + ) + # However far the head turned about one axis, the camera's offset along that axis stays free. + if second < MIN_HEAD_SECOND_TURN_DEG: + return ( + "The headset turned about one axis only while the board was in view, which leaves the camera's " + "place along that axis unsolved. Record again, nodding and tilting your head as well as turning it." + ) + return None + + +def _require_turns(head_poses: np.ndarray) -> None: + """Refuse, in the operator's words, head poses that cannot carry a hand-eye solve.""" + problem = head_turn_problem(head_poses) + if problem is not None: + raise CalibrationError(problem) + + +def position_uncertainty_m(spread_m: float, head_poses: np.ndarray) -> float | None: + """How far off a solved camera position may be along the direction its views pin least, in meters; None + when they do not pin that direction at all. + + Turns about an axis say nothing of the camera's offset along it, so the offset along the axis the head + turned most about rests on the turns off that axis. Their squared sum over the views, in radians, is the + information the views hold, the board's wander ``spread_m`` the noise, and this the noise over the root + of the information, with the ``_TURN_TRIM`` share of views that turned furthest off the axis left out. + """ + vectors = _turn_vectors(np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4)) + # Each view's squared turn, less the part about the main axis, which says nothing of the offset along it. + main_axis = np.linalg.svd(vectors, full_matrices=False)[2][0] + off_axis = np.square(vectors).sum(axis=1) - np.square(vectors @ main_axis) + # The views that say most are the ones left out: a few stray views cannot then stand for a head that + # otherwise held still. + counted = len(vectors) - math.ceil(_TURN_TRIM * len(vectors)) + information = float(np.sort(off_axis)[:counted].sum()) + # With no more than rounding left to divide by, the direction is simply not pinned. + return float(spread_m / np.sqrt(information)) if information > _NO_TURN_INFORMATION else None + + +def _invert_poses(poses: np.ndarray) -> np.ndarray: + """The inverses of a stack of rigid poses, from their transposes.""" + out = np.zeros_like(poses) + out[:, :3, :3] = poses[:, :3, :3].transpose(0, 2, 1) + out[:, :3, 3] = -np.einsum("nij,nj->ni", out[:, :3, :3], poses[:, :3, 3]) + out[:, 3, 3] = 1.0 + return out + + +def _angles_deg(rotations: np.ndarray) -> np.ndarray: + """The turn each rotation matrix of a stack makes, in degrees.""" + return np.degrees(Rotation.from_matrix(rotations).magnitude()) + + +def board_poses_in_camera( + views: Sequence[BoardView], intrinsics: Intrinsics +) -> list[tuple[np.ndarray, float] | None]: + """Each view's board pose in the camera with its reprojection RMS, in order; None for a view without one. + + These do not depend on the head poses, so a caller solving the same views against several sets of head + poses computes them once and passes them to the solve as ``board_poses``. The lens model is the + intrinsics' own (``camera_model.board_pose``). + """ + return [board_pose(view, intrinsics) for view in views] + + +def _hand_eye(method: int, world_head: np.ndarray, camera_board: np.ndarray) -> np.ndarray | None: + """One solver's camera-on-headset pose; None when it fails or returns something that is not a rigid pose.""" + try: + rotation, translation = cv2.calibrateHandEye( + list(world_head[:, :3, :3]), + list(world_head[:, :3, 3]), + list(camera_board[:, :3, :3]), + list(camera_board[:, :3, 3]), + method=method, + ) + except cv2.error: + # Raised when the motions between the views are too alike to solve from. + return None + pose = homogeneous(rotation, np.asarray(translation).reshape(3)) + # Rather than fail, a solver can return NaN or a reflection when the motions leave an axis undetermined. + rigid = ( + np.all(np.isfinite(pose)) + and np.allclose(pose[:3, :3] @ pose[:3, :3].T, np.eye(3), atol=1e-6) + and np.linalg.det(pose[:3, :3]) > 0 + ) + return pose if rigid else None + + +def _board_turns_deg(board_world: np.ndarray) -> np.ndarray: + """How far each view's board orientation is from the mean orientation, in degrees.""" + mean = Rotation.from_matrix(board_world[:, :3, :3]).mean().as_matrix() + return _angles_deg(board_world[:, :3, :3] @ mean.T) + + +def _consistent_views(world_head: np.ndarray, camera_board: np.ndarray) -> np.ndarray: + """Which views agree on where the board stands, under a first hand-eye fit over all of them. + + A view with a wrong pose (a mismatched head pose, a board seen too obliquely, a head position that + leapt for a moment) puts the board somewhere else in the world than the rest do. How far "somewhere + else" is follows the views themselves (``_BOARD_SHIFT_MEDIANS``): a rig whose views agree to 2 mm shows + a 4 cm leap that a fixed limit of 5 cm lets through. Without a first fit there is nothing to compare + against, and every view is kept for the solvers to judge. + """ + first = _hand_eye(cv2.CALIB_HAND_EYE_HORAUD, world_head, camera_board) + if first is None: + return np.ones(len(world_head), dtype=bool) + board_world = world_head @ first @ camera_board + positions = board_world[:, :3, 3] + shift = np.linalg.norm(positions - np.median(positions, axis=0), axis=1) + limit = min(max(_BOARD_SHIFT_MEDIANS * float(np.median(shift)), MIN_BOARD_SHIFT_M), MAX_BOARD_SHIFT_M) + return (shift < limit) & (_board_turns_deg(board_world) < MAX_BOARD_TURN_DEG) + + +def _method_record(head_camera: np.ndarray, world_head: np.ndarray, camera_board: np.ndarray) -> dict[str, Any]: + """One solver's result and how still it leaves the board, which never moved, across the views.""" + board_world = world_head @ head_camera @ camera_board + position_std = board_world[:, :3, 3].std(axis=0) + turns = _board_turns_deg(board_world) + return { + "T_headset_camera": head_camera.tolist(), + "translation_m": head_camera[:3, 3].tolist(), + "translation_norm_m": float(np.linalg.norm(head_camera[:3, 3])), + "rotation_rpy_deg_xyz": Rotation.from_matrix(head_camera[:3, :3]).as_euler("xyz", degrees=True).tolist(), + "board_position_std_m": position_std.tolist(), + "board_position_std_norm_m": float(np.linalg.norm(position_std)), + "board_rotation_std_deg": float(turns.std()), + "board_rotation_max_deg": float(turns.max()), + } + + +def _rotation_consistency(world_head: np.ndarray, camera_board: np.ndarray) -> dict[str, float]: + """How well the headset's turns between views match the camera's, which a rigid mount makes equal. + + A large mismatch points at head poses that do not belong to the frames: a wrong time offset, or tracking + that drifted. + """ + head_turns = _angles_deg((_invert_poses(world_head[1:]) @ world_head[:-1])[:, :3, :3]) + camera_turns = _angles_deg((camera_board[1:] @ _invert_poses(camera_board[:-1]))[:, :3, :3]) + # The floor keeps two views with almost no turn between them from dividing by nothing. + relative = np.abs(head_turns - camera_turns) / np.maximum(head_turns, 1e-3) + return { + "headset_mean_deg": float(head_turns.mean()), + "camera_mean_deg": float(camera_turns.mean()), + "mean_relative_error": float(relative.mean()), + "max_relative_error": float(relative.max()), + } + + +def _posed_views( + views: Sequence[BoardView], + head_poses: np.ndarray, + board_poses: Sequence[tuple[np.ndarray, float] | None], + invert_head: bool, +) -> tuple[list[int], np.ndarray, np.ndarray, np.ndarray]: + """The views that give a board pose: their frames, the headset's pose in the world (forward-left-up), the + board's pose in the camera, and the reprojection RMS of that pose.""" + recorded = np.asarray(head_poses, dtype=np.float64).reshape(-1, 4, 4) + frames, heads, boards, errors = [], [], [], [] + for view, head, posed in zip(views, recorded, board_poses, strict=True): + # A view without a board pose has nothing to set against its head pose. + if posed is None: + continue + frames.append(view.frame) + # The stored pose is in OpenXR axes; the calibration file describes the headset forward-left-up. + heads.append((invert_pose(head) if invert_head else head) @ _T_OPENXR_FROM_FLU) + boards.append(posed[0]) + errors.append(posed[1]) + if len(frames) < MIN_VIEWS: + raise CalibrationError( + f"Only {len(frames)} views gave a pose of the board and at least {MIN_VIEWS} are needed. " + "Record again, keeping the board in view for longer." + ) + return frames, np.stack(heads), np.stack(boards), np.asarray(errors) + + +def _run_solvers(world_head: np.ndarray, camera_board: np.ndarray) -> dict[str, dict[str, Any]]: + """Every solver's result on the kept views, by name; a solver that gives up is left out.""" + methods = {} + for name, method in _SOLVERS.items(): + head_camera = _hand_eye(method, world_head, camera_board) + # One solver giving up says nothing about the others. + if head_camera is not None: + methods[name] = _method_record(head_camera, world_head, camera_board) + if not methods: + raise CalibrationError( + "The camera's place on the headset could not be solved from this take. Record again, turning your " + "head about more than one axis while looking at the board." + ) + return methods + + +def solve_head_camera_extrinsics( + views: Sequence[BoardView], + head_poses: np.ndarray, + intrinsics: Intrinsics, + spec: BoardSpec, + *, + invert_head: bool = False, + board_poses: Sequence[tuple[np.ndarray, float] | None] | None = None, +) -> dict[str, Any]: + """Solve the camera's pose on the headset; returns the record a head-camera extrinsics file stores. + + ``head_poses[i]`` is the recorded head pose (world from head, OpenXR axes) at the time of ``views[i]``; + with ``invert_head`` each is inverted first, for a stream recorded the other way round. Views that + disagree on where the board stands are dropped, every OpenCV hand-eye solver is run on the rest, and the + one that leaves the board stillest wins. Too few views, a head that hardly turned or turned about one + axis only (``head_turn_problem``, over the views and again over those kept), fewer than half of them + agreeing (a ``ViewsDisagreeError``), or no solver succeeding, is a ``CalibrationError``. ``board_poses`` + are the views' ``board_poses_in_camera``, for a caller that already has them. + + How still the board stands says nothing of how well the views pin the camera, so the record also carries + what the grade needs to judge that, both over the views the solve kept: ``head_turn_spread_deg`` and + ``position_uncertainty_m``, from the functions of those names. + """ + # The board's pose in each view is the same whatever the head poses, so it is taken as given when it is. + if board_poses is None: + board_poses = board_poses_in_camera(views, intrinsics) + frames, posed_heads, posed_boards, pnp_rms = _posed_views(views, head_poses, board_poses, invert_head) + # Before any fit: without turns about two axes the first fit is arbitrary, would throw out sound views, + # and the take would be refused for a board that moved. + _require_turns(posed_heads) + + keep = _consistent_views(posed_heads, posed_boards) + kept = int(keep.sum()) + # Views are judged against the median board position, which means nothing unless most of them share it. + if kept < MIN_VIEWS or 2 * kept < len(keep): + raise ViewsDisagreeError( + f"The board seemed to move: only {kept} of {len(keep)} views agree on where it stands. Fix the board " + "to something rigid and record again." + ) + world_head, camera_board, pnp_rms = posed_heads[keep], posed_boards[keep], pnp_rms[keep] + used = [frame for frame, kept_view in zip(frames, keep) if kept_view] + # Again over the views kept, which are the ones solved from: the few views of a head on the move can be + # the very ones dropped, leaving those of a head that held still. + _require_turns(world_head) + + methods = _run_solvers(world_head, camera_board) + # The board never moved, so the solver under which it wanders least is the most consistent one. + best = min(methods, key=lambda name: methods[name]["board_position_std_norm_m"]) + head_camera = np.asarray(methods[best]["T_headset_camera"]) + turns = _angles_deg(world_head[1:, :3, :3].transpose(0, 2, 1) @ world_head[:-1, :3, :3]) + # Over every posed view, dropped ones included, so a fit to a few kept views cannot pass for a good one. + positions = (posed_heads @ head_camera @ posed_boards)[:, :3, 3] + shifts = np.linalg.norm(positions - np.median(positions, axis=0), axis=1) + return { + "frame_convention": _FRAME_CONVENTION, + # The head poses solved against are the OpenXR ones, and the transform is right for those alone. + POSE_SOURCE_KEY: OPENXR_POSES, + **spec.to_record(), + "best_method": best, + "T_headset_camera": head_camera.tolist(), + "T_headset_camera_openxr": (_T_OPENXR_FROM_FLU @ head_camera).tolist(), + "n_views": len(used), + "num_views_outlier_removed": len(frames) - len(used), + "used_frames": used, + "mean_pnp_reproj_rms_px": float(pnp_rms.mean()), + "max_pnp_reproj_rms_px": float(pnp_rms.max()), + "headset_inter_frame_rotation_deg": { + "mean": float(turns.mean()), + "min": float(turns.min()), + "max": float(turns.max()), + }, + "rotation_consistency": _rotation_consistency(world_head, camera_board), + "head_turn_spread_deg": head_turn_spread_deg(world_head).tolist(), + "position_uncertainty_m": position_uncertainty_m(methods[best]["board_position_std_norm_m"], world_head), + "board_position_spread_all_views_m": float(np.percentile(shifts, 75)), + "methods": methods, + "invert_head": bool(invert_head), + } + + +def board_position_spread_m(record: dict[str, Any]) -> float: + """The headline error of an extrinsics record: how far its best solver leaves the static board wandering.""" + return float(record["methods"][record["best_method"]]["board_position_std_norm_m"]) + + +def solve_with_head_direction_check( + views: Sequence[BoardView], + head_poses: np.ndarray, + intrinsics: Intrinsics, + spec: BoardSpec, + *, + board_poses: Sequence[tuple[np.ndarray, float] | None] | None = None, +) -> dict[str, Any]: + """Solve with the head poses as recorded and inverted, and keep the direction the board stands stiller in. + + Which way round a pose stream is stored is the classic hand-eye mistake, and the wrong way either fails or + leaves the board wandering by far more. The directions are compared by ``board_position_spread_all_views_m``, + the distance from the median board position that three quarters of all posed views stay within: the best + solver's own spread covers only the views it kept, and the wrong direction can keep a handful that fit. + The inverted reading must leave the board ``_INVERSION_MARGIN`` times stiller to win, because with only + a few views both readings fit and the recorder is known to write the poses the first way. + + The record says which was kept (``invert_head``) and that spread for both (``invert_head_spread_m``, None + for a direction that could not be solved). When neither can be solved, the failure as recorded is raised. + ``board_poses`` are the views' ``board_poses_in_camera``, for a caller that already has them. + """ + # Both directions look at the same views, so the board is posed in them once. + if board_poses is None: + board_poses = board_poses_in_camera(views, intrinsics) + solved: dict[bool, dict[str, Any]] = {} + failures: list[CalibrationError] = [] + for invert in (False, True): + try: + solved[invert] = solve_head_camera_extrinsics( + views, head_poses, intrinsics, spec, invert_head=invert, board_poses=board_poses + ) + except CalibrationError as error: + failures.append(error) + if not solved: + raise failures[0] + spreads = {invert: record["board_position_spread_all_views_m"] for invert, record in solved.items()} + # A direction that could not be solved loses to one that could, whatever the margin. + as_recorded, inverted = spreads.get(False, np.inf), spreads.get(True, np.inf) + record = solved[bool(_INVERSION_MARGIN * inverted < as_recorded)] + record["invert_head_spread_m"] = {"false": spreads.get(False), "true": spreads.get(True)} + return record + + +def _solve_views_with_head_pose( + views: Sequence[BoardView], + head_poses: np.ndarray, + valid: np.ndarray, + board_poses: Sequence[tuple[np.ndarray, float] | None], + intrinsics: Intrinsics, + spec: BoardSpec, +) -> dict[str, Any]: + """The solve, with the head-direction check, from the views that have a head pose under one camera lag.""" + kept = np.flatnonzero(valid) + # What few views remain when most have no head pose could be fitted at almost any lag, and would win. + if 2 * len(kept) < len(views): + raise CalibrationError( + f"Only {len(kept)} of {len(views)} views of the board have a head pose. Check the headset was tracked " + "throughout the take, and record again." + ) + return solve_with_head_direction_check( + [views[i] for i in kept], head_poses[kept], intrinsics, spec, board_poses=[board_poses[i] for i in kept] + ) + + +def solve_with_latency_search( + views: Sequence[BoardView], + head_poses_at_lag: Callable[[float], tuple[np.ndarray, np.ndarray]], + intrinsics: Intrinsics, + spec: BoardSpec, + *, + given_s: float, + half_range_s: float, + progress: Callable[[float, str], None] | None = None, +) -> dict[str, Any]: + """Solve at the camera lag, near the given one, under which the board stands stillest. + + A camera's frames are exposed some time before the times recorded for them, and a lag that is off pairs + every frame with the head pose of another moment. ``head_poses_at_lag(lag_s)`` gives, for each view, the + head pose when its frame is taken to be ``lag_s`` older than recorded, and whether there is one. Lags from + ``given_s - half_range_s`` to ``given_s + half_range_s`` are tried ``LATENCY_STEP_S`` apart, each solved + with the head-direction check from the views that have a head pose under it, and compared by + ``board_position_spread_all_views_m``. A lag that cannot be solved, or under which fewer than half the + views have a head pose, is passed over. + + The best lag is the one nearest the given lag among those the data does not tell apart from the stillest + (``_LATENCY_TIE_RATIO``). It is adopted when the given lag could not be solved, or when it cuts the given + lag's spread by enough to matter, as a share and as a distance (``_LATENCY_MIN_GAIN_RATIO``, + ``_LATENCY_MIN_GAIN_M``); otherwise the given lag is kept, so that noise is not chased. The record + is the adopted lag's, with ``camera_latency_s`` (the lag it used) and ``camera_latency_search`` + (``half_range_s``, ``step_s``, ``given_s``, ``best_s``, ``spread_at_given_m``, None when the given lag + could not be solved, ``spread_at_best_m``, ``adopted`` and ``at_range_end``). When no lag can be solved, + the failure at the given lag is raised. + + ``at_range_end`` says an adopted lag may not be the true one: the first or the last lag tried is among + those the data does not tell apart from the best, so the board may stand stiller still beyond the range. + """ + board_poses = board_poses_in_camera(views, intrinsics) + steps = max(int(half_range_s / LATENCY_STEP_S + 1e-9), 0) + solved: dict[int, dict[str, Any]] = {} + failure_at_given: CalibrationError | None = None + for done, step in enumerate(range(-steps, steps + 1), start=1): + # A frame moved past the end of the tracking by this lag has no head pose, and is marked so. + poses, valid = head_poses_at_lag(given_s + step * LATENCY_STEP_S) + try: + solved[step] = _solve_views_with_head_pose(views, poses, valid, board_poses, intrinsics, spec) + except CalibrationError as error: + # Most wrong lags cannot be solved at all; only the given one's failure is worth reporting. + if step == 0: + failure_at_given = error + if progress is not None: + progress(done / (2 * steps + 1), f"Trying camera lags: {done} of {2 * steps + 1}") + if not solved: + raise failure_at_given + + spreads = {step: record["board_position_spread_all_views_m"] for step, record in solved.items()} + # Among lags the data does not tell apart, the one that changes the given lag least. + near_ties = [step for step in spreads if spreads[step] <= _LATENCY_TIE_RATIO * min(spreads.values())] + best = min(near_ties, key=lambda step: (abs(step), spreads[step])) + adopted = 0 not in spreads or ( + spreads[best] <= (1.0 - _LATENCY_MIN_GAIN_RATIO) * spreads[0] + and spreads[best] <= spreads[0] - _LATENCY_MIN_GAIN_M + ) + used = best if adopted else 0 + # Asked of the near ties and not of the best lag alone: the tie rule takes the lag nearest the given one, + # which with a slowly moving head lies a step or two inside the range while the end is as good. + at_range_end = adopted and (min(near_ties) == -steps or max(near_ties) == steps) + # A lag built from steps is rounded to the microsecond, to read as the number it stands for; the given + # lag comes back as it was given. + lags = { + step: float(given_s) if step == 0 else round(given_s + step * LATENCY_STEP_S, 6) for step in (used, best) + } + record = solved[used] + record["camera_latency_s"] = lags[used] + record["camera_latency_search"] = { + "half_range_s": float(half_range_s), + "step_s": LATENCY_STEP_S, + "given_s": float(given_s), + "best_s": lags[best], + "spread_at_given_m": spreads.get(0), + "spread_at_best_m": spreads[best], + "adopted": bool(adopted), + "at_range_end": bool(at_range_end), + } + return record diff --git a/examples/egocap/recording/egocap/calibration/files.py b/examples/egocap/recording/egocap/calibration/files.py new file mode 100644 index 0000000000..fd59915233 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/files.py @@ -0,0 +1,313 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The station's calibration files: their names, and reading the two that other calibrations are solved from. + +A station keeps one flat directory of calibration JSONs (``egocap.core.data_root.calibration_dir``). The +recorder copies them into every session under the same names, so the names are a contract with whatever reads +a recording later. The recorder's list is its own, in the backend, in an order a take's configuration digest +depends on; ``test_calibration_station_store`` holds it to the names the station store installs. Errors here +name a file, never a directory: they are shown to an operator in a browser. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +import uuid +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np + +from egocap.recording.episode_layout import fsync_dir + +HEAD_INTRINSICS = "head_camera_intrinsics.json" +HEAD_EXTRINSICS = "head_camera_extrinsics.json" +LEFT_WRIST_INTRINSICS = "left_wrist_camera_intrinsics.json" +RIGHT_WRIST_INTRINSICS = "right_wrist_camera_intrinsics.json" +WRIST_OFFSETS = "wrist_calibration_offsets.json" + +#: The intrinsics file of the camera filling each station role. +ROLE_INTRINSICS = { + "ego": HEAD_INTRINSICS, + "wrist_left": LEFT_WRIST_INTRINSICS, + "wrist_right": RIGHT_WRIST_INTRINSICS, +} + +#: In a session whose video was corrected when it was recorded, the lens calibration each role's correction +#: was built from. The role's own intrinsics file then describes the corrected picture, which is what a reader +#: of a session's video expects that file to describe. +HEAD_LENS_INTRINSICS = "head_camera_lens_intrinsics.json" +LEFT_WRIST_LENS_INTRINSICS = "left_wrist_camera_lens_intrinsics.json" +RIGHT_WRIST_LENS_INTRINSICS = "right_wrist_camera_lens_intrinsics.json" +ROLE_LENS_INTRINSICS = { + "ego": HEAD_LENS_INTRINSICS, + "wrist_left": LEFT_WRIST_LENS_INTRINSICS, + "wrist_right": RIGHT_WRIST_LENS_INTRINSICS, +} + +#: Which tracking the poses behind a head-camera position or a pair of wrist offsets came from, as those two +#: kinds of file state it. This project's head and controller poses are the OpenXR ones. A file made from +#: another source's poses carries the same keys and holds transforms for other poses. +POSE_SOURCE_KEY = "pose_source" +OPENXR_POSES = "openxr" + +#: OpenCV's radial-tangential lens model, and its fisheye model. A file says which its coefficients belong to. +PINHOLE = "pinhole" +FISHEYE = "fisheye" +#: What each model's ``distortion_model`` key says, for a reader that wants the coefficients' names. +DISTORTION_NAMES = {PINHOLE: "k1_k2_p1_p2_k3", FISHEYE: "k1_k2_k3_k4"} +#: How many coefficients each model's distortion vector may hold. +_MODEL_LENGTHS = {PINHOLE: (5, 8, 12, 14), FISHEYE: (4,)} + + +class CalibrationFileError(ValueError): + """A calibration file that is missing, unreadable or not of the expected shape.""" + + +@dataclass(frozen=True) +class Intrinsics: + """A camera's solved intrinsics: its matrix, its distortion, and the image size they were solved at.""" + + K: np.ndarray + dist: np.ndarray + image_size_wh: tuple[int, int] + #: The whole file, for the provenance fields (solve quality, board) a consumer may check. + record: dict[str, Any] + #: Which lens model ``dist`` belongs to: ``PINHOLE`` or ``FISHEYE``. The two project differently, so + #: nothing may read the coefficients without it. + model: str = PINHOLE + + +def absent(path: Path | str) -> bool: + """Whether nothing stands at ``path``. Out of reach is not absent: a read of it fails and says so. + + For a caller to whom "there is none" and "it cannot be looked at" mean different things: only the first + lets it go on without the file. A link that leads nowhere is something that stands there. + """ + try: + os.lstat(path) + except (FileNotFoundError, NotADirectoryError): + return True + except OSError: + # Not ours to look at, or reached through a link that only leads back to itself. + return False + return False + + +def write_json(path: Path, record: Mapping[str, Any]) -> None: + """Write a JSON file whole: beside its destination, flushed, and renamed over it. + + The name of the file written first is ours to choose, not a private temporary file's, so the result has + the permissions of any new file. A station's calibration files, its plan and a run's streams state pass + between the page and the launcher, which may run under different accounts; made owner-only, neither could + read what the other wrote. + """ + temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + try: + with open(temporary, "x", encoding="utf-8") as file: + json.dump(record, file, indent=2, sort_keys=True) + file.flush() + os.fsync(file.fileno()) + os.replace(temporary, path) + finally: + # Renamed away by now, or left by a failure or an interrupt: it never stays beside the file it was for. + # Where it could not even be made there is none to remove, and the failure itself is what is raised. + with contextlib.suppress(OSError): + temporary.unlink(missing_ok=True) + fsync_dir(path.parent) + + +def _file_bytes(path: Path) -> bytes: + """A calibration file's bytes; one that cannot be read is a ``CalibrationFileError`` naming the file.""" + try: + return path.read_bytes() + except OSError: + # Absent, a directory, or not ours to read: an operator is told which file, never where it is. + raise CalibrationFileError(f"{path.name} could not be read") from None + + +def _json_object(data: bytes, name: str) -> dict[str, Any]: + """The JSON object a calibration file's bytes hold; ``name`` is the file named in an error.""" + try: + value = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + # ValueError, not JSONDecodeError: bytes that are not UTF-8 raise UnicodeDecodeError, which is one + # too. Brackets nested too deep to parse are no more a calibration than a syntax error is. + raise CalibrationFileError(f"{name} is not valid JSON") from None + # Every reader looks fields up by name; a list or a number would fail there, far from the file's name. + if not isinstance(value, dict): + raise CalibrationFileError(f"{name} does not hold a JSON object") + return value + + +def read_json_object(path: Path) -> dict[str, Any]: + """The JSON object in a calibration file; anything else is a ``CalibrationFileError`` naming the file.""" + return _json_object(_file_bytes(path), path.name) + + +def _matrix(record: dict[str, Any], key: str, shape: tuple[int, int], name: str) -> np.ndarray: + """A finite matrix of the given shape from a file's record.""" + try: + matrix = np.asarray(record.get(key), dtype=np.float64) + except (TypeError, ValueError, OverflowError): + # A file edited by hand can hold any of these: text or rows of unequal length (ValueError), an + # object (TypeError), a whole number too large for a float (OverflowError). + raise CalibrationFileError(f"{name}: {key} is not numeric") from None + # Refused here, where the file can be named: OpenCV fails on a NaN or a wrong shape far from it. + if matrix.shape != shape or not np.all(np.isfinite(matrix)): + raise CalibrationFileError(f"{name}: {key} must be a finite {shape[0]}x{shape[1]} matrix") + return matrix + + +def intrinsics_from_record(record: dict[str, Any], name: str) -> Intrinsics: + """The intrinsics an intrinsics file's record describes; ``name`` is the file named in an error.""" + K = _matrix(record, "K", (3, 3), name) + # OpenCV's lens models read four numbers of this matrix. One that states a skew or another last row (from + # another solver, or a hand edit) would be used as if it did not, and recorded as if it had been. + if K[0, 1] != 0 or K[1, 0] != 0 or K[2].tolist() != [0.0, 0.0, 1.0]: + raise CalibrationFileError(f"{name}: K must be [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]") + try: + # Flattened, so a vector saved as one row and one saved as one column read the same. + dist = np.asarray(record.get("dist_coeffs"), dtype=np.float64).ravel() + except (TypeError, ValueError, OverflowError): + # The same errors as for a matrix, answered the same way: by naming the file. + raise CalibrationFileError(f"{name}: dist_coeffs is not numeric") from None + if dist.size == 0 or not np.all(np.isfinite(dist)): + raise CalibrationFileError(f"{name}: dist_coeffs must hold finite numbers") + model = _model_of(record, dist.size, name) + size = record.get("image_size_wh") + # A bool is an int to Python, and no image is True pixels wide. + sized = isinstance(size, list) and len(size) == 2 and all(type(n) is int and n > 0 for n in size) + if not sized: + raise CalibrationFileError(f"{name}: image_size_wh must be two positive whole numbers") + return Intrinsics(K=K, dist=dist, image_size_wh=(size[0], size[1]), record=record, model=model) + + +def _model_of(record: dict[str, Any], coefficients: int, name: str) -> str: + """The lens model a record's coefficients belong to, from its ``model`` key and their number.""" + model = record.get("model") + if model is None: + # A file from before the key existed is the radial-tangential model, the only one solved then. Four + # numbers are never taken for fisheye by their count: four radial-tangential numbers look the same + # and mean another lens. + if coefficients not in _MODEL_LENGTHS[PINHOLE]: + raise CalibrationFileError( + f"{name}: {coefficients} distortion coefficients and no model; a file must say " + f'"model": "{PINHOLE}" or "{FISHEYE}"' + ) + return PINHOLE + # A list or an object cannot even be looked up among the models' names: no lens model is anything but text. + if not isinstance(model, str) or model not in _MODEL_LENGTHS: + raise CalibrationFileError(f'{name}: model must be "{PINHOLE}" or "{FISHEYE}"') + if coefficients not in _MODEL_LENGTHS[model]: + wanted = " or ".join(str(n) for n in _MODEL_LENGTHS[model]) + raise CalibrationFileError( + f"{name}: a {model} model has {wanted} distortion coefficients, not {coefficients}" + ) + return model + + +def _showable(value: Any) -> bool: + """Whether a value read from a file is text that can be shown. A file written by hand can hold half of a + surrogate pair, which neither a terminal nor a reply to a page can encode.""" + if not isinstance(value, str): + return False + # Asked by encoding it, as whatever shows it would. + try: + value.encode("utf-8") + except UnicodeEncodeError: + return False + return True + + +def other_camera_problem(record: Mapping[str, Any], camera: str | None, name: str) -> str | None: + """Why the calibration file ``name``, whose content is ``record``, must not be used for ``camera``; None + when it may. + + A solve stamps the camera it was made for, and a role can change hands afterwards: used for another + camera, a lens model corrects and poses pictures that lens never took. None when the stamp names this + camera, when there is no camera to hold it against, and when the file names none (one placed by hand). + The sentence is written for an operator. + """ + solved_for = record.get("camera") + # No camera to hold it against, no stamp that names one, or the same camera: nothing to refuse. + if camera is None or not _showable(solved_for) or solved_for == camera: + return None + # A stream that was only renamed trips this too, so the sentence says what clears it. + return ( + f"{name} was solved for camera {solved_for!r}, and {camera!r} fills the role now; calibrate this camera " + "to replace it" + ) + + +def camera_stamp_note(record: Mapping[str, Any], name: str) -> str | None: + """What an operator should know of the lens file ``name`` when its record names no camera; None when it + names one. + + The stamp is what ``other_camera_problem`` holds a file against. A file without it, from another tool or + placed by hand, passes for any camera, one of the same picture size and another lens included. + """ + if _showable(record.get("camera")): + return None + return f"{name} is not stamped for a camera, so it cannot be checked against the camera in this role" + + +def pose_source_problem(record: Mapping[str, Any], name: str) -> str | None: + """Why the head-camera position or the wrist offsets in the file ``name`` must not be built on; None when + they may. + + Both are transforms between tracked poses, right only for the poses they were made with. A record this + project's tools write says its poses are the OpenXR ones. One that does not was made with another + tracking source or by another tool: it reads without complaint and is wrong here by a fixed transform + nothing shows. A lens file is not asked: a lens is the same whatever tracks the headset. + """ + if record.get(POSE_SOURCE_KEY) == OPENXR_POSES: + return None + return f"{name} was made with another tracking source or another tool: calibrate again" + + +def intrinsics_identity(intrinsics: Intrinsics) -> str: + """A hash that is the same for the same camera model however its file was written out. + + Taken over the model, the image size, K and the coefficients as exact IEEE numbers, so two files that + differ only in key order, spacing or provenance name the same calibration. + """ + digest = hashlib.sha256() + digest.update(intrinsics.model.encode()) + digest.update(np.asarray(intrinsics.image_size_wh, dtype=" str: + """The SHA-256 of a file's bytes, as the recorder stores for the calibration files it copies.""" + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def load_intrinsics(path: Path) -> Intrinsics: + """Read a camera intrinsics file.""" + return intrinsics_from_record(read_json_object(path), path.name) + + +def load_intrinsics_with_sha256(path: Path) -> tuple[Intrinsics, str]: + """Read a camera intrinsics file once: what it describes, and the SHA-256 of the bytes that say so. + + For a caller that records the hash beside what it made of the file: read twice, a file replaced between + the two reads would be recorded under the hash of a calibration that was never used. + """ + data = _file_bytes(path) + return intrinsics_from_record(_json_object(data, path.name), path.name), hashlib.sha256(data).hexdigest() + + +def load_headset_extrinsics(path: Path) -> np.ndarray: + """Read ``T_headset_camera`` from a head-camera extrinsics file: the camera's optical frame expressed in + the headset frame whose axes are X forward, Y left, Z up, in meters.""" + return _matrix(read_json_object(path), "T_headset_camera", (4, 4), path.name) diff --git a/examples/egocap/recording/egocap/calibration/frames.py b/examples/egocap/recording/egocap/calibration/frames.py new file mode 100644 index 0000000000..88b74d1bb3 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/frames.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Coordinate frames the calibrations share, and the small rigid-transform helpers they are written with. + +Tracking is recorded in OpenXR axes (X right, Y up, -Z forward). The calibration files describe the headset +and the world in forward-left-up axes (X forward, Y left, Z up), the convention their readers expect. Poses +are 4x4 homogeneous matrices in meters, and ``T_a_b`` maps a point in frame ``b`` to frame ``a``. +""" + +from __future__ import annotations + +import numpy as np +from scipy.spatial.transform import Rotation + +#: Rotates forward-left-up coordinates into OpenXR coordinates of the same body. +R_OPENXR_FROM_FLU = np.array([[0.0, -1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0]]) +#: Rotates OpenXR coordinates into forward-left-up coordinates of the same body. +R_FLU_FROM_OPENXR = R_OPENXR_FROM_FLU.T + + +def homogeneous(rotation: np.ndarray, translation: np.ndarray) -> np.ndarray: + """The 4x4 pose with the given rotation matrix and translation.""" + pose = np.eye(4) + pose[:3, :3] = rotation + pose[:3, 3] = translation + return pose + + +def invert_pose(pose: np.ndarray) -> np.ndarray: + """The inverse of a rigid pose, from its transpose: exact for a rotation, unlike a general inverse.""" + rotation = pose[:3, :3].T + return homogeneous(rotation, -rotation @ pose[:3, 3]) + + +def euler_pose(rx_deg: float, ry_deg: float, rz_deg: float) -> np.ndarray: + """A pure rotation pose from angles about the fixed X, then Y, then Z axes, in degrees.""" + return homogeneous(Rotation.from_euler("xyz", [rx_deg, ry_deg, rz_deg], degrees=True).as_matrix(), np.zeros(3)) + + +def openxr_poses_to_flu(poses: np.ndarray) -> np.ndarray: + """Re-express poses given in OpenXR world axes in forward-left-up world axes. + + Both the world and the body change axes, so the rotation is conjugated, not just premultiplied: a body + at rest along the OpenXR axes is at rest along the forward-left-up ones. Accepts any leading shape. + """ + poses = np.asarray(poses, dtype=np.float64) + out = np.array(poses, dtype=np.float64, copy=True) + out[..., :3, 3] = poses[..., :3, 3] @ R_FLU_FROM_OPENXR.T + out[..., :3, :3] = R_FLU_FROM_OPENXR @ poses[..., :3, :3] @ R_FLU_FROM_OPENXR.T + return out diff --git a/examples/egocap/recording/egocap/calibration/grading.py b/examples/egocap/recording/egocap/calibration/grading.py new file mode 100644 index 0000000000..660c751876 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/grading.py @@ -0,0 +1,536 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Grading a solved calibration for the operator: how good it is, whether it may be installed, what to redo. + +A solve is graded on two kinds of number, and its grade is the worst of them. Its residuals say how well it +fits the views it used, and they get smaller, not larger, as those views get fewer or more alike. Its +evidence says whether the views pin the answer: how many there are, how much they differ, and the +uncertainty that follows. The evidence is read from the keys the solvers store beside the solve; a record +without them is graded on its residuals alone. + +Everything returned is plain JSON data, because it is shown in a browser. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +from .extrinsics import board_position_spread_m +from .files import FISHEYE, PINHOLE + +EXCELLENT = "excellent" +ACCEPTABLE = "acceptable" +BAD = "bad" +_RANK = {EXCELLENT: 0, ACCEPTABLE: 1, BAD: 2} + +#: Each limit pair is (excellent, acceptable): a number that should be small must be under its limit, one +#: that should be large at or over it. +INTRINSICS_RMS_PX = (0.5, 1.0) +EXTRINSICS_SPREAD_M = (0.005, 0.010) +EXTRINSICS_PNP_RMS_PX = (1.0, 2.0) + +# The evidence limits were chosen on simulated takes, none on hardware: for the pinhole model a 640x480 +# camera with corners found to 0.2 px and head poses to 1 mm and 0.1 degree, for the fisheye model lenses of +# 90 to 135 degrees across with corners found to 0.2 to 0.5 px. Each comment gives what was measured there. + +#: Views an intrinsics solve rests on, per lens model. Pinhole: with 5 or 6 well-tilted views the other +#: limits passed lens models 53 to 315 px off at the picture's corners; from 10 views on, none over 5 px. +#: Fisheye, within the other limits: from 10 views on, 1.6% of 1152 solves were over 5 px off there and the +#: worst 15 px; from 15 on, 0.7% of 850 and 8 px. +INTRINSICS_VIEWS = {PINHOLE: (10, 6), FISHEYE: (15, 10)} +#: Share of the picture the used corners reached. Sound takes reached 0.58 to 1.0; a board kept mid-picture +#: reached 0.10 to 0.33 and left the lens model 240 to 340 px off at the picture's corners (median). +INTRINSICS_COVERAGE = (0.5, 0.25) +#: Tilt spread of the used views. Sound takes gave 0.023 to 0.062; a board tilted 8 degrees or less gave +#: 0.006 to 0.018 with the focal length 1.4% to 14% off (median); copies of one view give 0. Under a fisheye +#: lens, read from the solved poses, sound takes gave 0.07 to 0.14. A well-tilted board held 1 to 2 m away +#: reads 0.017 to 0.027 and is at times refused by this limit alone. It is not lowered for that: at 0.01 a +#: pinhole solve of 30 views 22% off (tilts of 8 degrees, RMS 0.47 px, focal uncertainty 0.44%) would pass. +INTRINSICS_TILT_SPREAD = (0.02, 0.01) +#: Relative uncertainty of the focal length. Sound 30-view takes gave 0.04% to 0.4% and were within 1%; +#: 12 degrees of tilt gave 0.5% to 0.9% and up to 1.7% off; 8 degrees gave 1.1% to 2% and up to 3.7% off. +INTRINSICS_FOCAL_UNCERTAINTY = (0.005, 0.01) +#: How far from the optical axis the used corners were seen, as a share of the angle of the picture's own +#: furthest corner under the solved model. A fisheye model is a guess beyond what was seen. Measured on +#: well-tilted takes: seen to 0.95 or more, none of 387 solves was over 5 px off at the picture's corners; +#: 0.85 to 0.9, 9% of 139 (worst 15 px); 0.8 to 0.85, 39% of 110; 0.75 to 0.8, 68% of 101; under 0.7, over +#: 90%, by hundreds of pixels. The share of the picture reached does not show it: at a coverage of 0.6 to 0.7 +#: the median solve was 50 px off. A picture whose corners lie past what a fisheye model describes is held to +#: the same shares of ``_MODEL_END_DEG``. Measured on 362 solves of such lenses, of four shapes, at the circle +#: 88 degrees off the axis where it crosses the picture: seen to 0.85 or more, none of 162 was over 5 px off +#: (worst 4 px); 0.75 to 0.85, 60% of 159 (worst 18 px); under 0.75, 56% of 41 (worst 25 px). +INTRINSICS_REACH = (0.85, 0.75) +#: How far from its axis either lens model describes a lens at most, in degrees: a ray across the view or +#: behind the camera has no place in either. +_MODEL_END_DEG = 90.0 +#: Uncertainty of the camera's position; it lay between the true error's median and its 90th percentile, so +#: it takes the wander's limits. Of 1536 takes with a still board: under 5 mm, 0.3% were over 10 mm off; from +#: 5 to 10 mm, 6% and none over 19 mm; over 10 mm, 23%. Sound 30-view takes graded excellent in 375 of 391. +EXTRINSICS_UNCERTAINTY_M = (0.005, 0.010) +#: Views a position rests on. Of well-moved takes, 3 to 6 views left 18% to 67% over 10 mm off; 8 views 6% +#: of those the other limits passed and none over 14 mm; 15 views 0.7% and none over 11 mm. +EXTRINSICS_VIEWS = (15, 8) +#: Share of the posed views dropped for disagreeing, over which a position is never excellent. Sound takes +#: dropped over a quarter in 3% of 391; a board moved for 30% to 40% of a take still solved within 8 mm from +#: the rest (151 takes), so drops are said and never refuse on their own. +EXTRINSICS_DROPPED_SHARE = 0.25 + +#: One number that fell short of excellent: its grade, and the clause that names it in a refusal. +_Shortfall = tuple[str, str] + + +def _grade_low(value: float, limits: tuple[float, float]) -> str: + """The grade of a number that should be small; one that is not a number is bad.""" + if value < limits[0]: + return EXCELLENT + return ACCEPTABLE if value < limits[1] else BAD + + +def _grade_high(value: float, limits: tuple[float, float]) -> str: + """The grade of a number that should be large; one that is not a number is bad.""" + if value >= limits[0]: + return EXCELLENT + return ACCEPTABLE if value >= limits[1] else BAD + + +def grade_intrinsics(rms_px: float) -> str: + """The grade of an intrinsics solve's fit, from its reprojection RMS in pixels.""" + return _grade_low(rms_px, INTRINSICS_RMS_PX) + + +def grade_extrinsics(spread_m: float, mean_pnp_rms_px: float) -> str: + """The grade of an extrinsics solve's fit: how far the static board wanders, and how well its poses fit.""" + return worst_grade( + [_grade_low(spread_m, EXTRINSICS_SPREAD_M), _grade_low(mean_pnp_rms_px, EXTRINSICS_PNP_RMS_PX)] + ) + + +def worst_grade(grades: Iterable[str]) -> str | None: + """The worst of some grades; None when there are none.""" + return max(grades, key=_RANK.__getitem__, default=None) + + +def field_of_view_line(seen_deg: float | None, corner_deg: float | None = None) -> str: + """One line saying how far out the lens was seen, for the operator. + + ``seen_deg`` is the largest angle from the optical axis at which a corner the solve used was seen: the + lens model is known out to there and is an extrapolation beyond. ``corner_deg`` is that angle for the + picture's own furthest corner under the solved model, None when the model does not reach it. With no + ``seen_deg`` there was nothing to assess: no intrinsics were solved, or their record says nothing of it. + """ + if seen_deg is None: + return "Field of view: not assessed." + if corner_deg is None: + return ( + f"Corners seen out to {seen_deg:.0f} degrees from the axis; the lens model does not reach the " + "picture's corners." + ) + return ( + f"Corners seen out to {seen_deg:.0f} degrees from the axis; the picture's corners lie at " + f"{corner_deg:.0f} degrees." + ) + + +def _corners_past_model(record: dict[str, Any], model: str) -> bool: + """Whether a record's lens model gives the picture's corners no direction because they lie past all it + can describe, and not because its curve turns short of them. + + A fisheye model describes a lens out to 90 degrees from its axis and no further. A picture whose corners + look 90 degrees or more off the axis (a lens of about 145 degrees across, or a narrower one whose axis + is off the picture's middle) therefore has corners no solve can reach, however far the board was seen. + The record says so by a ``field_limit_deg`` of 90: the curve rises all the way. Under the pinhole model + a curve that rises all the way reaches every pixel, so there the case does not arise. + """ + limit = record.get("field_limit_deg") + return ( + model == FISHEYE + and record.get("max_field_angle_deg") is not None + and record.get("picture_corner_angle_deg") is None + and limit is not None + and limit >= _MODEL_END_DEG + ) + + +def _field_of_view(record: dict[str, Any]) -> str: + """The field-of-view line of an intrinsics record: ``field_of_view_line``, but for a picture whose + corners lie past the lens model, which is said as that.""" + seen = record.get("max_field_angle_deg") + if _corners_past_model(record, record.get("model", PINHOLE)): + return ( + f"Corners seen out to {seen:.0f} degrees from the axis; the picture's corners lie beyond the " + f"{record['field_limit_deg']:.0f} degrees this lens model reaches." + ) + return field_of_view_line(seen, record.get("picture_corner_angle_deg")) + + +def _note(short: list[_Shortfall], feedback: list[str], grade: str, clause: str, advice: str) -> None: + """Take down a number that is not excellent: its grade and clause to ``short``, its advice to ``feedback``.""" + # An excellent number draws no advice and is never a reason. + if grade != EXCELLENT: + short.append((grade, clause)) + feedback.append(advice) + + +def _intrinsics_evidence(record: dict[str, Any], fit: str, short: list[_Shortfall], feedback: list[str]) -> str: + """Judge whether an intrinsics record's views pin the camera; what falls short and refuses the install + goes to ``short``, its advice to ``feedback``. ``fit`` is the grade of the reprojection error. + + Returns the grade of how far out the corners were seen (``_judge_reach``), which is kept apart from + ``short`` because at acceptable it does not refuse. + """ + # A record without the evidence keys, an older file or one built by hand, has none to judge. + if "focal_uncertainty" not in record: + return EXCELLENT + # A record that names no model is of the pinhole one, as a file that names none is. + model = record.get("model", PINHOLE) + # A handful of views can be fitted by many cameras, however well each view is tilted; a fisheye by more. + views, wanted = int(record["num_views_used"]), INTRINSICS_VIEWS[model] + _note( + short, + feedback, + _grade_high(views, wanted), + f"it rests on {views} views where at least {wanted[0]} are needed", + f"The intrinsics rest on only {views} views of the board (excellent is at least {wanted[0]}): " + "record for longer, keeping the board in view.", + ) + # Where no corner was seen the lens model is an extrapolation. + coverage = float(record["corner_coverage"]) + _note( + short, + feedback, + _grade_high(coverage, INTRINSICS_COVERAGE), + f"its corners reached {coverage:.0%} of the picture where at least {INTRINSICS_COVERAGE[0]:.0%} is needed", + f"The board's corners reached only {coverage:.0%} of the picture (excellent is at least " + f"{INTRINSICS_COVERAGE[0]:.0%}): record again pointing the camera so that the board passes through " + "every part of the picture.", + ) + # Views that are alike fit almost any focal length. + spread = float(record["tilt_spread"]) + _note( + short, + feedback, + _grade_high(spread, INTRINSICS_TILT_SPREAD), + "its views hardly differ in tilt", + f"The views of the board hardly differ in tilt (a spread of {spread:.3f}, excellent is at least " + f"{INTRINSICS_TILT_SPREAD[0]:g}): record again tilting the camera up, down and to each side between " + "views.", + ) + # None is a solve its views do not determine at all, which no limit lets through. + uncertainty = record["focal_uncertainty"] + pinned = "is not pinned by the views" if uncertainty is None else f"is pinned only to {uncertainty:.1%}" + _note( + short, + feedback, + BAD if uncertainty is None else _grade_low(float(uncertainty), INTRINSICS_FOCAL_UNCERTAINTY), + f"its focal length {pinned}", + f"The focal length {pinned} (excellent is under {INTRINSICS_FOCAL_UNCERTAINTY[0]:.1%}): record again " + "from nearer and further, tilting the camera between views.", + ) + # Judged last, knowing whether anything else fell short: that decides what its advice says. + return _judge_reach(record, model, fit == EXCELLENT and not short, short, feedback) + + +def _unreached_corners(record: dict[str, Any], model: str, remedy: str) -> str: + """What to tell the operator of a lens model that gives the corners of its own picture no direction.""" + limit = record.get("field_limit_deg") + # Under the fisheye model the curve turned back in the part of the lens the board never showed. + if model == FISHEYE: + return ( + "The lens model does not reach the picture's corners: the board was not seen far enough out to " + f"say how the lens bends there. {remedy}" + ) + # Under the pinhole model there are two causes, and the record cannot tell them apart: a board kept + # short of the corners, and a lens too wide for the model, which no further take mends. + turns = ( + f"past {limit:.0f} degrees from the axis it folds the picture back over itself" + if limit is not None and limit < _MODEL_END_DEG + else "it folds the picture back over itself short of them" + ) + return ( + f"The lens model does not reach the picture's corners: {turns}. If the board was not taken into each " + "of them, record again taking it there. If it was, this lens is too wide for the pinhole model: solve " + "it under the fisheye model." + ) + + +def _judge_reach( + record: dict[str, Any], model: str, sound_otherwise: bool, short: list[_Shortfall], feedback: list[str] +) -> str: + """Judge how far out an intrinsics record's corners were seen against how far its picture goes, and + return its grade; its advice goes to ``feedback``, and what refuses the install to ``short``. + + A model that does not reach its own picture's corners is said of either lens model. How near the corners + were seen to them is held against a fisheye solve alone: that is where it was measured to go wrong + (``INTRINSICS_REACH``), where the pinhole model's measured limit is the share of the picture reached. + A picture whose corners lie past the fisheye model (``_corners_past_model``) is judged against the 90 + degrees the model does describe: that is all of the picture any solve of it can be asked to know. + ``sound_otherwise`` says nothing else fell short, which is when an acceptable reach leaves the solve + installable and the advice says so. + """ + # A record made before the angles were kept has none to judge. + if "max_field_angle_deg" not in record: + return EXCELLENT + seen, corner = record["max_field_angle_deg"], record.get("picture_corner_angle_deg") + remedy = "Record again taking the board into every corner of the picture, partly out of frame if need be." + past = _corners_past_model(record, model) + # Without either angle the solved model does not reach its own picture's corners: its curve turns short + # of them, or it gives the corners it was solved from no direction. No limit lets that through. + if seen is None or (corner is None and not past): + feedback.append(_unreached_corners(record, model, remedy)) + # Under the pinhole model it is said and costs no grade, as the corners' reach does not. + if model != FISHEYE: + return EXCELLENT + short.append((BAD, "its lens model does not reach the picture's corners")) + return BAD + # How far the picture goes, as far as the model can say, and that in words for the two sentences below. + if past: + far = record["field_limit_deg"] + beside, against = ( + f"this lens model reaches {far:.0f}, short of the picture's corners", + "the lens model reaches", + ) + else: + far = corner + beside, against = f"the picture's corners lie at {far:.0f}", "the picture's corners lie at" + graded = _grade_high(seen / far, INTRINSICS_REACH) if model == FISHEYE else EXCELLENT + if graded == EXCELLENT: + return EXCELLENT + said = ( + f"Corners were seen out to {seen:.0f} degrees from the axis and {beside} (excellent is at least " + f"{INTRINSICS_REACH[0]:.0%} of the way)" + ) + # An acceptable reach refuses nothing by itself (see where the install is decided): the operator is told + # what the solve is good for, and not sent to record a take the hardware may not be able to give. + if graded == ACCEPTABLE and sound_otherwise: + feedback.append( + f"{said}. These intrinsics can be installed: the lens model is trustworthy out to the {seen:.0f} " + "degrees that were seen and a guess beyond, and the Rectification tool warns when a corrected " + "picture looks further out than that." + ) + return graded + feedback.append(f"{said}: beyond what was seen the lens model is a guess. {remedy}") + # Only a reach that is bad is a reason for a refusal; an acceptable one beside another shortfall is not. + if graded == BAD: + short.append((BAD, f"its corners were seen out to {seen:.0f} degrees where {against} {far:.0f}")) + return graded + + +def _grade_intrinsics_record(record: dict[str, Any], feedback: list[str]) -> dict[str, Any]: + """An intrinsics record's grade and install decision; advice for what fell short goes to ``feedback``.""" + rms = float(record["rms_calibrate_camera"]) + seen, corner = record.get("max_field_angle_deg"), record.get("picture_corner_angle_deg") + fit = grade_intrinsics(rms) + # The fit first, then whether the views pin it: advice is given in the order it is worth acting on. + if fit != EXCELLENT: + feedback.append( + f"Intrinsics error is {rms:.2f} px (excellent is under {INTRINSICS_RMS_PX[0]:g}): record again " + "moving more slowly so the board stays sharp, tilting the camera and changing its distance to " + "the board." + ) + short: list[_Shortfall] = [] + reach = _intrinsics_evidence(record, fit, short, feedback) + grade = worst_grade([fit, reach, *(grade for grade, _ in short)]) + # A camera matrix shapes everything computed from the recordings made with it, so only the best solve + # replaces the installed one. The one exception is a solve short of excellent in its reach alone, and + # there no worse than acceptable. What ``INTRINSICS_REACH`` was measured on is the error at the picture's + # corners, which a corrected picture of a wide lens does not contain: whether the part of the lens nobody + # saw is used at all is known to the rectification planner, and is judged there. + installable = grade == EXCELLENT or (fit == EXCELLENT and not short and reach == ACCEPTABLE) + # The error is quoted when it is what fell short, and the evidence named when that did. + at = f" at {rms:.2f} px" if fit != EXCELLENT else "" + why = f": {'; '.join(clause for _, clause in short)}" if short else "" + # The rule as it stands for the record's lens model: reach is held against a fisheye solve alone, so a + # pinhole solve has no exception to state. + rule = "Intrinsics are installed only when excellent" + if record.get("model", PINHOLE) == FISHEYE: + rule += ", or acceptable in nothing but how far out the corners were seen" + return { + "grade": grade, + "rms_px": rms, + "field_angle_deg": {"seen": seen, "picture_corner": corner}, + "field_of_view": _field_of_view(record), + "installable": installable, + "not_installable_reason": None if installable else f"{rule}, and this solve is {grade}{at}{why}.", + } + + +def _extrinsics_evidence( + record: dict[str, Any], wander: str, short: list[_Shortfall], feedback: list[str] +) -> None: + """Judge whether an extrinsics record's views pin the camera's position; what falls short goes to + ``short`` and ``feedback``. ``wander`` is the grade of the board's wander.""" + # A record without the evidence keys, an older file or one built by hand, has none to judge. + if "position_uncertainty_m" not in record: + return + # None is a position its views leave loose along some direction, which no limit lets through. + uncertainty = record["position_uncertainty_m"] + excellent_mm, limit_mm = (1000 * limit for limit in EXTRINSICS_UNCERTAINTY_M) + loose = uncertainty is None + pinned = ( + "is not pinned along one direction" if loose else f"is pinned only to about {1000 * uncertainty:.1f} mm" + ) + bound = "" if loose else f" where the limit is {limit_mm:g} mm" + # In whole degrees, as the advice quotes them, so that the cure it names follows from the figures it gives. + most, second = (round(turn) for turn in record["head_turn_spread_deg"][:2]) + # A head that turned mostly one way needs the other turns; one that turned evenly needs more of them. + cure = ( + "nodding and tilting your head as well as turning it" + if most > 2 * second + else "turning your head further in every direction" + ) + graded = BAD if loose else _grade_low(float(uncertainty), EXTRINSICS_UNCERTAINTY_M) + # The uncertainty is the wander seen through how the head turned. Where it grades no worse than the + # wander, the wander's own line says all there is; where it grades worse, the turning is what fell short. + if _RANK[graded] > _RANK[wander]: + _note( + short, + feedback, + graded, + f"the camera's position {pinned}{bound}", + f"The camera's position {pinned} (excellent is under {excellent_mm:g} mm): over the views used " + f"your head turned {most} degrees about one axis and {second} about the next. Record " + f"again, {cure}.", + ) + # Few views leave the board still under many poses: the wander is then a fit, not a check. + views, dropped = int(record["n_views"]), int(record["num_views_outlier_removed"]) + _note( + short, + feedback, + _grade_high(views, EXTRINSICS_VIEWS), + f"it rests on {views} views of the board where at least {EXTRINSICS_VIEWS[1]} are needed", + f"The position rests on only {views} views of the board (excellent is at least {EXTRINSICS_VIEWS[0]}): " + "record again keeping the board in view for the whole take.", + ) + # Drops never refuse on their own: the views kept are judged by everything above. + _note( + short, + feedback, + ACCEPTABLE if dropped > EXTRINSICS_DROPPED_SHARE * (views + dropped) else EXCELLENT, + "views were dropped", + f"{dropped} of {views + dropped} views of the board disagreed with the rest about where it stands and " + "were left out: check that the board stood still and the headset stayed tracked throughout.", + ) + + +def _lag_warning(record: dict[str, Any], feedback: list[str]) -> None: + """Warn, in ``feedback``, when the camera lag a search adopted lies at, or as good as at, the end of the + range it looked in.""" + # None when no search was run; a search recorded without the flag is taken not to have reached an end. + search = record.get("camera_latency_search") or {} + if search.get("at_range_end"): + feedback.append( + f"The camera lag found, {1000 * search['best_s']:.0f} ms, lies at or next to the end of the range " + "searched, so the true lag may be beyond it: solve the take again from the command line with a " + "wider --latency-search-ms." + ) + + +def _tracking_note(record: dict[str, Any], feedback: list[str]) -> None: + """Say, in ``feedback``, when the headset lost its position during the take and what the solve made of + that, with what keeps a headset from losing it.""" + # Absent from a record solved without the take's head track. + tracking = record.get("head_tracking") or {} + if not tracking.get("lost"): + return + lost = f"Head tracking lost its position during the take, first {tracking['first_lost_s']:.0f} s in" + # A position that leapt left stretches nothing ties together; one that did not cost only its own time. + if tracking["stretches"] > 1: + solved = ( + f"{lost}, and found it again somewhere else: the camera's position was solved from the longest " + f"stretch of sound tracking, {tracking['sound_s']:.0f} s." + ) + else: + solved = ( + f"{lost}, for {tracking['lost_s']:.0f} s in all: what was recorded meanwhile was left out, and the " + f"camera's position was solved from the other {tracking['sound_s']:.0f} s." + ) + feedback.append( + f"{solved} Stand about a meter from the board with part of the room in the headset's view: close up, " + "with the board filling its view, the headset loses its position." + ) + + +def _grade_extrinsics_record(record: dict[str, Any], feedback: list[str]) -> dict[str, Any]: + """An extrinsics record's grade and install decision; advice for what fell short goes to ``feedback``.""" + spread = board_position_spread_m(record) + pnp_rms = float(record["mean_pnp_reproj_rms_px"]) + wander = _grade_low(spread, EXTRINSICS_SPREAD_M) + short: list[_Shortfall] = [] + # The residuals first: how still the board stands, and how well its poses fit the picture. + _note( + short, + feedback, + wander, + f"the board wanders {spread * 1000:.1f} mm where the limit is {EXTRINSICS_SPREAD_M[1] * 1000:g} mm", + f"The board wanders {spread * 1000:.1f} mm under the solved camera pose (excellent is under " + f"{EXTRINSICS_SPREAD_M[0] * 1000:g}): record again with the board perfectly still, moving your head " + "slowly.", + ) + _note( + short, + feedback, + _grade_low(pnp_rms, EXTRINSICS_PNP_RMS_PX), + f"the board's poses fit the picture to {pnp_rms:.2f} px where the limit is " + f"{EXTRINSICS_PNP_RMS_PX[1]:g} px", + f"The board's poses fit the picture to {pnp_rms:.2f} px (excellent is under " + f"{EXTRINSICS_PNP_RMS_PX[0]:g}): fix the board to something rigid and move your head more slowly " + "so the frames stay sharp.", + ) + # Then whether the views pin the position, and last what the lag search and the head track have to say + # of themselves. + _extrinsics_evidence(record, wander, short, feedback) + _lag_warning(record, feedback) + _tracking_note(record, feedback) + grade = worst_grade([EXCELLENT, *(grade for grade, _ in short)]) + installable = grade != BAD + # Only what crossed its limit is named: a number that is merely not excellent is not why it is refused. + refused = "; ".join(clause for graded, clause in short if graded == BAD) + return { + "grade": grade, + "board_position_spread_m": spread, + "mean_pnp_reproj_rms_px": pnp_rms, + "installable": installable, + "not_installable_reason": None + if installable + else f"Extrinsics graded {BAD} are not installed: {refused}.", + } + + +def grade_calibration(intrinsics: dict[str, Any] | None, extrinsics: dict[str, Any] | None) -> dict[str, Any]: + """Grade what a calibration run solved; either record may be None when that part was not solved. + + Returns ``overall`` (the worse of the parts, None when nothing was solved), a part for ``intrinsics`` and + for ``extrinsics`` (None when not solved) with its grade, its numbers, ``installable`` and + ``not_installable_reason``, and ``feedback``: one sentence of advice per number that is not excellent. + A part's grade is the worst of its residuals and of the evidence its record carries (see the module). + Extrinsics solved in the same run as intrinsics are installed with them or not at all (``with_intrinsics``). + """ + feedback: list[str] = [] + parts = { + "intrinsics": None if intrinsics is None else _grade_intrinsics_record(intrinsics, feedback), + "extrinsics": None if extrinsics is None else _grade_extrinsics_record(extrinsics, feedback), + } + solved_together = parts["intrinsics"] is not None and parts["extrinsics"] is not None + if solved_together: + _pair(parts["intrinsics"], parts["extrinsics"]) + overall = worst_grade(part["grade"] for part in parts.values() if part is not None) + return {"overall": overall, **parts, "feedback": feedback} + + +def _pair(intrinsics: dict[str, Any], extrinsics: dict[str, Any]) -> None: + """Tie the install decision of extrinsics to the intrinsics they were solved with in the same run. + + A camera's place on the headset is only right for the camera matrix it was solved under, so it is never + installed over a different one: ``with_intrinsics`` tells an installer to write both, and when those + intrinsics may not be installed the extrinsics may not be either. + """ + extrinsics["with_intrinsics"] = True + if extrinsics["installable"] and not intrinsics["installable"]: + extrinsics["installable"] = False + extrinsics["not_installable_reason"] = ( + "The camera's position was solved with this run's intrinsics, which are not good enough to " + "install, and it would not fit the intrinsics the station has." + ) diff --git a/examples/egocap/recording/egocap/calibration/guidance.py b/examples/egocap/recording/egocap/calibration/guidance.py new file mode 100644 index 0000000000..9dc88e269a --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/guidance.py @@ -0,0 +1,956 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Live feedback while a calibration take is being recorded. + +The guide is fed frames as they arrive and says what the operator should do next: show the board, slow down, +reach a corner of the picture, tilt the camera, move the head. It only advises. The solve runs later from the +recorded take and picks its own frames, so nothing the guide counts is used as data. + +"Ready" means the take holds what the solve and its grade ask for, as far as that shows while recording: +measured by their functions against their limits, with a margin, from frames the solve could use. How well +the views will fit, and how tightly they pin the focal length, only the solve can say. Through a fisheye +lens that goes for the variety of tilt too: the corners alone do not show tilt there, so it is asked for and +not measured. How far out the lens was seen, which a fisheye solve is graded on, is measured in the picture, +for want of the lens: see ``_CORNER_REACH``. + +A headset that loses its own position goes on sending head poses, and the solve leaves out what it recorded +then. The guide reads the head poses it is given as the solve reads the take's, says when the position is +lost, and counts head motion only from the sound tracking that will be solved from. A lost position shows +in every head pose that arrived, not in the one that came with each picture: a guide given only those says +when a position stands still, and of one that creeps along with the turning it says nothing. +""" + +from __future__ import annotations + +import dataclasses +import math +from collections import deque +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation + +from .board import BoardDetector, BoardSpec, BoardView, Detection, as_gray, sharpness +from .camera_pipeline import DEFAULT_PICKS +from .extrinsics import ( + MIN_HEAD_POSITION_STD_M, + MIN_HEAD_ROTATION_FROBENIUS, + MIN_HEAD_SECOND_TURN_DEG, + MIN_HEAD_TURN_DEG, + TRACK_FROZEN_M_PER_DEG, + TRACK_WINDOW_S, + HeadTrackReader, + head_turn_spread_deg, + position_uncertainty_m, +) +from .files import FISHEYE, PINHOLE +from .grading import ( + EXTRINSICS_SPREAD_M, + EXTRINSICS_UNCERTAINTY_M, + EXTRINSICS_VIEWS, + INTRINSICS_COVERAGE, + INTRINSICS_TILT_SPREAD, + INTRINSICS_VIEWS, +) +from .intrinsics import ( + COVERAGE_GRID, + MIN_CORNERS, + PICTURE_CORNERS, + corner_coverage, + corner_reach, + tilt_spread, + usable_for, +) + +#: Share of the board's corners a frame must show to count as a view, and the fewest that share may mean. +_GOOD_CORNER_SHARE = 0.2 +_MIN_GOOD_CORNERS = 6 +#: What the guide asks for before it says ready, as a multiple of what the solve or its grade stops at. The +#: solve picks other frames than the guide counted, and the margin is what that difference may cost. +_SOLVE_MARGIN = 1.5 +#: How far into each corner of the picture a fisheye take must show a corner of the board, as a share of the +#: way from the picture's middle (``intrinsics.corner_reach``). A fisheye solve is graded on the angle from +#: the lens's axis at which its furthest corner was seen, against that of the picture's furthest corner +#: (``grading.INTRINSICS_REACH``); the guide has no lens to measure angles with, and pixels stand in for +#: them. It asks every corner, because it cannot tell which lies furthest from the axis, and the solve keeps +#: the frame that reaches furthest into each. Measured on 1052 synthetic lenses of three shapes (equal-angle, +#: equal-area, stereographic), 90 to 135 degrees across, their axis up to 4% of the picture off its middle: +#: a corner seen this share of the way into the picture corner furthest from the axis is at 0.75 of that +#: corner's angle or more, which installs, for all but 2 of them, and at 0.85 or more, which is excellent, +#: for 30%; of 148 orthographic lenses, which squeeze their rim hardest, a third reach 0.75. And on 128 +#: synthetic takes of one lens that dip the board into the corners to several depths, solved from the frames +#: the pipeline picks: asked this, the 65 takes that had it all installed and 57 were excellent, and of the +#: 63 that had not one was excellent; asked 0.85, 21 excellent takes had not. The detector, on rendered +#: frames of takes that carry the board to the rim, saw corners 0.84 to 0.90 of the way into each corner. +_CORNER_REACH = 0.82 +#: Pixels added around the detected corners when measuring the board's sharpness, to take in its outer squares. +_REGION_PAD_PX = 8 +#: Sharpness is compared between frames in which the board's squares appear about the same size: how many +#: such bands a doubling of that size spans. Do not widen the comparison beyond the next band: a board at +#: under twice the size, rolled, read under 0.4 times as sharp through the same simulated lens. +_SIZE_BANDS_PER_OCTAVE = 3 +#: For how long a frame goes on setting the bar for its band, counted in time the board was watched at that +#: size. Short of a take, so that one freak frame, or the light the take began in, does not hold every later +#: frame to its standard. A smear that outlasts it at one size is let through for that: its readings are the +#: freak frame's readings, one sharp frame and then softer ones, and nothing in them tells the two apart. +_SHARP_MEMORY_S = 30.0 +#: A longer wait than this between two frames at a size means the camera was looking at another, and what +#: is remembered of the size does not age meanwhile: nothing was learned of it. +_AWAY_GAP_S = 2.0 +#: What a guide given one head pose per picture calls a lost position, in meters per degree, and the longest +#: step between two such poses it reads across, in seconds. Between pictures a head turning about its neck +#: moves its headset by little more than a lost position creeps, so only one that stands still is called. +_COARSE_LOST_M_PER_DEG = 0.00025 +_COARSE_STEP_S = 1.0 +#: How many coverage cells across and down make one cell of the density grid. A coverage cell is covered by +#: one passing corner; a density cell, four of them, is a region of the picture that views can be counted in. +_DENSITY_CELLS = 2 +#: How many counted views must have had a corner in a density cell for it to count as sampled. +_DENSITY_SAMPLES = 2 +#: A frame is a new view once the corners it shares with the last counted view moved by this share of the +#: board's extent in the picture; "the corners" being those that moved furthest, up to this percentile. +_MIN_VIEW_SHIFT = 0.01 +_SHIFT_PERCENTILE = 90.0 +#: How many of the latest counted views and head poses are kept to judge the take by: minutes of either, +#: where a take lasts about one. +_VIEW_MEMORY = 512 +_POSE_MEMORY = 4096 +#: Tint laid over covered cells in a preview (BGR) and how strongly, and the colour of drawn corners. +_TINT = (80, 200, 80) +_TINT_STRENGTH = 0.25 +_CORNER_COLOUR = (0, 255, 0) + +#: The hint given while no head pose comes with the frames. A caller that knows why none does (and says so +#: itself) can recognise this one and leave it out. +HEAD_TRACKING_HINT = "Head tracking is not arriving: check the headset is on and tracked." + +#: A board that is not found, or found by a few corners only, may be out of the picture or smeared past +#: reading. The frame does not say which, so these name the remedy for both. +_NOT_FOUND_HINT = "The board is not found in the picture: point the camera at it, and move slowly." +_TOO_LITTLE_HINT = "Too little of the board is readable for this view to count: show more of it, and move slowly." +_SMEARED_HINT = "The picture is smeared: move more slowly." +_SAME_VIEW_HINT = "This view is the same as the last one counted: move or tilt the camera." +_TURN_MORE_HINT = "Turn and tilt your head more, in every direction." +#: Said first while the headset's position is lost: nothing recorded meanwhile counts for the camera's place. +_LOST_HINT = ( + "The headset has lost its position: look around the room until it finds it again, then go on from about a " + "meter back from the board, with part of the room in view." +) +#: Where to stand in a take the camera's position is solved from. Close up, with the board filling its view, +#: a headset loses its position. +_STAND_HINT = "from about a meter away, with part of the room in the headset's view" + + +@dataclass(frozen=True) +class GuideStatus: + """What the guide knows after one frame. Every field is plain JSON data.""" + + #: The image size corner positions are given in, as (width, height). + image_size_wh: tuple[int, int] + #: Whether the board is seen in this frame, how many of its corners, and how many the board has in all. + board_visible: bool + corners: int + board_corners: int + #: Pixel position ``[x, y]`` of each corner seen, for an overlay. + corner_points: list[list[float]] + #: Sharpness of the board in this frame (of the whole frame when no board is seen), and whether the frame + #: is blurred: the board far less sharp than in the sharpest recent frame at its size. Never True of a + #: frame in which the board is not found. + sharpness: float + blurred: bool + #: Distinct good views collected so far, and how many make a take worth solving. + views: int + views_needed: int + #: ``columns`` and ``rows`` of the grid over the image; ``cells[row][column]`` True once that cell is covered + #: (row 0 at the top), which ``CaptureGuide`` says when it is; ``fraction`` of cells covered; ``corners``, + #: the picture's four corners by name, True once the board was taken far enough into each (which + #: ``CaptureGuide`` says too); ``corner_reach``, by the same names, how far into each a corner of the + #: board was seen, as a share of the way from the picture's middle; ``edge_fraction``, the share + #: covered of the border cells between the corner cells; ``density``, how often each part of the + #: picture was sampled: ``columns`` and ``rows`` of a coarser grid, ``counts[row][column]`` the number of + #: counted views that had a corner in that cell, and ``fraction_twice`` the share of its cells that two + #: views or more did; and ``asked``, what the take's readiness holds ``fraction``, ``edge_fraction``, + #: ``corners`` and ``corner_reach`` to, each under its own name and None where it asks nothing. + coverage: dict[str, Any] + #: When the intrinsics are solved, what the counted views amount to as the solve's grade reads its own: + #: ``corner_coverage``, ``tilt_spread`` (None under the fisheye model, where the corners alone do not + #: show it), ``enough``, and ``asked``: at least how much of each of the two figures the guide asks + #: for. Otherwise None. + evidence: dict[str, Any] | None + #: When head motion is needed: ``tracking`` (a head pose came with this frame) and, over the frames that + #: showed the board in the sound head tracking the position can be solved from, ``position_spread_m``, + #: ``rotation_deg`` (the largest turn from the first pose), ``turn_spread_deg`` (about the axis turned + #: most about, and the next), ``uncertainty_per_wander`` (of the camera's position, as a multiple of the + #: board's wander; None while unpinned) and ``enough``. ``asked`` holds what the guide asks of each of + #: those figures, under the same names: at least that much of the first three, at most that much of the + #: last. ``health`` says how the head tracking itself is doing: ``state`` ("no_pose" when no head pose + #: came with this frame, "lost" while the headset's position is not tracked, "still" when the head turned + #: too little lately to tell, "tracked" otherwise), ``mm_per_degree`` (how far the head's position moved + #: for each degree it turned over the last ``window_s`` seconds; None when it turned too little to tell), + #: ``lost_below_mm_per_degree`` (under which that figure counts as lost), ``dense`` (whether the figure + #: is taken over every head pose that arrived, or over the one that came with each picture, which tells + #: less), ``lost_seconds_ago`` (how long ago the position was last lost: 0 while it is, None when it + #: never was), ``losses`` (how many times it was lost), ``stretches`` (how many stretches the tracking + #: is split into: more than one once the position leapt into another frame), ``sound_seconds`` (seconds + #: of sound tracking with the board in view, in the longest stretch) and ``sound_seconds_wanted``. + #: Otherwise None. + head: dict[str, Any] | None + #: Whether enough has been captured to stop the take. + ready: bool + #: What to do next, most useful first. + hints: list[str] + + def to_record(self) -> dict[str, Any]: + """The status as a JSON-serialisable dict.""" + return {**dataclasses.asdict(self), "image_size_wh": list(self.image_size_wh)} + + +def _usable_pose(head_pose: Any) -> np.ndarray | None: + """A head pose as a 4x4 array, or None for what is no pose: nothing, one with holes in it, or one whose + turn is no rotation.""" + if head_pose is None: + return None + pose = np.asarray(head_pose, dtype=np.float64).reshape(4, 4) + usable = bool(np.all(np.isfinite(pose)) and np.linalg.det(pose[:3, :3]) > 0.0) + return pose if usable else None + + +def _listed(names: list[str]) -> str: + """Names joined as prose: "a", "a and b", "a, b and c".""" + return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}" + + +def _holds(was: bool, share: float) -> bool: + """Whether a measure counts as enough, given as a share of what the guide asks for. + + It gets there by reaching what is asked, and stays there while it holds what the solve itself stops at, + one margin lower: a measure that shrinks while the operator pauses must not take "ready" back from a take + that lost nothing the solve needs. + """ + return share >= 1.0 or (was and share >= 1.0 / _SOLVE_MARGIN) + + +def _spread_evenly(items: Sequence[Any], count: int) -> list[Any]: + """At most ``count`` of some items, spread evenly over them in order: how the solve picks from a take.""" + places = np.linspace(0, len(items) - 1, min(len(items), count)).round().astype(int) + return [items[place] for place in places] + + +def _square_size_px(detection: Detection, corner_grid: tuple[int, int]) -> float | None: + """How large a square of the board appears in a frame, in pixels; None when no two corners found are + neighbours on the board. + + The median distance between neighbouring corners, along the board's rows and along its columns, and the + larger of the two: a board seen at a slant is squeezed along one, and its sharpness follows the other. + """ + columns, rows = corner_grid + # Corner ids run along the board's rows, so laid out on its grid, neighbours are one step apart. + grid = np.full((rows * columns, 2), np.nan) + grid[detection.ids] = detection.corners + grid = grid.reshape(rows, columns, 2) + sizes = [] + for axis in (0, 1): + steps = np.linalg.norm(np.diff(grid, axis=axis), axis=-1) + steps = steps[np.isfinite(steps)] + # A single line of corners has neighbours along one direction only. + if steps.size: + sizes.append(float(np.median(steps))) + return max(sizes, default=None) + + +@dataclass +class _SizeMemory: + """How sharp the board has looked at one size, for as long as that is remembered.""" + + #: Seconds the board has been watched at this size, and the time it was last seen at it. + watched_s: float = 0.0 + last_seen: float | None = None + #: The frames still remembered, as (``watched_s`` when seen, sharpness), the sharpest first. + frames: deque[tuple[float, float]] = dataclasses.field(default_factory=deque) + + +class CaptureGuide: + """Follows a calibration take frame by frame and tells the operator how it is going. + + A view is counted when a frame shows at least ``good_corners`` corners spanning the board's plane, is not + blurred, comes at least ``min_view_gap_s`` after the last counted one, and differs from it. A cell of the + grid over the image is covered once a corner was seen in it in a sharp frame the solve could pick. A + corner of the picture is reached, under the pinhole model, once its cell of the grid is covered; under + the fisheye model, whose solve is graded on how far out it saw the board, once such a frame showed a + corner of the board ``_CORNER_REACH`` of the way into it. Head motion is counted from the frames that + show the board, the only ones the solve pairs a head pose with. + + The take is ready when ``views_needed`` views are in; when (``needs_coverage``) the grid is covered, the + picture's four corners are reached and the counted views pass the intrinsics grade's limits on coverage + and on tilt; and when (``needs_head_motion``) the head has moved, and turned far enough about two axes + to pin the camera's position as that grade asks, within one stretch of sound head tracking long enough + to hold the views that grade wants (see the module). Under the fisheye model the tilt is not measured + (see the module): the hints ask for it all the same. + + A frame is blurred when the board in it is under ``blur_ratio`` as sharp as in the sharpest frame + remembered that showed its squares at about the same size: of its own size band and of the band next to + it, each remembering ``_SHARP_MEMORY_S`` seconds of watching. Sharpness is ``board.sharpness`` over the + part of the frame the board occupies; judging it against the take's own frames allows for a lens that + is never pixel-sharp. A frame in which the board is not found is not judged: the hint for it covers a + board out of the picture and one smeared past reading alike. Frames are compared by the size of the + board's squares and not by where in the picture the board is: a lens much softer at its rim than at its + centre could have every frame at the rim read as blurred, and its corners never reached. That has not + been tried on a lens. + """ + + def __init__( + self, + spec: BoardSpec, + image_size_wh: tuple[int, int], + *, + needs_head_motion: bool, + needs_coverage: bool = True, + model: str = PINHOLE, + grid: tuple[int, int] = COVERAGE_GRID, + good_corners: int | None = None, + min_view_gap_s: float = 1.0, + views_needed: int | None = None, + min_coverage: float = 0.8, + blur_ratio: float = 0.5, + ) -> None: + """Start a guide for one take. + + ``image_size_wh`` is the camera's full image size; frames may be fed at a smaller size of the same + shape and are scaled to it. ``grid`` is (columns, rows). ``needs_coverage`` is False when the + intrinsics are not being solved, which is the only thing the corners of the picture and the variety + of the views matter for. ``model`` is the lens model they are solved under (``files.PINHOLE`` or + ``files.FISHEYE``), which says what a frame must show and how many views the grade wants. + ``views_needed`` is the caller's to give; by default it is as many as the solve picks. + """ + # The edges are the border cells between the corner cells; a narrower grid has none. + if min(grid) < 3: + raise ValueError("the coverage grid needs at least 3 columns and 3 rows") + # Chosen by the caller's code, not typed by an operator, so a wrong one is a plain error. + if model not in MIN_CORNERS: + raise ValueError(f"model must be {PINHOLE} or {FISHEYE}") + self._detector = BoardDetector(spec) + self._corner_grid = (spec.squares[0] - 1, spec.squares[1] - 1) + self._size = (int(image_size_wh[0]), int(image_size_wh[1])) + self._needs_head_motion = needs_head_motion + self._needs_coverage = needs_coverage + self._model = model + # A fisheye picture is no flat picture of the board, and its corners alone do not show tilt. + self._measures_tilt = model != FISHEYE + # Capped at the whole board, which is all a small one can ever show. + share = max(_MIN_GOOD_CORNERS, math.ceil(_GOOD_CORNER_SHARE * spec.max_corners)) + self._good_corners = min(spec.max_corners, share) if good_corners is None else good_corners + self._min_view_gap_s = min_view_gap_s + # Never fewer than the grade wants under a solve it calls excellent, of either part. + enough_views = max(DEFAULT_PICKS, INTRINSICS_VIEWS[model][0], EXTRINSICS_VIEWS[0]) + self._views_needed = enough_views if views_needed is None else views_needed + self._min_coverage = min_coverage + self._blur_ratio = blur_ratio + self._covered = np.zeros((grid[1], grid[0]), dtype=bool) + # How far into each corner of the picture the board was seen, in the order of ``PICTURE_CORNERS``. + self._corner_reach = np.zeros(len(PICTURE_CORNERS)) + # How sharp the board has looked, by size band. + self._sharp_by_size: dict[int, _SizeMemory] = {} + # How many counted views had a corner in each cell of the density grid. + self._density = np.zeros( + (math.ceil(grid[1] / _DENSITY_CELLS), math.ceil(grid[0] / _DENSITY_CELLS)), dtype=int + ) + self._board_corners = spec.max_corners + self._views = 0 + self._last_view_time = -math.inf + self._counted: deque[BoardView] = deque(maxlen=_VIEW_MEMORY) + # What reads the head track, and whether it is given every head pose that arrives. Until a caller + # hands those over it gets the pose of each picture, and is held to what that can tell. + self._dense = False + self._reader = HeadTrackReader(lost_below_m_per_deg=_COARSE_LOST_M_PER_DEG, longest_step_s=_COARSE_STEP_S) + # The head pose that came with each picture, with its time and whether the picture showed the board. + self._head_track: deque[tuple[float, np.ndarray, bool]] = deque(maxlen=_POSE_MEMORY) + # The position is solved from one stretch of sound tracking, which must be long enough to hold the + # views its grade wants, a gap apart; or the views this take is asked for, when those are fewer. + self._sound_seconds_wanted = _SOLVE_MARGIN * min(EXTRINSICS_VIEWS[0], self._views_needed) * min_view_gap_s + # What the counted views amount to, kept between views: it changes only when one is counted. + self._corner_coverage = self._tilt_spread = 0.0 + # Verdicts on measures that can shrink again, each kept as ``_holds`` says. + self._reaching = self._tilted = self._moved = self._turned = self._pinned = False + # The solve's floor on turning from the first pose is a Frobenius distance; this is it as an angle. + self._turn_floor_deg = math.degrees(2.0 * math.asin(MIN_HEAD_ROTATION_FROBENIUS / (2.0 * math.sqrt(2.0)))) + + def _judge_sharpness( + self, gray: np.ndarray, detection: Detection | None, now_seconds: float + ) -> tuple[float, bool]: + """A frame's sharpness and whether it is blurred. + + Only a board that is found is judged. A frame without it is as soft where the board left the picture + as where a smear hid it, and sensor noise makes the whole frame read sharper again as the board's edges + fade. + """ + # The whole frame's sharpness is reported for want of the board's. + if detection is None: + return sharpness(gray), False + # The box around the corners found, widened to take in the squares at the board's rim. + height, width = gray.shape[:2] + low = np.floor(detection.corners.min(axis=0)).astype(int) - _REGION_PAD_PX + high = np.ceil(detection.corners.max(axis=0)).astype(int) + _REGION_PAD_PX + x0, x1 = np.clip([low[0], high[0]], 0, width) + y0, y1 = np.clip([low[1], high[1]], 0, height) + value = sharpness(gray[y0:y1, x0:x1]) + size = _square_size_px(detection, self._corner_grid) + # Corners that are not neighbours do not tell the size of the squares, so not which frames to judge + # this one against either. + if size is None: + return value, False + # A square under a pixel is never detected; the floor only keeps the logarithm defined. + place = _SIZE_BANDS_PER_OCTAVE * math.log2(max(size, 1.0)) + band = math.floor(place) + memory = self._watched(band, now_seconds) + # The band next to this one on the side the size is nearer holds frames as like this one as its own + # band's far end does. Without it a smear a hair across a band's edge from the sharp frame of the + # same view would open an empty band and go unjudged. + beside = self._sharp_by_size.get(band + 1 if place - band >= 0.5 else band - 1) + bars = [held.frames[0][1] for held in (memory, beside) if held is not None and held.frames] + # Judged before this frame joins its band, so that no frame is measured against itself; the first + # frame at a size and the sizes beside it has nothing to fall short of. + blurred = bool(bars) and value < self._blur_ratio * max(bars) + remembered = memory.frames + # A glimpse of a few corners is a patch too small to say how sharp the board can look. + if len(detection.ids) >= self._good_corners: + # A remembered frame that is older and no sharper can never be the sharpest again. With those + # dropped the sharpest is the first and the oldest, and the next is what the bar falls back to + # when that one is forgotten: a blurred frame is remembered for then, and sets no bar before. + while remembered and remembered[-1][1] <= value: + remembered.pop() + remembered.append((memory.watched_s, value)) + return value, blurred + + def _watched(self, band: int, now_seconds: float) -> _SizeMemory: + """What is remembered of a size band, once this frame's time at it is counted and what is older than + ``_SHARP_MEMORY_S`` of watching is forgotten.""" + memory = self._sharp_by_size.setdefault(band, _SizeMemory()) + # Time away at another size is not time spent learning how sharp this one can look: a camera that + # comes back to a size after half a minute elsewhere is still held to what it showed there. + if memory.last_seen is not None: + memory.watched_s += min(now_seconds - memory.last_seen, _AWAY_GAP_S) + memory.last_seen = now_seconds + # Forgotten by time watched, not by how many frames came since: a smear brings as many as it lasts. + while memory.frames and memory.watched_s - memory.frames[0][0] > _SHARP_MEMORY_S: + memory.frames.popleft() + return memory + + def _mark_covered(self, points: np.ndarray) -> None: + """Record which grid cells the corners of this frame fall in.""" + rows, columns = self._covered.shape + column = np.clip((points[:, 0] / self._size[0] * columns).astype(int), 0, columns - 1) + row = np.clip((points[:, 1] / self._size[1] * rows).astype(int), 0, rows - 1) + self._covered[row, column] = True + + def _is_new_view(self, view: BoardView) -> bool: + """Whether a view differs from the last one counted: the corners both show have moved.""" + # The first view has nothing to be the same as. + if not self._counted: + return True + last = self._counted[-1] + _, here, there = np.intersect1d(view.ids, last.ids, return_indices=True) + # A board seen by other corners altogether has plainly moved. + if not here.size: + return True + shift = np.linalg.norm(view.image_points[here] - last.image_points[there], axis=1) + # Against the board's extent in the picture, so that the same motion counts near and far. Tilting + # in place moves the corners at the board's rim and hardly any other, so the rim is what is asked; + # short of the very furthest corner, which one misread corner would be. + return bool( + np.percentile(shift, _SHIFT_PERCENTILE) >= _MIN_VIEW_SHIFT * np.ptp(view.image_points, axis=0).max() + ) + + def _credit_view(self, view: BoardView, whole: bool, blurred: bool, now_seconds: float) -> str | None: + """Count a frame as a view when it is one. Returns what to tell the operator when it is not, where + no other hint says so: None for a counted view, a blurred frame and one too soon after the last.""" + # The hint that the picture is smeared says all there is to say of a blurred frame. + if blurred: + return None + # Too few corners for a view, or all of them along one line. + if not whole: + return _TOO_LITTLE_HINT + # Frames a moment apart show the same view; only ones spaced out add something to solve from. + if now_seconds - self._last_view_time < self._min_view_gap_s: + return None + # A camera held still shows one view however long it looks. + if not self._is_new_view(view): + return _SAME_VIEW_HINT + self._views += 1 + self._last_view_time = now_seconds + self._counted.append(view) + # One sample for each part of the picture the view has a corner in, however many corners. + rows, columns = self._density.shape + column = np.clip((view.image_points[:, 0] / self._size[0] * columns).astype(int), 0, columns - 1) + row = np.clip((view.image_points[:, 1] / self._size[1] * rows).astype(int), 0, rows - 1) + sampled = np.zeros_like(self._density, dtype=bool) + sampled[row, column] = True + self._density += sampled + # What the views amount to matters to the intrinsics alone. It is measured over as many views as + # the solve picks, spread over the take as its picks are. + if self._needs_coverage: + picked = _spread_evenly(self._counted, DEFAULT_PICKS) + self._corner_coverage = corner_coverage(picked, self._size) + if self._measures_tilt: + self._tilt_spread = tilt_spread(picked) + return None + + def _evidence_record(self) -> dict[str, Any]: + """What the counted views amount to as the solve's grade reads its own views, and whether that is + enough for intrinsics that may be installed.""" + # Intrinsics are installed only when excellent, so that is the limit asked of each. Both figures can + # come down again, as the views picked from a longer take are spread wider over it. + asked = _SOLVE_MARGIN * INTRINSICS_COVERAGE[0] + self._reaching = _holds(self._reaching, self._corner_coverage / asked) + # Where tilt cannot be measured it is not held against the take: the solve's grade judges it. + if not self._measures_tilt: + return { + "corner_coverage": self._corner_coverage, + "tilt_spread": None, + "enough": self._reaching, + "asked": {"corner_coverage": asked, "tilt_spread": None}, + } + tilt_asked = _SOLVE_MARGIN * INTRINSICS_TILT_SPREAD[0] + self._tilted = _holds(self._tilted, self._tilt_spread / tilt_asked) + return { + "corner_coverage": self._corner_coverage, + "tilt_spread": self._tilt_spread, + "enough": self._reaching and self._tilted, + # What each figure is held to, from below; None for one that is not held to anything. + "asked": {"corner_coverage": asked, "tilt_spread": tilt_asked}, + } + + def _read_head_track( + self, + pose: np.ndarray | None, + now_seconds: float, + head_track: Sequence[tuple[float, np.ndarray]] | None, + ) -> None: + """Hand the reader of the head track what arrived: every head pose since the last picture when the + caller gives those, the picture's own pose otherwise.""" + if head_track is None: + # A caller that hands over every pose does so with each picture; one that never did gives this one. + if not self._dense and pose is not None: + self._reader.add([now_seconds], [pose]) + return + if not self._dense: + # What was read from one pose per picture was held to other limits: the reading starts again. + self._dense = True + self._reader = HeadTrackReader() + self._head_track.clear() + arrived = [(seconds, _usable_pose(given)) for seconds, given in head_track] + arrived = [(seconds, given) for seconds, given in arrived if given is not None] + if arrived: + self._reader.add([seconds for seconds, _ in arrived], [given for _, given in arrived]) + + def _sound_stretch(self, times: np.ndarray, shown: np.ndarray) -> tuple[np.ndarray, float]: + """Which of the pictures' head poses the position can be solved from (those of the longest stretch of + sound tracking that came with the board in view), and how many seconds with the board in view that + stretch holds.""" + stretch = self._reader.stretches(times) + # Time counts between two poses of one stretch when the later one's frame showed the board; a long + # wait between two poses counts for no more than a look away would. + counts = (stretch[1:] >= 0) & (stretch[1:] == stretch[:-1]) & shown[1:] + waits = np.minimum(np.diff(times), _AWAY_GAP_S) + seconds = np.bincount(stretch[1:][counts], waits[counts], int(stretch.max(initial=0)) + 1) + # The longest; of stretches that are as long, as two that hold one pose each are, the later. + longest = len(seconds) - 1 - int(np.argmax(seconds[::-1])) + return (stretch == longest) & shown, float(seconds[longest]) + + def _health_record(self, tracking: bool, now_seconds: float) -> dict[str, Any]: + """How the head tracking itself is doing, as the reader of the head track has it; without the + seconds of sound tracking, which the caller adds.""" + per_degree = self._reader.reading() + limit = TRACK_FROZEN_M_PER_DEG if self._dense else _COARSE_LOST_M_PER_DEG + unusable = self._reader.unusable_spans + # Lost over the window up to now, or within a span the reader has found. It finds a span a moment + # after the window tells of it, so a window that tells of one the reader has not yet is a loss more. + below = per_degree is not None and per_degree < limit + lost = below or bool(unusable and now_seconds <= unusable[-1][1]) + ahead = below and not (unusable and unusable[-1][1] >= now_seconds - TRACK_WINDOW_S) + if not tracking: + state = "no_pose" + elif lost: + state = "lost" + else: + state = "still" if per_degree is None else "tracked" + ago = None + if lost: + ago = 0.0 + elif unusable: + ago = float(now_seconds - unusable[-1][1]) + return { + "state": state, + "mm_per_degree": None if per_degree is None else 1000.0 * per_degree, + "window_s": TRACK_WINDOW_S, + "lost_seconds_ago": ago, + "losses": len(unusable) + int(ahead), + # Whether the figure is taken over every head pose that arrived, or over one for each picture, + # and what it must stay above not to count as lost. + "dense": self._dense, + "lost_below_mm_per_degree": 1000.0 * limit, + "stretches": self._reader.stretch_count, + } + + def _head_record( + self, + head_pose: np.ndarray | None, + board_in_view: bool, + now_seconds: float, + head_track: Sequence[tuple[float, np.ndarray]] | None, + ) -> dict[str, Any]: + """Take in the head pose that came with a frame, and the head poses that arrived since the last when + given; how the head tracking is doing, how far the head has moved and turned in the sound tracking the + position can be solved from, and whether that is enough.""" + # Tracking that drops out sends nothing, or a pose with holes in it, or one whose turn is no + # rotation; none of them is motion. + pose = _usable_pose(head_pose) + tracking = pose is not None + self._read_head_track(pose, now_seconds, head_track) + # Kept in the order of their times: a pose given for a moment no later than the last one is left out. + if tracking and (not self._head_track or now_seconds > self._head_track[-1][0]): + self._head_track.append((now_seconds, pose, board_in_view)) + times = np.array([time for time, _, _ in self._head_track]) + track = np.array([pose for _, pose, _ in self._head_track]).reshape(-1, 4, 4) + shown = np.array([seen for _, _, seen in self._head_track], dtype=bool) + # The solve pairs head poses with views of the board, so motion made while the board is out of + # view gives it nothing: the walk up to the board must not pass for moving around it. Nor does + # motion outside the sound tracking the position is solved from. + counted, sound_s = self._sound_stretch(times, shown) + spread = turn = most = second = 0.0 + uncertainty = None + if counted.any(): + # Moving, and turning from the first pose, as the solve judges them over a whole take. + poses = track[counted] + spread = float(poses[:, :3, 3].std(axis=0).max()) + turn = float(np.degrees(Rotation.from_matrix(poses[0, :3, :3].T @ poses[:, :3, :3]).magnitude().max())) + # How the turning pins the camera, as the solve judges it over its views: over as many poses as + # it picks views, spread over the take, and for a board that wanders one unit. + picked = np.stack(_spread_evenly(poses, DEFAULT_PICKS)) + uncertainty = position_uncertainty_m(1.0, picked) + # One pose turns about nothing, and the solve's measure has no second figure for it. + if len(picked) > 1: + most, second = (float(angle) for angle in head_turn_spread_deg(picked)[:2]) + # Each verdict takes the solve's own floor, or its grade's limit, and the margin over it. + self._moved = _holds(self._moved, spread / (_SOLVE_MARGIN * MIN_HEAD_POSITION_STD_M)) + turned = min(turn / self._turn_floor_deg, most / MIN_HEAD_TURN_DEG) / _SOLVE_MARGIN + self._turned = _holds(self._turned, turned) + # The grade holds the position's uncertainty and the board's wander each to its own limit, so the + # head has turned enough once a wander at its limit leaves the uncertainty within its own. + allowed = EXTRINSICS_UNCERTAINTY_M[0] / EXTRINSICS_SPREAD_M[0] + pinned = 0.0 if uncertainty is None else allowed / uncertainty + self._pinned = _holds(self._pinned, min(second / MIN_HEAD_SECOND_TURN_DEG, pinned) / _SOLVE_MARGIN) + return { + "tracking": tracking, + "position_spread_m": spread, + "rotation_deg": turn, + "turn_spread_deg": [most, second], + "uncertainty_per_wander": uncertainty, + "enough": self._moved and self._turned and self._pinned and sound_s >= self._sound_seconds_wanted, + # What each figure above is held to: the first three from below, the last from above. + "asked": { + "position_spread_m": _SOLVE_MARGIN * MIN_HEAD_POSITION_STD_M, + "rotation_deg": _SOLVE_MARGIN * self._turn_floor_deg, + "turn_spread_deg": [_SOLVE_MARGIN * MIN_HEAD_TURN_DEG, _SOLVE_MARGIN * MIN_HEAD_SECOND_TURN_DEG], + "uncertainty_per_wander": allowed / _SOLVE_MARGIN, + }, + "health": { + **self._health_record(tracking, now_seconds), + "sound_seconds": sound_s, + "sound_seconds_wanted": self._sound_seconds_wanted, + }, + } + + def _coverage_record(self) -> dict[str, Any]: + """The grid as plain data, with the corner cells and the edges between them reported on their own.""" + covered = self._covered + border = np.ones_like(covered) + border[1:-1, 1:-1] = False + # The corner cells are reported by name, so the edge share is of the border cells between them. + border[[0, 0, -1, -1], [0, -1, 0, -1]] = False + # A fisheye solve is graded on how far out the board was seen, which a cell does not say: under a + # 130-degree lens its innermost pixel looks 0.71 to 0.74 of the way to the picture's corner, short of + # what installs. + if self._model == FISHEYE: + reached = self._corner_reach >= _CORNER_REACH + else: + reached = np.array([covered[0, 0], covered[0, -1], covered[-1, 0], covered[-1, -1]]) + return { + "columns": covered.shape[1], + "rows": covered.shape[0], + "cells": covered.tolist(), + "fraction": float(covered.mean()), + "corners": {name: bool(done) for name, done in zip(PICTURE_CORNERS, reached)}, + "corner_reach": {name: float(reach) for name, reach in zip(PICTURE_CORNERS, self._corner_reach)}, + "edge_fraction": float(covered[border].mean()), + "density": { + "columns": self._density.shape[1], + "rows": self._density.shape[0], + "counts": self._density.tolist(), + "fraction_twice": float((self._density >= _DENSITY_SAMPLES).mean()), + }, + "asked": self._coverage_asked(), + } + + def _coverage_asked(self) -> dict[str, Any]: + """What the take's readiness holds each figure of the coverage to, under the figure's own name; None + for a figure it asks nothing of.""" + # A take that solves no lens asks nothing of where in the picture the board was seen. + if not self._needs_coverage: + return dict.fromkeys(("fraction", "edge_fraction", "corners", "corner_reach")) + return { + "fraction": self._min_coverage, + "edge_fraction": self._min_coverage, + "corners": dict.fromkeys(PICTURE_CORNERS, True), + # Only a fisheye solve is held to how far into a corner the board was seen; under the pinhole + # model a corner is reached by its cell being covered. + "corner_reach": dict.fromkeys(PICTURE_CORNERS, _CORNER_REACH) if self._model == FISHEYE else None, + } + + def _coverage_hints(self, coverage: dict[str, Any]) -> list[str]: + """What is left to cover, the corners first: distortion is solved from the rim of the picture. + + Each says to move the camera: when the position is solved too, the board must not move at all. + """ + hints = [] + missing = [name for name, reached in coverage["corners"].items() if not reached] + if missing: + noun = "corner" if len(missing) == 1 else "corners" + hint = ( + f"Take the board into the {_listed([name.replace('_', '-') for name in missing])} {noun} of the " + "picture by moving the camera; it may hang partly out of frame." + ) + # Where a corner is reached by how far in the board was seen, how far that is so far is said: the + # cell may be covered and the corner still short. + if self._model == FISHEYE: + so_far = [f"{math.floor(100 * coverage['corner_reach'][name])}%" for name in missing] + hint += ( + f" So far it was seen {_listed(so_far)} of the way there, and " + f"{round(100 * _CORNER_REACH)}% is needed." + ) + hints.append(hint) + if coverage["edge_fraction"] < self._min_coverage: + covered = self._covered + sides = {"top": covered[0, 1:-1], "bottom": covered[-1, 1:-1], "left": covered[1:-1, 0]} + sides["right"] = covered[1:-1, -1] + open_sides = [name for name, cells in sides.items() if not cells.all()] + noun = "edge" if len(open_sides) == 1 else "edges" + hints.append( + f"Run the board along the {_listed(open_sides)} {noun} of the picture by moving the camera." + ) + if coverage["fraction"] < self._min_coverage: + hints.append( + "Sweep the board over the rest of the picture by moving the camera: " + f"{round(100 * coverage['fraction'])}% is covered." + ) + return hints + + def _evidence_hints(self, evidence: dict[str, Any]) -> list[str]: + """What the counted views still lack for the intrinsics, as shares of what is asked.""" + hints = [] + # Cells are covered by any frame the solve could pick, and it picks few: slower, more of them count. + if not self._reaching: + reached = evidence["corner_coverage"] / (_SOLVE_MARGIN * INTRINSICS_COVERAGE[0]) + hints.append( + "Move the camera more slowly over the picture: the views counted so far reach " + f"{round(100 * reached)}% of what is needed of it." + ) + # Views that are alike in tilt fit any focal length, however many they are. + if self._measures_tilt and not self._tilted: + tilted = evidence["tilt_spread"] / (_SOLVE_MARGIN * INTRINSICS_TILT_SPREAD[0]) + hints.append( + "Tilt the camera more between views, up, down and to each side: the views counted so far " + f"differ in tilt by {round(100 * tilted)}% of what is needed." + ) + return hints + + @staticmethod + def _loss_words(health: dict[str, Any]) -> str: + """What a loss of the headset's position has cost the count of sound seconds.""" + if health["state"] == "lost": + return "The headset's position is lost now: what is recorded meanwhile does not count." + lost = f"The headset's position was last lost {round(health['lost_seconds_ago'])} s ago" + # Found again in another place, what lies before and after cannot be solved from together. + if health["stretches"] > 1: + return f"{lost} and was found again somewhere else, so only the longest stretch of tracking counts." + return f"{lost}: what was recorded meanwhile does not count." + + def _head_hints(self, head: dict[str, Any]) -> list[str]: + """What the head has still to do; nothing once it has moved and turned enough, in sound tracking.""" + hints = [] + health = head["health"] + # While views are short and nothing was lost, the count of views says as much: said once that + # count no longer does. + short = health["sound_seconds"] < self._sound_seconds_wanted + if short and (health["losses"] or self._views >= self._views_needed): + hint = ( + f"Keep going with the board in view: {math.floor(health['sound_seconds'])} of the " + f"{math.ceil(self._sound_seconds_wanted)} seconds of sound head tracking needed are in." + ) + # A loss holds the count back, which the operator would otherwise see it do unexplained. + if health["losses"]: + hint += f" {self._loss_words(health)}" + hints.append(hint) + if not self._moved: + hints.append("Move your head more: lean and step from side to side and up and down.") + most, second = head["turn_spread_deg"] + # A head that has hardly turned is told to turn before it is told about what. + if not self._turned: + hints.append(_TURN_MORE_HINT) + # Far enough, but mostly about one axis: the camera's place along that axis cannot be solved from + # it. A head that turned evenly needs more of the same. + elif not self._pinned: + hints.append( + "Turn your head about a second axis as well: look up and down, left and right, and tilt it " + "sideways." + if 2.0 * second < most + else _TURN_MORE_HINT + ) + return hints + + def _hints( + self, + visible: bool, + blurred: bool, + view_hint: str | None, + coverage: dict[str, Any], + evidence: dict[str, Any] | None, + head: dict[str, Any] | None, + ) -> list[str]: + """Everything still to do, most useful first; empty when the take is ready.""" + hints = [] + # What blocks everything else comes first: without tracking or the board, nothing below can be done. + if head is not None and not head["tracking"]: + hints.append(HEAD_TRACKING_HINT) + # A headset that sends poses and no longer knows where it is: nothing recorded meanwhile counts. + if head is not None and head["health"]["state"] == "lost": + hints.append(_LOST_HINT) + # Only a board that is found can be called smeared. + if not visible: + hints.append(_NOT_FOUND_HINT) + elif blurred: + hints.append(_SMEARED_HINT) + if self._needs_coverage: + hints.extend(self._coverage_hints(coverage)) + if self._views < self._views_needed: + # Said only while views are short: reaching a corner leaves little of the board in frame on purpose. + if view_hint is not None: + hints.append(view_hint) + # Worded for the camera: when the position is solved the board must not move at all. And then + # for where to stand: the lens alone is served by coming close, the position is not. + how = ( + f"tilting the camera between views, {_STAND_HINT}." + if self._needs_head_motion + else "tilting the camera and changing its distance to the board between views." + ) + hints.append(f"{self._views} of {self._views_needed} views collected: keep going, {how}") + if evidence is not None: + hints.extend(self._evidence_hints(evidence)) + # Head motion last: it comes about on its own while the operator looks at the board from new places. + if head is not None: + hints.extend(self._head_hints(head)) + return hints + + def _is_ready( + self, coverage: dict[str, Any], evidence: dict[str, Any] | None, head: dict[str, Any] | None + ) -> bool: + """Whether the take now holds what the solve needs.""" + pictured = evidence is None or ( + all(coverage["corners"].values()) + and coverage["fraction"] >= self._min_coverage + and coverage["edge_fraction"] >= self._min_coverage + and evidence["enough"] + ) + moved = head is None or head["enough"] + return self._views >= self._views_needed and pictured and moved + + def observe( + self, + frame: np.ndarray, + head_pose: np.ndarray | None, + now_seconds: float, + *, + counts: bool = True, + head_track: Sequence[tuple[float, np.ndarray]] | None = None, + ) -> GuideStatus: + """Take in one frame (grayscale or BGR), the head pose that came with it if any, and the current time. + + Runs one board detection. ``now_seconds`` spaces counted views apart and ages the frames that blur is + judged against, so any steady clock does. With ``counts`` False the frame is looked at and reported but + credited nothing (no view, no coverage, no head motion): for a frame the take will not hold what + the solve needs of. + + ``head_track`` is every head pose that arrived since the last call, oldest first, as + ``(seconds, pose)`` pairs on the clock of ``now_seconds``, each pose a 4x4 world-from-head like + ``head_pose``; an empty one when none arrived. Given with every picture, it is what the head + tracking's health and its sound seconds are read from, and a lost position is told as the solve + tells it. Never given, those are read from the pictures' own poses, which tell only a position + that stands still. ``head_pose`` stays the pose that goes with the picture. + """ + gray = as_gray(frame) + detection = self._detector.detect(gray) + value, blurred = self._judge_sharpness(gray, detection, now_seconds) + points = np.zeros((0, 2)) + whole, view_hint = False, None + if detection is not None: + # Corners are reported in the full image's pixels, whatever size the frame was fed at. + scale = (self._size[0] / gray.shape[1], self._size[1] / gray.shape[0]) + points = detection.corners.astype(np.float64) * scale + view = BoardView(0, detection.ids, points.astype(np.float32), self._detector.object_points(detection)) + # What the solve could pick: a view its lens model's solver can use. + usable = usable_for(view, self._model) + whole = usable and view.corners >= self._good_corners + if counts: + # A frame the solve would drop, or could never pick, covers nothing for it. + if usable and not blurred: + self._mark_covered(points) + self._corner_reach = np.maximum(self._corner_reach, corner_reach([view], self._size)) + view_hint = self._credit_view(view, whole, blurred, now_seconds) + head = None + if self._needs_head_motion: + head = self._head_record(head_pose, counts and whole, now_seconds, head_track) + evidence = self._evidence_record() if self._needs_coverage else None + coverage = self._coverage_record() + ready = self._is_ready(coverage, evidence, head) + if ready: + # What the current frame lacks no longer matters once enough is in. + hints = ["Enough has been captured: you can stop the take."] + else: + hints = self._hints(detection is not None, blurred, view_hint, coverage, evidence, head) + return GuideStatus( + image_size_wh=self._size, + board_visible=detection is not None, + corners=len(points), + board_corners=self._board_corners, + corner_points=points.tolist(), + sharpness=value, + blurred=bool(blurred), + views=self._views, + views_needed=self._views_needed, + coverage=coverage, + evidence=evidence, + head=head, + ready=ready, + hints=hints, + ) + + +def annotate(frame_bgr: np.ndarray, status: GuideStatus) -> np.ndarray: + """A copy of a BGR frame with the covered cells lightly tinted and the detected corners drawn, for a preview. + + The frame may be any size of the image's shape; the grid and the corners are scaled to it. + """ + out = frame_bgr.copy() + height, width = out.shape[:2] + # The grid stretched to the frame; blended rather than painted, so the picture under it stays visible. + cells = np.asarray(status.coverage["cells"], dtype=np.uint8) + covered = cv2.resize(cells, (width, height), interpolation=cv2.INTER_NEAREST).astype(bool) + out[covered] = (out[covered] * (1.0 - _TINT_STRENGTH) + np.array(_TINT) * _TINT_STRENGTH).astype(np.uint8) + scale = (width / status.image_size_wh[0], height / status.image_size_wh[1]) + for x, y in status.corner_points: + cv2.circle(out, (round(x * scale[0]), round(y * scale[1])), 3, _CORNER_COLOUR, -1, cv2.LINE_AA) + return out diff --git a/examples/egocap/recording/egocap/calibration/hand_view.py b/examples/egocap/recording/egocap/calibration/hand_view.py new file mode 100644 index 0000000000..fcd108dfe6 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/hand_view.py @@ -0,0 +1,333 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What an operator sees while calibrating the wrist offset: the frames of a take chosen for clicking, the +overlay a browser draws over each, and the live guide for recording a take worth choosing frames from. + +Tracking arrives here in OpenXR axes as recorded and leaves in forward-left-up world axes (see ``frames``). +""" + +from __future__ import annotations + +import dataclasses +import logging +from collections.abc import Mapping, Sequence +from typing import Any + +import numpy as np + +from egocap.calibration.camera_model import project, project_world +from egocap.calibration.files import Intrinsics +from egocap.calibration.frames import invert_pose, openxr_poses_to_flu +from egocap.calibration.wrist_offset import ( + JOINT_COUNT, + SIDES, + TIP_SLOTS, + HandSample, + WristOffset, + fingers_run_outward, + joints_px, + wrist_in_controller, +) + +_LOG = logging.getLogger("isaaccapture.egocap.hand_view") + +_AXIS_NAMES = ("origin", "x", "y", "z") +#: A hand whose fingers run outward from the wrist in fewer than this share of its frames is taken for one +#: whose joints arrive in another order. One frame says nothing, since a curled finger breaks the order in a +#: sound skeleton; a wrong order breaks it in every frame. +_OUTWARD_SHARE = 0.5 +#: What the operator is told of such a hand before any fingertip is clicked on it. +JOINT_ORDER_PROBLEM = ( + "The {side} glove's skeleton is not in the expected joint order: in most frames its fingers' joints do not " + "lie successively further from the wrist. Do not click on it: offsets fitted to this skeleton would be wrong." +) + + +class HandViewError(ValueError): + """A take or a picture the wrist-offset tool cannot work from; the message is written for the operator.""" + + +def scale_K(K: np.ndarray, from_wh: tuple[int, int], to_wh: tuple[int, int]) -> np.ndarray: + """A camera matrix solved at one image size, for the same picture delivered at another scale. + + Raises ``HandViewError`` for a size of any other shape: that is a crop or a stretch of the calibrated + picture, which no scaling of the matrix describes. + """ + (from_w, from_h), (to_w, to_h) = from_wh, to_wh + # A resize keeps the picture's shape to within the pixel it rounds away, at whichever size is coarser. + if abs(to_w * from_h - to_h * from_w) > max(from_w, from_h, to_w, to_h): + raise HandViewError( + f"The head camera's installed intrinsics are for a {from_w}x{from_h} image but its picture is " + f"{to_w}x{to_h}, which is not that image at another scale. Calibrate the headset again at this size." + ) + return np.diag([to_w / from_w, to_h / from_h, 1.0]) @ np.asarray(K, dtype=np.float64) + + +def _camera_at(intrinsics: Intrinsics, frame_size_wh: tuple[int, int]) -> Intrinsics: + """A calibrated camera as it delivers pictures of another size: the same picture at another scale. + + Only the matrix changes. Under either lens model the distortion coefficients act on the direction a + pixel looks along, not on pixels, so they are the same at every scale. Raises ``HandViewError`` as + ``scale_K`` does. + """ + size = (int(frame_size_wh[0]), int(frame_size_wh[1])) + return dataclasses.replace( + intrinsics, K=scale_K(intrinsics.K, intrinsics.image_size_wh, size), image_size_wh=size + ) + + +def _world_camera(head_openxr: np.ndarray, T_headset_camera: np.ndarray) -> np.ndarray: + """The head camera's pose in the forward-left-up world, for head poses recorded in OpenXR axes.""" + return openxr_poses_to_flu(head_openxr) @ T_headset_camera + + +def _inside(pixels: np.ndarray, size_wh: tuple[int, int], margin_px: float = 0.0) -> np.ndarray: + """Which pixels (P, 2) lie in an image grown by a margin on every side; a NaN pixel never does.""" + u, v = pixels[:, 0], pixels[:, 1] + return (u >= -margin_px) & (u < size_wh[0] + margin_px) & (v >= -margin_px) & (v < size_wh[1] + margin_px) + + +def _points(pixels: np.ndarray) -> list[list[float] | None]: + """Pixels as JSON values: ``[u, v]``, or ``None`` where a point has no finite pixel.""" + return [[float(u), float(v)] if np.isfinite(u) and np.isfinite(v) else None for u, v in pixels] + + +def build_samples( + frame_valid: np.ndarray, + head_world: np.ndarray, + controllers_world: Mapping[str, np.ndarray], + hands_local: Mapping[str, np.ndarray], + hands_valid: Mapping[str, np.ndarray], + intrinsics: Intrinsics, + T_headset_camera: np.ndarray, + frame_size_wh: tuple[int, int], + *, + n_samples: int = 40, + margin_px: float = 200.0, + start_offsets: Mapping[str, WristOffset] | None = None, +) -> list[HandSample]: + """Choose the frames of a take to click fingertips in: spread evenly over those that show a gloved hand. + + The arrays hold the take's tracking at each head-camera frame's time, in OpenXR axes as recorded: head + and controller poses (N, 4, 4), skeletons (N, 25, 4, 4) and per-hand validity (N,), keyed by hand. + ``frame_valid`` marks the frames the tracking covers and ``frame_size_wh`` is the video's size, which + the intrinsics are scaled to. Raises ``HandViewError`` when too few frames show a hand, or when the + video is not the calibrated picture at another scale. + """ + offsets = {side: WristOffset() for side in SIDES} if start_offsets is None else start_offsets + # Refused here, before any frame is chosen, when the video is another shape than the calibrated picture. + camera = _camera_at(intrinsics, frame_size_wh) + # A frame the tracking does not cover holds placeholder poses, so those are dropped before any math. + frames = np.flatnonzero(frame_valid) + world_camera = _world_camera(np.asarray(head_world)[frames], T_headset_camera) + controllers = {side: openxr_poses_to_flu(np.asarray(controllers_world[side])[frames]) for side in SIDES} + + # There is something to click only where a glove gave a pose and its wrist is near the image. The margin + # allows for the start offset being wrong: the hand can be in view while its assumed wrist is not. + shows_hand = np.zeros(len(frames), dtype=bool) + for side in SIDES: + wrist = (controllers[side] @ wrist_in_controller(offsets[side]))[:, :3, 3] + in_camera = np.einsum("nji,nj->ni", world_camera[:, :3, :3], wrist - world_camera[:, :3, 3]) + near_image = _inside(project(in_camera, camera), frame_size_wh, margin_px) + shows_hand |= near_image & np.asarray(hands_valid[side], dtype=bool)[frames] + rows = np.flatnonzero(shows_hand) + needed = max(3, n_samples // 2) + _LOG.info("wrist offset sampling: %d of %d frames show a gloved hand", len(rows), len(shows_hand)) + # A handful of frames cannot show the hands in enough different poses to fit from. + if len(rows) < needed: + raise HandViewError( + f"Only {len(rows)} head-camera frames show a gloved hand and the fit needs at least {needed}. " + "Record a take with both hands held where the head camera can see them." + ) + + # Frames are evenly spaced in time, so evenly spaced picks are evenly spread in time. + spread = np.linspace(0, len(rows) - 1, min(n_samples, len(rows))) + samples = [] + for row in rows[np.unique(np.round(spread).astype(int))]: + frame = int(frames[row]) + samples.append( + HandSample( + frame_index=frame, + intrinsics=camera, + T_camera_world=invert_pose(world_camera[row]), + controller_world={side: controllers[side][row] for side in SIDES}, + hand_local={side: np.asarray(hands_local[side][frame], dtype=np.float64) for side in SIDES}, + hand_valid={side: bool(hands_valid[side][frame]) for side in SIDES}, + ) + ) + return samples + + +def joint_order_problems(samples: Sequence[HandSample]) -> dict[str, str]: + """For each hand whose recorded skeleton does not run as a hand does, the sentence that says so, by hand; + empty when both do. + + The fingertip a click belongs to is found by its slot in the skeleton. Gloves whose software delivers the + joints in another order put fingertips in other slots, and no fit brings the error down. + """ + problems = {} + for side in SIDES: + # A frame without a glove pose holds a placeholder, and one with a joint missing cannot be judged. + seen = (fingers_run_outward(sample.hand_local[side]) for sample in samples if sample.hand_valid[side]) + judged = [outward for outward in seen if outward is not None] + if judged and sum(judged) < _OUTWARD_SHARE * len(judged): + _LOG.warning("the %s glove's fingers run outward in %d of %d frames", side, sum(judged), len(judged)) + problems[side] = JOINT_ORDER_PROBLEM.format(side=side) + return problems + + +def _axes_px(sample: HandSample, T_world_frame: np.ndarray, length_m: float) -> dict[str, list[float] | None]: + """Pixels of a frame's origin and of the ends of its three axes drawn ``length_m`` long.""" + origin = T_world_frame[:3, 3] + points = np.vstack([origin, origin + length_m * T_world_frame[:3, :3].T]) + pixels = project_world(points, sample.T_camera_world, sample.intrinsics) + return dict(zip(_AXIS_NAMES, _points(pixels))) + + +def overlay( + sample: HandSample, offsets: Mapping[str, WristOffset], *, axis_length_m: float = 0.08 +) -> dict[str, Any]: + """What a browser draws over a sampled frame under the given offsets, per hand, as JSON values. + + Each hand has ``valid``, ``joints_px`` (a pixel per skeleton slot), ``tips_px`` (the fingertips in the + order of ``FINGERS``), ``wrist_axes_px`` (the calibrated wrist frame) and ``controller_axes_px`` (the + raw controller frame, drawn at half the length). A point with no pixel is ``None``. + """ + drawn = {} + for side in SIDES: + valid = bool(sample.hand_valid[side]) + # Without a glove pose the stored skeleton is a placeholder, and drawing it would invite a click. + joints = _points(joints_px(sample, side, offsets[side])) if valid else [None] * JOINT_COUNT + controller = sample.controller_world[side] + drawn[side] = { + "valid": valid, + "joints_px": joints, + "tips_px": [joints[slot] for slot in TIP_SLOTS], + "wrist_axes_px": _axes_px(sample, controller @ wrist_in_controller(offsets[side]), axis_length_m), + "controller_axes_px": _axes_px(sample, controller, axis_length_m / 2.0), + } + return drawn + + +class HandViewGuide: + """Tells an operator recording a take for the wrist-offset fit whether the head camera is seeing the hands. + + A hand is counted when its controller is tracked, its glove is delivering joints and the controller + projects inside the image, at most once every ``min_gap_s``. The take is ready once each hand has been + counted ``needed`` times: counts that far apart are different moments of a moving hand, so the frames + later chosen from the take show distinct poses and not one pose many times over. One guide covers one + recording, and it is not safe to call from more than one thread. + """ + + HEADSET_HINT = "The headset is not being tracked. Put it on and keep it awake." + CONTROLLER_HINT = "The {side} controller is not being tracked." + GLOVE_HINT = "The {side} glove is not sending finger joints. Put both gloves on and check their connection." + VIEW_HINT = "Hold both hands where the head camera can see them." + MOVE_HINT = "Keep both hands in view and move them through different poses and distances." + DONE_HINT = "Enough has been collected. You can stop the recording." + + def __init__( + self, + intrinsics: Intrinsics, + T_headset_camera: np.ndarray, + frame_size_wh: tuple[int, int], + *, + min_gap_s: float = 0.5, + needed: int = 40, + ) -> None: + """Guide for a head camera delivering ``frame_size_wh`` images, with its installed calibration. + + Raises ``HandViewError`` when those images are not the calibrated picture at another scale. + """ + # The live image can be the calibrated picture at another scale, and nothing else: a guide drawn + # through a stretched camera would count hands where they are not. + self._camera = _camera_at(intrinsics, frame_size_wh) + self._T_headset_camera = np.asarray(T_headset_camera, dtype=np.float64) + self._frame_size_wh = frame_size_wh + self._min_gap_s = min_gap_s + self._needed = needed + self._counts = {side: 0 for side in SIDES} + self._counted_at: dict[str, float | None] = {side: None for side in SIDES} + + def _observe_hand( + self, + side: str, + T_camera_world: np.ndarray | None, + controller: np.ndarray | None, + glove_present: bool, + now_seconds: float, + ) -> dict[str, Any]: + """One hand's state for this observation, counting it when it is in view and due.""" + pixel, in_view = None, False + # Seeing the controller takes both ends of the projection: the camera's pose and the controller's. + if T_camera_world is not None and controller is not None: + origin = openxr_poses_to_flu(controller)[:3, 3] + projected = project_world(origin, T_camera_world, self._camera) + pixel, in_view = _points(projected)[0], bool(_inside(projected, self._frame_size_wh)[0]) + counted_at = self._counted_at[side] + # Counting no more often than the gap is what makes the count mean time spent in view. + due = counted_at is None or now_seconds - counted_at >= self._min_gap_s + if in_view and glove_present and due: + self._counts[side] += 1 + self._counted_at[side] = now_seconds + return { + "controller_tracked": controller is not None, + "glove_present": glove_present, + "in_view": in_view, + "pixel": pixel, + "observations": self._counts[side], + } + + def observe( + self, + head_pose: np.ndarray | None, + controllers: Mapping[str, np.ndarray | None], + hands_present: Mapping[str, bool], + now_seconds: float, + ) -> dict[str, Any]: + """Take in the latest tracking and report, as JSON values, what the operator should know. + + Poses are 4x4 in OpenXR axes, or ``None`` when not received; ``hands_present`` says whether each + glove is delivering joints, and ``now_seconds`` is a monotonic clock. The report holds + ``head_tracked``, per-hand state under ``hands`` (``controller_tracked``, ``glove_present``, + ``in_view``, the controller's ``pixel`` and its running ``observations``), ``needed``, ``ready`` + and ``hints``, most pressing first. + """ + head_tracked = head_pose is not None + # Without the head there is no camera pose, and so no telling where a controller appears. + T_camera_world = invert_pose(_world_camera(head_pose, self._T_headset_camera)) if head_tracked else None + hands = { + side: self._observe_hand( + side, T_camera_world, controllers[side], bool(hands_present[side]), now_seconds + ) + for side in SIDES + } + ready = all(self._counts[side] >= self._needed for side in SIDES) + + # Hints run from what must be fixed first to what merely helps. + hints = [] + if not head_tracked: + hints.append(self.HEADSET_HINT) + hints += [ + self.CONTROLLER_HINT.format(side=side) for side in SIDES if not hands[side]["controller_tracked"] + ] + hints += [self.GLOVE_HINT.format(side=side) for side in SIDES if not hands[side]["glove_present"]] + # Whether a hand is in view is only known while the headset and both controllers are tracked. + tracked = head_tracked and all(hands[side]["controller_tracked"] for side in SIDES) + if tracked and not all(hands[side]["in_view"] for side in SIDES): + hints.append(self.VIEW_HINT) + # Being done is worth saying whatever else is wrong; before that, the hint to keep moving is for + # when nothing is. + if ready: + hints.append(self.DONE_HINT) + elif not hints: + hints.append(self.MOVE_HINT) + return { + "head_tracked": head_tracked, + "hands": hands, + "needed": self._needed, + "ready": ready, + "hints": hints, + } diff --git a/examples/egocap/recording/egocap/calibration/intrinsics.py b/examples/egocap/recording/egocap/calibration/intrinsics.py new file mode 100644 index 0000000000..dcb474311c --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/intrinsics.py @@ -0,0 +1,557 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Camera intrinsics from views of the board: a camera matrix and the distortion coefficients of one of the +two lens models ``files`` names, OpenCV's radial-tangential one (pinhole) or its fisheye one. + +The camera is solved twice. The first solve shows which views disagree with the rest (a blurred frame, a +corner matched to the wrong place); those are dropped and the camera is solved again from the others. A +fisheye solve goes round again while its views still disagree: its solver hides one wild view behind another. + +A small reprojection error says the model fits the views it was given, not that those views fix the camera: +views that are alike fit any focal length, and a few views fit almost any fisheye. The record therefore also +says how much the views used can be trusted to pin the camera (``corner_coverage``, ``tilt_spread``, +``focal_uncertainty``) and how far out the lens was seen (``max_field_angle_deg``), for the grade. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from typing import Any + +import cv2 +import numpy as np + +from .board import BoardSpec, BoardView, CalibrationError +from .camera_model import field_angle_deg, field_limit_deg, picture_corner_angle_deg, posed_projection +from .files import DISTORTION_NAMES, FISHEYE, PINHOLE, Intrinsics + +#: Fewest usable views each lens model is solved from. A fisheye fits a handful of views whatever the lens, +#: at the same RMS. On synthetic lenses of 90 to 135 degrees across, well-tilted views, corners found to +#: 0.5 px, 40 takes each: from 4 to 6 views 35 to 38% of solves were over 5 px off at the picture's corners +#: and the worst 58 to 193 px; from 7, 28% and 23 px; from 8, 18% and 11 px. +MIN_VIEWS = {PINHOLE: 4, FISHEYE: 8} +#: Fewest corners a view must show to be used. OpenCV's fisheye solver gives up on a take that holds a view +#: of exactly four: one such view among 19 whole ones failed 7 of 8 takes, views of five or more none of 72. +MIN_CORNERS = {PINHOLE: 4, FISHEYE: 5} +#: Fewest corners a fisheye view must show off the row or column of the board that holds most of them. +#: OpenCV's fisheye solver starts each view's pose from a flat picture of the board, which a line of corners +#: with one beside it hardly gives: it poses such a view anywhere, and then gives up on the whole take. +#: Measured on 84 synthetic takes of a 128-degree lens, 27 whole views and three of one row and one corner +#: of the next: the solver finished from no start in 25 and left 6 more fitted too poorly to install; with +#: the three left out all 84 solved to the lens. With a second corner beside the row the solver kept the +#: three views and solved 60 of 60. The radial-tangential solver used the views of one corner in 12 of 12. +_FISHEYE_OFF_LINE = 2 +#: How many times the views that disagree with the rest are dropped and the camera solved again. The +#: radial-tangential solver takes a wild view in its stride, and one pass is what its limits were measured +#: with. OpenCV's fisheye solver poses a wild view anywhere, and a solve that holds three may show two of +#: them and the third only once those are gone. On the 84 takes above, their three views counted as usable +#: for the measurement: one pass left 9 solves still holding one of the three and graded bad, three passes +#: none. In both, 3 takes stayed unsolved, no start having got through its first stage. +_OUTLIER_ROUNDS = {PINHOLE: 1, FISHEYE: 3} +#: Cells (columns, rows) the picture is divided into when measuring how much of it the corners reached. +COVERAGE_GRID = (8, 6) +#: The picture's four corners, in the order ``corner_reach`` reports them. +PICTURE_CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right") +#: Smallest eigenvalue, of a normal matrix scaled to a unit diagonal, below which the views leave some +#: combination of the camera's parameters undetermined. +_SINGULAR = 1e-10 + +# OpenCV's fisheye solver walks downhill from where it is put, and from a poor place it raises or settles +# far off without a word. It is therefore started from several places, each time with the last two +# coefficients held at zero first, and the best fit is kept. Measured on 321 synthetic lenses of 60 to 170 +# degrees across, 8 to 30 views each: the first start alone found the fit in 318, some start in all; a start +# that settled elsewhere ended at 36 px or more, ten times the best; and without the first stage the widest +# start failed 41 to 53 times of 54 where staged it failed 0 to 18. + +#: Skew stays zero because OpenCV's fisheye projection ignores it; the conditioning check is left off +#: because it refuses sound takes. +_FISHEYE_FLAGS = ( + cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC | cv2.fisheye.CALIB_FIX_SKEW | cv2.fisheye.CALIB_USE_INTRINSIC_GUESS +) +_FISHEYE_FIRST_STAGE = _FISHEYE_FLAGS | cv2.fisheye.CALIB_FIX_K3 | cv2.fisheye.CALIB_FIX_K4 +_FISHEYE_CRITERIA = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, 1e-9) +#: Focal lengths the solver is started from, as multiples of half the picture's longer side. +_FISHEYE_FOCAL_LADDER = (1.0, 1.35, 0.75, 1.8) +#: A start that fits this well found the lens, and no other is tried: see the figures above. +_FISHEYE_GOOD_RMS_PX = 3.0 + +# OpenCV's radial-tangential solver walks downhill too. From its own start it settles, on a wide lens seen +# with little tilt, at a focal length 5 to 20% off with a fit all but as good as the true one's, and the +# views then look as if they pinned it. It is therefore run again from a ladder of focal lengths, and a +# ladder start is taken only when it fits clearly better. Measured on two sets of 1320 synthetic takes (12 +# and 30 views tilted from not at all to 35 degrees, corners found to 0.2 px), each take solved from +# OpenCV's start alone and with the ladder. On the first set (lenses drawn around three cameras, some with a +# curve that turns inside the picture): graded excellent while over 5% off in focal length, 13 takes and +# none; 98 takes came to within 1% of the true focal length and none left it. On the second (focal lengths +# of 0.4 to 2 times the picture's longer side, every curve rising past the picture's corners): 4 takes and +# none; over 2% off, 5 and 1; 28 came to within 1% and none left it. Each rung costs one more run of the +# solver, a quarter of a second for 30 views. + +#: Focal lengths the radial-tangential solver is started from beside its own start, as multiples of the +#: picture's longer side. A run started between 0.7 and 1.5 times the true focal length ended within 1% of it +#: 92 to 95 times in 100, one started below half of it or above 2.2 times it 35 to 39; two more rungs above +#: these found no more fits, and rungs placed around OpenCV's own answer found fewer. +_PINHOLE_FOCAL_LADDER = (0.4, 0.6, 0.9, 1.35) +#: How much lower, as a share, a ladder start's error must be for it to be taken over OpenCV's own start. +#: Two runs that end at one fit differ by less than this where they stopped: of 792 such takes, taking the +#: lowest error outright moved 8 that were within 1% of the true focal length away from it, each for a gain +#: under 0.2%, and a bar anywhere from 0.2% to 1% moved none. +_PINHOLE_GAIN = 0.01 + + +#: What a run of either OpenCV solver comes to: RMS, camera matrix, coefficients and each view's pose. +_Solved = tuple[float, np.ndarray, np.ndarray, Sequence[np.ndarray], Sequence[np.ndarray]] +#: What the operator is told when no solver run gets anywhere. +_UNSOLVED = ( + "The intrinsics could not be solved from these views. Record again, viewing the board from different angles." +) + + +@dataclass(frozen=True) +class _Fit: + """One solve over some views: the camera, the board's pose in each view, and how well it all fits.""" + + rms: float + camera: Intrinsics + #: Each view's pose as a rotation vector and a translation, in the order of the views. + poses: list[tuple[np.ndarray, np.ndarray]] + #: Each view's own reprojection RMS in pixels. + per_view: list[float] + #: The focal lengths' relative uncertainty; None when the views do not determine the camera. + focal_uncertainty: float | None + #: False for a fisheye fit no start carried past its first stage. Such a fit shows which views disagree + #: with the rest, and is good for nothing else. + complete: bool = True + + +def corner_coverage(views: Sequence[BoardView], image_size_wh: tuple[int, int]) -> float: + """The share of the picture, in ``COVERAGE_GRID`` cells, that holds a corner of at least one view. + + The lens model is only known where corners were seen: outside that part it is an extrapolation. + """ + columns, rows = COVERAGE_GRID + covered = np.zeros((rows, columns), dtype=bool) + for view in views: + # A corner found a hair outside the picture belongs to the cell at its edge. + column = np.clip((view.image_points[:, 0] / image_size_wh[0] * columns).astype(int), 0, columns - 1) + row = np.clip((view.image_points[:, 1] / image_size_wh[1] * rows).astype(int), 0, rows - 1) + covered[row, column] = True + return float(covered.mean()) + + +def corner_reach(views: Sequence[BoardView], image_size_wh: tuple[int, int]) -> np.ndarray: + """How far into each corner of the picture the views' corners were seen, in the order of + ``PICTURE_CORNERS``: per quarter of the picture, the furthest a corner in it lies from the picture's + middle, as a share of the way to the picture's own corner; 0 for a quarter that holds none. + + It needs no lens model, so a take can be judged by it while it is recorded, and frames compared by it + before any solve. The grade measures the solved lens instead: the angle from its axis at which the + furthest corner was seen, against that of the picture's furthest corner. + """ + middle = np.array([(image_size_wh[0] - 1) / 2.0, (image_size_wh[1] - 1) / 2.0]) + reach = np.zeros(len(PICTURE_CORNERS)) + for view in views: + offset = view.image_points.astype(np.float64) - middle + # Right of the middle counts one, below it two: the order of the names. + quarter = (offset[:, 0] > 0.0) + 2 * (offset[:, 1] > 0.0) + np.maximum.at(reach, quarter, np.hypot(offset[:, 0], offset[:, 1]) / np.hypot(*middle)) + return reach + + +def usable_for(view: BoardView, model: str) -> bool: + """Whether a lens model's solver can use a view: corners enough for it (``MIN_CORNERS``) that span the + board's plane, and for the fisheye solver ``_FISHEYE_OFF_LINE`` of them or more off the row or column of + the board that holds most.""" + if view.corners < MIN_CORNERS[model] or not view.spans_plane: + return False + if model != FISHEYE: + return True + # Board points are multiples of the square's side, so rounded they fall into the board's rows and columns. + board = np.round(view.object_points[:, :2].astype(np.float64), 6) + most = max(int(np.unique(board[:, axis], return_counts=True)[1].max()) for axis in (0, 1)) + return view.corners - most >= _FISHEYE_OFF_LINE + + +def _board_reach(view: BoardView) -> tuple[np.ndarray, float]: + """The middle of the corners a view shows, on the board, and their root-mean-square distance from it.""" + board = view.object_points.astype(np.float64) + middle = board.mean(axis=0) + return middle, float(np.sqrt(np.square(board - middle).sum(axis=1).mean())) + + +def _foreshortening(view: BoardView) -> np.ndarray: + """How one view foreshortens the board: the relative change in depth across the corners it shows, along + each axis of the board. + + It is the projective part of the view's own board-to-picture homography, so it needs no camera matrix, + and it is zero for a board seen flat-on wherever in the picture and however far it is. A picture bent by + a fisheye lens is no homography of the board: there ``_posed_foreshortening`` gives the same figure. + """ + board = view.object_points[:, :2].astype(np.float64) + picture = view.image_points.astype(np.float64) + # Both are centred and brought to unit size, which leaves the projective part alone and keeps the fit + # well conditioned whatever the board's size in meters and the picture's in pixels. The floor keeps + # corners that all fell on one pixel from dividing by nothing. + board = board - board.mean(axis=0) + board = board / np.sqrt(np.square(board).sum(axis=1).mean()) + picture = (picture - picture.mean(axis=0)) / max(float(picture.std()), np.finfo(float).tiny) + # picture = (A board + b) / (1 + p . board), made linear in A, b and p by multiplying out. + ones, zeros = np.ones((len(board), 1)), np.zeros((len(board), 3)) + design = np.vstack( + [ + np.hstack([board, ones, zeros, -picture[:, :1] * board]), + np.hstack([zeros, board, ones, -picture[:, 1:] * board]), + ] + ) + solution, *_ = np.linalg.lstsq(design, np.concatenate([picture[:, 0], picture[:, 1]]), rcond=None) + return solution[6:] + + +def _posed_foreshortening(view: BoardView, pose: tuple[np.ndarray, np.ndarray]) -> np.ndarray: + """The figure ``_foreshortening`` reads from a view's corners, from the view's solved pose instead. + + Depth along the optical axis is what it measures under either lens model: a board square to that axis + says nothing of the focal length wherever it is in the picture, through a fisheye as through a pinhole. + """ + rotation, _ = cv2.Rodrigues(np.asarray(pose[0], dtype=np.float64).reshape(3, 1)) + middle, reach = _board_reach(view) + depth = float(rotation[2] @ middle + np.asarray(pose[1], dtype=np.float64).reshape(3)[2]) + # The board's two axes each climb away from the camera by the third row of the rotation. + return reach * rotation[2, :2] / depth + + +def _spread_about_second_axis(vectors: np.ndarray) -> float: + """The root-mean-square spread of some vectors about their second principal axis; 0 for a single one.""" + spread = np.linalg.svd(vectors - vectors.mean(axis=0), compute_uv=False) + # A single vector has one spread only, and nothing to differ from about a second axis. + return float(np.append(spread, 0.0)[1] / np.sqrt(len(vectors))) + + +def tilt_spread(views: Sequence[BoardView]) -> float: + """How much the views differ in tilt, about the axis they differ least about; 0 for copies of one view. + + Each view's ``_foreshortening`` is a vector along the board's two axes, and this is the root-mean-square + spread of those vectors about their second principal axis: views tilted one way only leave it near + zero. Because it is read from the corners alone, it stands whatever the solve made of them. A + strongly distorted lens bends a flat-on board into some apparent tilt (0.03 to 0.04 was measured at a + first radial coefficient of -0.3), so a figure above zero is no proof that the views pin the camera, and + through a fisheye lens it says nothing: a fisheye solve measures its poses (``posed_tilt_spread``). + """ + return _spread_about_second_axis(np.stack([_foreshortening(view) for view in views])) + + +def posed_tilt_spread(views: Sequence[BoardView], poses: Sequence[tuple[np.ndarray, np.ndarray]]) -> float: + """``tilt_spread`` from the views' solved poses (rotation vector, translation), for a lens that bends + the picture too far for the corners alone to show tilt. It rests on the solve it judges: views that are + all square to the camera solve to poses that are, whatever focal length the solve settled on.""" + return _spread_about_second_axis( + np.stack([_posed_foreshortening(view, pose) for view, pose in zip(views, poses, strict=True)]) + ) + + +def _focal_uncertainty( + views: Sequence[BoardView], camera: Intrinsics, poses: Sequence[tuple[np.ndarray, np.ndarray]] +) -> float | None: + """The relative standard deviation of the solved focal lengths, the larger of the two; None when the views + do not determine the camera at all. + + It is the usual least-squares estimate: the reprojection error's variance spread through the inverse of + the normal matrix of the camera's parameters, each view's pose having taken its own share first. OpenCV's + ``calibrateCameraExtended`` reports the same figure where the views pin the camera and not where they + fail to: it inverts by a truncated SVD, which drops the very direction left loose. For a flat-on board + slid about under a lens with a first radial coefficient of -0.3 it read under 0.1% with the focal length + 30% off (OpenCV 4.12), where this reads several hundred percent or None, so the figure is worked out + here. OpenCV's fisheye solver reports no uncertainty at all; the same estimate serves it. Measured on + 143 synthetic fisheye takes, each solved 30 times with only its 0.3 px corner noise redrawn: the focal + length's real scatter was 0.68 to 1.36 of this figure (median 1.01), over figures from 0.02% to 1.5%. + """ + unknowns = 4 + len(camera.dist) + normal = np.zeros((unknowns, unknowns)) + squared_error, residuals = 0.0, 0 + for view, (rvec, tvec) in zip(views, poses, strict=True): + projected, pose, parameters = posed_projection(view.object_points, rvec, tvec, camera) + # A solve that ran away to numbers that are not finite has no uncertainty to speak of. + if not (np.all(np.isfinite(pose)) and np.all(np.isfinite(parameters))): + return None + error = view.image_points.astype(np.float64) - projected + squared_error += float(np.square(error).sum()) + residuals += error.size + # A view's pose is solved with the camera, so what the view says about the camera is what is left + # once its pose is eliminated. Slopes that are finite and absurd overflow here, which is judged + # below and not warned about. + with np.errstate(over="ignore", invalid="ignore"): + shared = parameters.T @ pose + normal += parameters.T @ parameters - shared @ np.linalg.pinv(pose.T @ pose) @ shared.T + freedom = residuals - unknowns - 6 * len(views) + # Without spare corners there is no error left over to estimate from. + if freedom <= 0: + return None + # What is left for a parameter once the poses have taken their share is its diagonal entry here. Zero + # says the views do not move with it at all; below zero, that the elimination lost its footing on a fit + # that ran away (-5 was seen beside entries of 20). Neither is an uncertainty. Do not scale by such an + # entry: on flat-on boards slid about under a fisheye lens that overflowed, and the eigensolver raised, + # in 10 of 420 synthetic takes. + diagonal = np.diag(normal) + if not (np.all(np.isfinite(normal)) and np.all(diagonal > 0.0)): + return None + # Scaled to a unit diagonal first: a focal length in pixels and a distortion coefficient near zero differ + # by orders of magnitude, which would otherwise pass for a singular matrix. + scale = np.sqrt(diagonal) + values, vectors = np.linalg.eigh(normal / np.outer(scale, scale)) + if values[0] < _SINGULAR: + return None + # The focal lengths are the first two parameters; their variances are those rows of the inverse. + variance = np.square(vectors[:2]) @ (1.0 / values) / np.square(scale[:2]) * squared_error / freedom + return float(np.max(np.sqrt(variance) / np.abs([camera.K[0, 0], camera.K[1, 1]]))) + + +def _pinhole_run( + views: Sequence[BoardView], size: tuple[int, int], start: np.ndarray | None = None +) -> _Solved | None: + """One run of OpenCV's radial-tangential solver over ``views``, from its own start or from a camera + matrix: RMS, matrix, coefficients and each view's pose; None for a run that raised or came back with + numbers no camera has.""" + object_points = [view.object_points.reshape(-1, 1, 3).astype(np.float32) for view in views] + image_points = [view.image_points.reshape(-1, 1, 2).astype(np.float32) for view in views] + try: + if start is None: + fit = cv2.calibrateCamera(object_points, image_points, size, None, None) + else: + # Copies: the solver writes its answer into what it is given. + fit = cv2.calibrateCamera( + object_points, image_points, size, start.copy(), np.zeros(5), flags=cv2.CALIB_USE_INTRINSIC_GUESS + ) + except cv2.error: + # OpenCV's own text names source files and is no use to an operator. + return None + rms, K, dist = fit[:3] + sound = ( + np.isfinite(rms) and np.all(np.isfinite(K)) and np.all(np.isfinite(dist)) and min(K[0, 0], K[1, 1]) > 0.0 + ) + return fit if sound else None + + +def _solve_pinhole(views: Sequence[BoardView], size: tuple[int, int]) -> _Solved | None: + """OpenCV's radial-tangential solve over ``views``, from its own start and from a ladder of focal + lengths: the best fit's RMS, matrix, coefficients and each view's pose; None when no start gets anywhere. + + OpenCV's own start is kept unless a ladder start fits clearly better (``_PINHOLE_GAIN``), so a take it + solves right is left as it solves it. + """ + best = _pinhole_run(views, size) + # With no fit of OpenCV's own to better, any fit will do. + bar = math.inf if best is None else (1.0 - _PINHOLE_GAIN) * best[0] + centre = ((size[0] - 1) / 2.0, (size[1] - 1) / 2.0) + for step in _PINHOLE_FOCAL_LADDER: + focal = step * max(size) + fit = _pinhole_run( + views, size, np.array([[focal, 0.0, centre[0]], [0.0, focal, centre[1]], [0.0, 0.0, 1.0]]) + ) + # Once one start has cleared the bar, another has only to fit better than it. + if fit is not None and fit[0] < bar: + best, bar = fit, fit[0] + return best + + +def _fisheye_starts(views: Sequence[BoardView], size: tuple[int, int]) -> Iterator[np.ndarray]: + """Camera matrices to start the fisheye solver from, the likeliest first, made as they are asked for.""" + half_side = max(size) / 2.0 + centre = ((size[0] - 1) / 2.0, (size[1] - 1) / 2.0) + ladder = [ + np.array([[step * half_side, 0.0, centre[0]], [0.0, step * half_side, centre[1]], [0.0, 0.0, 1.0]]) + for step in _FISHEYE_FOCAL_LADDER + ] + yield ladder[0] + # The radial-tangential solve of the same views knows where the principal point is, which the ladder + # does not; for a very wide lens its focal length is poor, so it comes second. It is worth its time + # only when the first start was not enough, and one run of it is enough for a place to start from. + pinhole = _pinhole_run(views, size) + if pinhole is not None: + yield np.array( + [[pinhole[1][0, 0], 0.0, pinhole[1][0, 2]], [0.0, pinhole[1][1, 1], pinhole[1][1, 2]], [0.0, 0.0, 1.0]] + ) + yield from ladder[1:] + + +def _fisheye_stage( + object_points: list[np.ndarray], + image_points: list[np.ndarray], + size: tuple[int, int], + K: np.ndarray, + dist: np.ndarray, + flags: int, +) -> _Solved | None: + """One run of OpenCV's fisheye solver from a camera matrix and coefficients; None for a run that raised + or came back with numbers no camera has.""" + try: + # Copies: the solver writes its answer into what it is given. + rms, K, dist, rvecs, tvecs = cv2.fisheye.calibrate( + object_points, image_points, size, K.copy(), dist.copy(), flags=flags, criteria=_FISHEYE_CRITERIA + ) + except cv2.error: + return None + sound = ( + np.isfinite(rms) and np.all(np.isfinite(K)) and np.all(np.isfinite(dist)) and min(K[0, 0], K[1, 1]) > 0.0 + ) + return (float(rms), K, dist, rvecs, tvecs) if sound else None + + +def _solve_fisheye(views: Sequence[BoardView], size: tuple[int, int]) -> tuple[_Solved | None, _Solved | None]: + """OpenCV's fisheye solve over ``views``, from several starts in two stages each. Returns the best fit + (RMS, matrix, coefficients and each view's pose), None when no start got through both stages, and the + best fit of a first stage alone, None when no start got through that either. + + A few wild views stop the second stage from every start, and the first from most; the first stage's fit + still poses every view, and shows which they are. + """ + # This solver takes each view's points as one row, where the radial-tangential one takes a column. + object_points = [view.object_points.reshape(1, -1, 3).astype(np.float64) for view in views] + image_points = [view.image_points.reshape(1, -1, 2).astype(np.float64) for view in views] + best = rough = None + for start in _fisheye_starts(views, size): + # The last two coefficients are held at zero until the first two have found the lens's shape. + first = _fisheye_stage(object_points, image_points, size, start, np.zeros(4), _FISHEYE_FIRST_STAGE) + if first is None: + continue + if rough is None or first[0] < rough[0]: + rough = first + fit = _fisheye_stage(object_points, image_points, size, first[1], first[2], _FISHEYE_FLAGS) + if fit is None: + continue + if best is None or fit[0] < best[0]: + best = fit + if best[0] < _FISHEYE_GOOD_RMS_PX: + break + return best, rough + + +def _calibrate(views: Sequence[BoardView], size: tuple[int, int], model: str) -> _Fit: + """One solve over ``views`` under a lens model, with each view's own error and the focal uncertainty.""" + complete = True + if model == FISHEYE: + solved, rough = _solve_fisheye(views, size) + # No start got through both stages: what the first stage made of the views is all there is. + if solved is None: + solved, complete = rough, False + else: + solved = _solve_pinhole(views, size) + if solved is None: + raise CalibrationError(_UNSOLVED) + rms, K, dist, rvecs, tvecs = solved + camera = Intrinsics( + np.asarray(K, dtype=np.float64), np.asarray(dist, dtype=np.float64).reshape(-1), size, {}, model + ) + poses = [(np.asarray(rvec).reshape(3), np.asarray(tvec).reshape(3)) for rvec, tvec in zip(rvecs, tvecs)] + per_view = [] + for view, (rvec, tvec) in zip(views, poses): + # Measured as the solver measured it, every corner counted wherever the model puts it. + residual = ( + view.image_points.astype(np.float64) - posed_projection(view.object_points, rvec, tvec, camera)[0] + ) + per_view.append(float(np.linalg.norm(residual) / np.sqrt(len(residual)))) + return _Fit(float(rms), camera, poses, per_view, _focal_uncertainty(views, camera, poses), complete) + + +def _largest_field_angle_deg(views: Sequence[BoardView], camera: Intrinsics) -> float | None: + """The furthest from the optical axis that a corner of the views looks under the solved camera, in + degrees; None when the camera gives none of them a direction.""" + angles = np.concatenate([field_angle_deg(view.image_points, camera) for view in views]) + angles = angles[np.isfinite(angles)] + return float(angles.max()) if angles.size else None + + +def solve_intrinsics( + views: Sequence[BoardView], + image_size_wh: tuple[int, int], + spec: BoardSpec, + *, + model: str = PINHOLE, + outlier_threshold_px: float = 1.5, +) -> dict[str, Any]: + """Solve a camera's intrinsics from board views; returns the record an intrinsics file stores. + + ``model`` is the lens model solved for, ``files.PINHOLE`` or ``files.FISHEYE``. A view is used when its + model's solver can use it (``usable_for``). A view whose own RMS after a solve exceeds ``max(2 * median, + outlier_threshold_px)`` is dropped and the camera solved again: once under the pinhole model, and under + the fisheye one until the views left agree, ``_OUTLIER_ROUNDS`` times at most. Fewer than the model's + ``MIN_VIEWS`` usable views, before that or after its first pass, is a ``CalibrationError``. + + Beside the solve, the record says how well the views used pin it, for ``grading``: ``corner_coverage`` + (see ``corner_coverage``), ``tilt_spread`` (``tilt_spread`` for the pinhole model, ``posed_tilt_spread`` + for the fisheye one), ``focal_uncertainty``, the relative standard deviation of the focal lengths, None + when the views do not determine the camera at all, ``max_field_angle_deg``, how far from the optical + axis the furthest corner used was seen, beyond which the model is an extrapolation, + ``picture_corner_angle_deg``, that angle for the picture's own furthest corner, None when the model + gives a corner of the picture no direction, and ``field_limit_deg``, how far from the axis the model + describes a lens at all (``camera_model.field_limit_deg``): at 90 degrees a corner without a direction + lies past what the model can describe, and under 90 the model's curve turns short of it. + """ + # Chosen by the caller's code, not typed by an operator, so a wrong one is a plain error. + if model not in MIN_VIEWS: + raise ValueError(f"model must be {PINHOLE} or {FISHEYE}") + size = (int(image_size_wh[0]), int(image_size_wh[1])) + least = MIN_VIEWS[model] + # A view whose corners lie along one line has no homography, and would wreck the first solve; one with + # too few corners for the model's solver stops it outright. + usable = [view for view in views if usable_for(view, model)] + skipped = len(views) - len(usable) + if len(usable) < least: + raise CalibrationError( + f"Only {len(usable)} usable views of the board were found and at least {least} are needed. " + "Record again, showing the board for longer and from more angles." + ) + kept = usable + fit = _calibrate(kept, size, model) + for dropped_before in range(_OUTLIER_ROUNDS[model]): + # The median scales the limit to this camera; the floor keeps a tight solve from dropping good views. + limit = max(2.0 * float(np.median(fit.per_view)), outlier_threshold_px) + agreeing = [view for view, error in zip(kept, fit.per_view) if error <= limit] + if len(agreeing) == len(kept): + break + if len(agreeing) < least: + # A later pass is there to drop a wild view the pass before could not see. Where the views left + # agree on nothing, as those of a board held flat-on do, it would peel them away one pass after + # another: the solve then stands as the first pass left it, for the grade to judge. + if dropped_before: + break + raise CalibrationError( + f"Only {len(agreeing)} views agreed with each other and at least {least} are needed. " + "Record again, moving slowly so the board stays sharp." + ) + kept = agreeing + fit = _calibrate(kept, size, model) + # A fit that stopped at its first stage has told which views to drop, and is no camera to hand on. + if not fit.complete: + raise CalibrationError(_UNSOLVED) + removed = len(usable) - len(kept) + + # Through a fisheye lens the corners alone do not show tilt, so the solve's own poses are measured. + tilt = posed_tilt_spread(kept, fit.poses) if model == FISHEYE else tilt_spread(kept) + return { + "model": model, + "distortion_model": DISTORTION_NAMES[model], + "image_size_wh": list(size), + **spec.to_record(), + "max_corners_per_view": spec.max_corners, + "num_views_used": len(kept), + "num_views_skipped": skipped, + "num_views_outlier_removed": removed, + "rms_calibrate_camera": fit.rms, + "per_image_rms_px": [ + {"frame": view.frame, "rms_px": error, "n_corners": view.corners} + for view, error in zip(kept, fit.per_view) + ], + # Measured over the views the solve kept, which are the ones it rests on. + "corner_coverage": corner_coverage(kept, size), + "tilt_spread": tilt, + "focal_uncertainty": fit.focal_uncertainty, + "max_field_angle_deg": _largest_field_angle_deg(kept, fit.camera), + "picture_corner_angle_deg": picture_corner_angle_deg(fit.camera), + "field_limit_deg": field_limit_deg(fit.camera), + "K": fit.camera.K.tolist(), + "dist_coeffs": fit.camera.dist.tolist(), + } diff --git a/examples/egocap/recording/egocap/calibration/rectification_files.py b/examples/egocap/recording/egocap/calibration/rectification_files.py new file mode 100644 index 0000000000..d1ac2fd56a --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/rectification_files.py @@ -0,0 +1,456 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The files that carry a station's rectification from one program to the next, each named and read here alone. + +The plan is the operator's choice for each camera role, in the station's calibration directory: the page writes +it and the launcher reads it at each start. The streams state is what the launcher did to each bridged stream in +one run, named to the backend in the environment. The record says what was done to a take's pictures: a session +whose video was corrected carries one, and an offline corrected copy of a take keeps its own. Errors here name +a file, never a directory: they are shown to an operator. +""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Any + +from egocap.recording.episode_layout import MANIFEST_DIR, SESSION_CONFIG_FILE + +from .files import ( + ROLE_INTRINSICS, + ROLE_LENS_INTRINSICS, + CalibrationFileError, + Intrinsics, + absent, + intrinsics_from_record, + load_intrinsics, + read_json_object, + write_json, +) + +#: Where the plan lies under a station's calibration directory, and the only layout of it. +PLAN_DIR = "rectification" +PLAN_FILE = "plan.json" +PLAN_VERSION = 1 + +#: The environment variable the launcher names its streams state file in, for the backend it starts. +STREAMS_STATE_ENV = "EGOCAP_STREAMS_STATE" +#: The only layout of the streams state. +STREAMS_STATE_VERSION = 1 + +#: The record of what was done to each camera's video: in a session whose video the capture stack corrected +#: while it was recorded, and inside an offline corrected copy of a take. One name, so one reader finds either. +RECORD_NAME = "rectification.json" +#: The layout of that record: ``{"version": ..., "cameras": {camera: what was done}}``. +RECORD_VERSION = 1 + +RECORD_UNREADABLE = ( + f"{RECORD_NAME} of this take cannot be read, so whether its video was recorded corrected is unknown" +) +#: Why a lens is not solved from a take recorded corrected, whichever program is asked to. +TAKE_RECORDED_CORRECTED = ( + "this take's video was recorded already corrected, so the lens cannot be calibrated from it; record a take " + "with the capture stack started without rectification" +) +#: Why a take is not read as recorded as received when its session holds what only a corrected run leaves. +RECORD_MISSING = ( + f"{RECORD_NAME} of this take is missing though its session holds the lens file of a corrected run, so " + "whether its video was recorded corrected is unknown" +) +#: Why a take that has left its session is not worked on by a program that must know how its video was recorded. +TAKE_OUTSIDE_SESSION = ( + "this take is not in the session it was recorded in, so whether its video was recorded corrected is unknown" +) + + +class PlanFileError(CalibrationFileError): + """A plan file that is there and cannot be understood. The message is one sentence for an operator and + names the file by its base name.""" + + +class TakeRecordError(ValueError): + """A take's record of its rectification that cannot be read, or that lists a camera as corrected without + describing the corrected camera. The message is one sentence for an operator.""" + + +# --- the plan -------------------------------------------------------------------------------------------------- + + +def plan_path(directory: Path) -> Path: + """Where the plan file lies under the calibration directory ``directory``.""" + return Path(directory) / PLAN_DIR / PLAN_FILE + + +def _is_version(stated: Any, version: int) -> bool: + """Whether a file states exactly this layout version. True and 1.0 equal 1 to Python and are not it: a file + that says either was not written by a program that knows the layout.""" + return type(stated) is int and stated == version + + +def read_plan(directory: Path) -> dict[str, dict[str, Any]]: + """Every camera role's entry of a station's plan, by role, as the file states it; none without a file. + + An entry says whether the role is corrected (``enabled``, a real true or false) and holds the geometry keys + ``rectify.OutputGeometry.from_record`` reads. A role written as null has no entry. ``PlanFileError`` for a + file that is there and cannot be understood: starting or listing without it would pass a station whose + operator chose a correction for one that corrects nothing. + """ + path = plan_path(directory) + # Only a plan that is not there means "correct nothing". + if absent(path): + return {} + try: + record = read_json_object(path) + except CalibrationFileError as unusable: + raise PlanFileError(str(unusable)) from None + cameras = record.get("cameras") + # Another version may give the same keys another meaning, so it is not read as this one. + if not _is_version(record.get("version"), PLAN_VERSION) or not isinstance(cameras, dict): + raise PlanFileError(f"{path.name} is not a version {PLAN_VERSION} plan with a cameras object") + entries: dict[str, dict[str, Any]] = {} + for role, entry in cameras.items(): + # Null is how an entry is taken away. + if entry is None: + continue + # Text such as "false" would pass for switched on, so only a real true or false is taken. + if not isinstance(entry, dict) or not isinstance(entry.get("enabled"), bool): + raise PlanFileError(f"{path.name} does not say whether its entry for {role} is enabled") + entries[role] = entry + return entries + + +def write_plan(directory: Path, cameras: Mapping[str, Mapping[str, Any]]) -> None: + """Write every role's entry as the station's plan file, whole and atomically; the launcher reads it at the + next start. A role without an entry is not corrected.""" + path = plan_path(directory) + # A station that never saved a plan has no directory for one yet. + path.parent.mkdir(parents=True, exist_ok=True) + write_json(path, {"version": PLAN_VERSION, "cameras": dict(cameras)}) + + +# --- the streams state ----------------------------------------------------------------------------------------- + + +def _corrected_camera(record: Mapping[str, Any]) -> Intrinsics: + """The ideal pinhole camera a rectification's record describes; ``CalibrationFileError`` when it describes + none.""" + # A plan's record reads as an intrinsics file of the corrected picture: no distortion, the output size. + return intrinsics_from_record(dict(record), RECORD_NAME) + + +@dataclass(frozen=True) +class CameraStream: + """One camera's stream as the launcher started it. A fact the file does not state usably is None.""" + + #: The camera's name as the capture server offers it, which is also what its video is recorded under. + camera: str + #: The bridge's own name for the stream. + stream: str | None + #: The camera role the launcher took the stream for, whose intrinsics and plan it used. + role: str | None + #: The size of the picture the bridge receives. + source_size_wh: tuple[int, int] | None + #: The whole number the bridge divides a picture by before publishing it: the picture it receives, or for + #: a corrected stream the picture its table makes, which is the plan's oversample. + divisor: int | None + #: The size of the picture the bridge publishes, which is what is shown and recorded. + published_size_wh: tuple[int, int] | None + #: What was applied to the stream: the plan's record, with the table file's facts. None when the stream + #: is published as it is received. + rectification: Mapping[str, Any] | None + + @property + def rectified(self) -> bool: + """Whether this camera's video is corrected before it is published.""" + return self.rectification is not None + + +@dataclass(frozen=True) +class StreamsState: + """Every camera stream the launcher reported for one run, by camera name. Empty when it reported none.""" + + cameras: Mapping[str, CameraStream] = field(default_factory=dict) + #: The file this was read from; None when the launcher named none. + path: Path | None = None + #: Whether the run was started with rectification switched off, which is not the plan asking for none: + #: started the same way again, such a run applies no saved choice either. + no_rectify: bool = False + + def camera(self, name: str | None) -> CameraStream | None: + """The stream of the camera ``name``, or None when the launcher reported none for it.""" + return None if name is None else self.cameras.get(name) + + def rectified(self, name: str | None) -> bool: + """Whether the video of the camera ``name`` is being corrected in this run.""" + stream = self.camera(name) + return stream is not None and stream.rectified + + def stamp(self, name: str | None) -> dict[str, Any] | None: + """What a lens calibration solved from this camera's published picture says of the stream, as the + ``stream`` entry of its file: the divisor and the size the bridge receives. None for a camera the + launcher did not report, or reported without them, and for one whose video is corrected: its + published picture is not the received one divided, and its divisor is the plan's oversample.""" + stream = self.camera(name) + if stream is None or stream.rectified or stream.divisor is None or stream.source_size_wh is None: + return None + return {"divisor": stream.divisor, "source_size_wh": list(stream.source_size_wh)} + + def corrected_camera(self, name: str | None) -> Intrinsics | None: + """The ideal pinhole camera the corrected video of ``name`` is a picture of; None when its video is not + corrected in this run. ``CalibrationFileError`` when the launcher's record does not describe one.""" + stream = self.camera(name) + if stream is None or stream.rectification is None: + return None + return _corrected_camera(stream.rectification) + + def session_record(self) -> dict[str, Any] | None: + """What a session recorded in this run says was done to its pictures: each corrected camera with the + record of its rectification. None when no camera is corrected, and a session then carries no record.""" + corrected = {name: dict(stream.rectification) for name, stream in self.cameras.items() if stream.rectified} + return {"version": RECORD_VERSION, "cameras": corrected} if corrected else None + + +def declared_divisor(intrinsics: Intrinsics) -> Any: + """The box downscale a calibration's ``stream`` stamp declares between its own picture and the picture the + bridge receives, as the file states it; 1 when the file has no stamp or its stamp names none. + + Handed to the planner as it is. A stamp that declares nonsense, null included, is refused there and never + read as no stamp: every program that plans from the file then says the same of it. + """ + stamp = intrinsics.record.get("stream") + return stamp.get("divisor", 1) if isinstance(stamp, dict) else 1 + + +def _size(value: Any) -> tuple[int, int] | None: + """A picture size a file states, as two positive whole numbers; None for anything else.""" + # A bool is an int to Python, and no picture is True pixels wide. + sized = isinstance(value, list) and len(value) == 2 and all(type(n) is int and n > 0 for n in value) + return (value[0], value[1]) if sized else None + + +def _stated_size(size: tuple[int, int] | None) -> list[int] | None: + """A picture size as the file states it.""" + return None if size is None else list(size) + + +def _camera_stream(name: str, entry: Mapping[str, Any]) -> CameraStream: + """One camera's entry of the streams state; a fact that is not of its expected shape is left out.""" + stream, role, divisor = entry.get("stream"), entry.get("role"), entry.get("divisor") + rectification = entry.get("rectification") + return CameraStream( + camera=name, + stream=stream if isinstance(stream, str) else None, + role=role if isinstance(role, str) else None, + source_size_wh=_size(entry.get("source_size_wh")), + divisor=divisor if type(divisor) is int and divisor > 0 else None, + published_size_wh=_size(entry.get("published_size_wh")), + rectification=None if rectification is None else dict(rectification), + ) + + +def _stream_entry(stream: CameraStream) -> dict[str, Any]: + """One camera's stream as its entry of the streams state.""" + return { + "stream": stream.stream, + "role": stream.role, + "source_size_wh": _stated_size(stream.source_size_wh), + "divisor": stream.divisor, + "published_size_wh": _stated_size(stream.published_size_wh), + "rectification": None if stream.rectification is None else dict(stream.rectification), + } + + +def write_streams_state(path: Path, cameras: Iterable[CameraStream], *, no_rectify: bool) -> None: + """Write what a run publishes each bridged camera as, keyed by the camera's name, atomically. + + ``no_rectify`` says the run was started with rectification switched off, which ``StreamsState`` keeps + apart from a plan that asked for none. + """ + record = { + "version": STREAMS_STATE_VERSION, + # A station's own local time, with its offset so the moment is not ambiguous. + "written_at": datetime.now().astimezone().isoformat(timespec="seconds"), + "no_rectify": bool(no_rectify), + "cameras": {stream.camera: _stream_entry(stream) for stream in cameras}, + } + write_json(Path(path), record) + + +def read_streams_state(path: Path) -> StreamsState: + """The streams state the launcher wrote at ``path``. + + ``CalibrationFileError`` for a file that is missing, damaged or of another layout; what a run is then + taken for is its reader's to decide. A camera's fact that is not of its shape is left out and the camera + stays known. + """ + path = Path(path) + record = read_json_object(path) + if not _is_version(record.get("version"), STREAMS_STATE_VERSION): + raise CalibrationFileError(f"{path.name} is not version {STREAMS_STATE_VERSION} of the streams state") + cameras = record.get("cameras") + if not isinstance(cameras, dict): + raise CalibrationFileError(f"{path.name} does not list its cameras") + for camera, entry in cameras.items(): + # A rectification that is neither absent nor an object says something was applied and not what: taken + # for "not corrected", the lens could be calibrated from corrected video. + applied = entry.get("rectification") if isinstance(entry, dict) else None + if not isinstance(entry, dict) or not (applied is None or isinstance(applied, dict)): + raise CalibrationFileError(f"{path.name} does not describe the stream of camera {camera!r}") + return StreamsState( + cameras={camera: _camera_stream(camera, entry) for camera, entry in cameras.items()}, + path=path, + # Only a real true: a run is not taken for one with rectification switched off on a word that is not one. + no_rectify=record.get("no_rectify") is True, + ) + + +# --- what a take says was done to its video -------------------------------------------------------------------- + + +def _marked(directory: Path) -> bool: + """Whether a directory carries the marks the recorder leaves in a session it wrote.""" + # os.path answers False for what it cannot look at, where Path can raise: unmarked is the careful reading. + return os.path.isdir(directory / MANIFEST_DIR) or os.path.isfile(directory / SESSION_CONFIG_FILE) + + +def take_sessions(episode_dir: Path) -> list[Path]: + """The directories that are a take's session, the one to read first leading. + + Always the directory the episode really lies in. An episode can also be a link, inside its session, to + storage elsewhere: the directory holding the link is then the session the recorder wrote, with its + calibration copies, and is one too when it carries a session's marks. + """ + episode_dir = Path(episode_dir) + real = episode_dir.resolve().parent + # The path made absolute but not resolved: its last component is the link itself, not where it leads. + named = episode_dir.absolute().parent.resolve() + return [named, real] if named != real and _marked(named) else [real] + + +def lies_in_recorded_session(episode_dir: Path) -> bool: + """Whether a take lies in a session the recorder wrote: a directory that is its session carries the marks. + + The record of a run whose video was corrected is kept in the session, beside the episode. A take copied + or moved without its session, or named by where a link in its session leads, has left that record behind. + """ + return any(_marked(session) for session in take_sessions(episode_dir)) + + +def _record_holders(episode_dir: Path) -> tuple[Path, ...]: + """Where a take's record of its rectification is looked for: its session directories, then the episode.""" + return (*take_sessions(episode_dir), Path(episode_dir)) + + +def knows_how_recorded(episode_dir: Path) -> bool: + """Whether a take can say if its video was recorded corrected: it lies in its recorded session, or a + record stands where one is looked for, as inside an offline corrected copy. + + ``recorded_rectification`` answers "as received" for a take that has neither, which is right for a take + read where it was recorded. A program handed a take from anywhere asks here first, and takes a no for + ``TAKE_OUTSIDE_SESSION`` unless whoever runs it states how the video was recorded. + """ + if lies_in_recorded_session(episode_dir): + return True + return any(not absent(holder / RECORD_NAME) for holder in _record_holders(episode_dir)) + + +def recorded_rectification(episode_dir: Path, camera: str) -> dict[str, Any] | None: + """What a take's own records say was done to the video of ``camera`` when it was recorded: the record of + its rectification, or None when the video was recorded as received. + + The recorder copies the run's record into the take's session; an offline corrected copy of a take keeps + its own inside the episode. ``TakeRecordError`` when a record is there and cannot be read, or is missing + from a session that holds the lens file of a corrected run: what it says is then unknown for every + camera, and unknown is never taken for "as received". Reads files. + """ + applied: dict[str, Any] | None = None + for holder in _record_holders(episode_dir): + record = holder / RECORD_NAME + # Only a record that is not there says nothing. A directory, a link that leads nowhere or a file out of + # reach is a record that cannot be read: the read below fails on it. + if absent(record): + # A run leaves a lens file under its lens name only where it corrected that camera's video, and + # then leaves the record too. One without the other is a session that lost its record. + if any(not absent(holder / name) for name in ROLE_LENS_INTRINSICS.values()): + raise TakeRecordError(RECORD_MISSING) + continue + try: + cameras = read_json_object(record).get("cameras") + except CalibrationFileError: + cameras = None + if not isinstance(cameras, dict): + raise TakeRecordError(RECORD_UNREADABLE) + # The first record that lists the camera as corrected stands; the others are still read, so that an + # unreadable one is refused whichever comes first. + if applied is not None or camera not in cameras: + continue + entry = cameras[camera] + # An offline copy lists the cameras it left alone too, and says so; anything else listed is corrected. + if isinstance(entry, dict) and entry.get("rectified") is False: + continue + applied = dict(entry) if isinstance(entry, dict) else {} + return applied + + +@dataclass(frozen=True) +class TakeCamera: + """The camera a take's pictures are pictures of.""" + + intrinsics: Intrinsics + #: Whether the take's video was recorded corrected, so ``intrinsics`` is the ideal pinhole camera of the + #: corrected picture and not the lens. + rectified: bool + + +def lens_file_in(directory: Path, role: str) -> Path | None: + """The file that holds a role's lens calibration in a session or in a station's calibration directory; + None when the directory holds none. + + A run that corrects a camera's video leaves the lens in its sessions under the role's lens name, because + the role's own intrinsics file there describes the corrected picture. Everywhere else, and in a session + written before that layout, the role's own file is the lens. A directory that cannot be looked into is + answered with the role's own file, which is the name every such directory has: reading it then fails + under a name the operator knows. + """ + lens, own = Path(directory) / ROLE_LENS_INTRINSICS[role], Path(directory) / ROLE_INTRINSICS[role] + # Whatever stands under the lens name is the lens, a link that leads nowhere included. + if os.path.lexists(lens): + return lens + return None if absent(own) else own + + +def _lens_beside(lens_file: Path) -> Path: + """The file to read a lens from when a caller names ``lens_file``: the role's lens file beside it where + one stands, since a role's own intrinsics file in such a directory is the corrected picture's camera.""" + for role, name in ROLE_INTRINSICS.items(): + if lens_file.name == name: + return lens_file_in(lens_file.parent, role) or lens_file + return lens_file + + +def camera_as_recorded(episode_dir: Path, camera: str, lens_file: Path) -> TakeCamera: + """The camera as a take saw it: the corrected pinhole camera when the take's records list ``camera`` as + corrected, else the lens calibration, which is read only then. + + The corrected camera is the take's record of it, which is also what the role's own intrinsics file holds + in the session of a corrected run. The lens is read from ``lens_file``, or from the role's lens file + beside it when ``lens_file`` is a role's own file in a directory laid out as such a session. + + Everything that projects into a take's pictures or poses a board in them asks here, so none of it applies + a lens to video that was already corrected. ``CalibrationFileError`` when the lens file cannot be read; + ``TakeRecordError`` when the take's record cannot be read or does not describe the corrected camera. + Reads files. + """ + applied = recorded_rectification(episode_dir, camera) + if applied is None: + return TakeCamera(load_intrinsics(_lens_beside(Path(lens_file))), False) + try: + return TakeCamera(_corrected_camera(applied), True) + except CalibrationFileError as unusable: + raise TakeRecordError(f"this take's video was recorded corrected, and {unusable}") from None diff --git a/examples/egocap/recording/egocap/calibration/rectify.py b/examples/egocap/recording/egocap/calibration/rectify.py new file mode 100644 index 0000000000..82f8a3f64b --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/rectify.py @@ -0,0 +1,1035 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Planning the correction of a camera's video into the picture of an ideal pinhole camera. + +A plan is made from a camera's intrinsics, the size of the picture to correct and an explicit output geometry. +It holds the output camera matrix, the maps from each output pixel to the source position it samples, and the +figures that describe the result. The maps are what the remap table file carries to the GPU step, and what a +preview or an offline copy applies here. The view is never searched for and nothing falls back. + +Where the corrected picture is much smaller than the camera's, the maps are made an oversample times larger a +side than the picture asked for, and a box filter shrinks what they give to that picture: the camera bridge's +own downscale, which runs after its steps. The picture asked for is the one published and recorded. + +A calibration or a geometry that would bake an error into video is refused, never adjusted: raw video can +always be corrected later, a wrongly corrected video cannot be undone. +""" + +from __future__ import annotations + +import hashlib +import math +import os +import struct +import uuid +from collections.abc import Mapping +from dataclasses import dataclass, replace +from functools import cached_property +from itertools import groupby +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from .camera_model import field_limit_deg, normalised_rays +from .files import FISHEYE, PINHOLE, CalibrationFileError, Intrinsics, intrinsics_from_record, intrinsics_identity + +#: A solve at or above this reprojection RMS is not rectified with: its error would be in every frame. +MAX_RECTIFICATION_RMS_PX = 0.5 +#: A lens that moves three quarters of its picture less than this, for every 640 pixels of the picture's longer +#: side, was almost certainly solved on video that was already corrected. Measured at 640 pixels wide: 99.4% of +#: solves of corrected video, in both models at up to 0.3 px corner noise, stay under it, half of them under +#: 0.4 px; a -0.05 radial lens at 640x360 gives 4.7. The distance is in pixels, so it grows with the picture. +MIN_LENS_DISPLACEMENT_PX = 4.0 +#: How far, as a share of the output's width or height, its principal point may sit from its centre. Measured at +#: balance 0 on fisheyes whose axis is 5% of the picture off centre: 0.135 at 130 by 100 degrees, 0.19 at 140. +MAX_PRINCIPAL_POINT_OFFSET = 0.15 +#: Source pixels per output pixel above which one bilinear pass skips source pixels. Measured: past 2, stripes four +#: source pixels a period come out as moire at 80% of their contrast. +ALIASING_RATIO = 2.0 +#: The largest side of the maps planned for: they and their checks take about a hundred bytes per pixel. +MAX_OUTPUT_SIDE_PX = 4096 +#: The largest oversample: the camera bridge's box filter divides a picture by at most this. +MAX_OVERSAMPLE = 8 +#: The largest source side OpenCV's remap takes: it addresses the source in 16 bits. +MAX_SOURCE_SIDE_PX = 32766 + +#: The record key that says a solve was made with a ChArUco board. +_BOARD_KEY = "charuco_squares" +#: Pixels a side of the grid the lens's displacement is measured on; the picture's corners are on it. +_DISPLACEMENT_GRID = 33 +#: The longer side, in pixels, of the pictures ``MIN_LENS_DISPLACEMENT_PX`` was measured at. +_DISPLACEMENT_MEASURED_AT_PX = 640 +#: How far past what a calibration saw of its lens a corrected picture may look before the plan says so, in +#: degrees: the angle a solve records is that of one corner, and the lens model does not end at it. +_REACH_MARGIN_DEG = 1.0 +#: The record key that says how far from the optical axis a solve saw the board, in degrees. +_SEEN_KEY = "max_field_angle_deg" +#: Where a map entry that names no source pixel is sent before OpenCV applies it: wholly in the border. +_NO_SOURCE = -2.0 +_OUTLINE_BGR = (0, 255, 0) +#: Fractional bits of the outline's coordinates, so its curve is drawn to an eighth of a pixel. +_OUTLINE_SHIFT = 3 + +#: The remap table file: a little-endian header, then one ``(sx, sy)`` float32 pair per output pixel, row by row. +_TABLE_MAGIC = b"ICRMAP01" +#: Magic, header size, source width and height, output width and height, flags, payload hash, reserved. +_TABLE_HEADER = struct.Struct("<8s6I2Q") +#: The largest width or height a table may name: up to here a float32 holds every pixel position exactly. +_TABLE_MAX_SIDE = 1 << 24 +_FNV_OFFSET = 0xCBF29CE484222325 +_FNV_PRIME = 0x100000001B3 +_U64 = (1 << 64) - 1 +#: Bytes hashed in one vectorised step. +_FNV_BLOCK = 1 << 17 +#: ``_FNV_POWERS[i]`` is the prime to the power ``i + 1``, modulo 2**64. +_FNV_POWERS = np.cumprod(np.full(_FNV_BLOCK, _FNV_PRIME, dtype=np.uint64)) + + +class RectificationError(RuntimeError): + """A calibration, a geometry or a frame that cannot be rectified; the message is fit to show an operator.""" + + +class RemapTableError(RectificationError): + """A remap table file that cannot be written or is refused when read; the message names the file.""" + + +# --- the geometry asked for ------------------------------------------------------------------------------------ + + +@dataclass(frozen=True, eq=False) +class OutputGeometry: + """The corrected picture that is asked for: its size, and which part of the lens's view it shows.""" + + #: Width and height of the corrected picture as it is published and recorded, both even. + size_wh: tuple[int, int] + #: 0 keeps only what the source can supply everywhere, 1 keeps the source's whole field of view. + balance: float = 0.0 + #: Above 1 widens the view chosen from ``balance``, below 1 narrows it. + fov_scale: float = 1.0 + #: Whether output pixels with no source pixel are accepted; they are filled with black. + allow_border: bool = False + #: The camera matrix of the corrected picture stated outright. ``balance`` and ``fov_scale`` are then not + #: used. + K: np.ndarray | None = None + #: How many times larger a side the correction is made than ``size_wh`` before a box filter shrinks it to + #: that size. One bilinear pass skips source pixels where it reduces the camera's picture by much; made + #: larger first, it does not. + oversample: int = 1 + + @classmethod + def from_record(cls, record: Mapping[str, Any]) -> OutputGeometry: + """The geometry a camera's entry of the station's plan file states; ``plan_rectification`` checks it.""" + # Anything that is not an object has no keys to read, and would fail far from this sentence. + if not isinstance(record, Mapping): + raise RectificationError("a camera's rectification choice must be an object") + return cls( + size_wh=record.get("output_size_wh"), + balance=record.get("balance", 0.0), + fov_scale=record.get("fov_scale", 1.0), + allow_border=record.get("allow_border", False), + K=record.get("K"), + oversample=record.get("oversample", 1), + ) + + def record(self) -> dict[str, Any]: + """This geometry under the keys of the station's plan file, as JSON values.""" + geometry = checked_geometry(self) + return { + "output_size_wh": list(geometry.size_wh), + "balance": geometry.balance, + "fov_scale": geometry.fov_scale, + "allow_border": geometry.allow_border, + "K": None if geometry.K is None else geometry.K.tolist(), + "oversample": geometry.oversample, + } + + +def _number(value: Any) -> float | None: + """``value`` as a float when it is a real, finite number; a bool is not one.""" + real = isinstance(value, (int, float, np.integer, np.floating)) and not isinstance(value, (bool, np.bool_)) + if not real: + return None + try: + number = float(value) + except OverflowError: + # JSON can carry a whole number that no float can hold. + return None + return number if math.isfinite(number) else None + + +def _size(value: Any, what: str, largest: int) -> tuple[int, int]: + """A picture size as two positive whole numbers no larger than ``largest``; anything else is refused.""" + try: + size = tuple(value) + except TypeError: + # A size that is no sequence at all (a number, nothing) is answered like one of the wrong length. + size = () + # A bool is an int to Python, and OpenCV would truncate a fractional size without saying so. + whole = all(isinstance(n, (int, np.integer)) and not isinstance(n, (bool, np.bool_)) and n > 0 for n in size) + if len(size) != 2 or not whole: + raise RectificationError(f"the {what} size must be two positive whole numbers of pixels") + # A size past this is a slip of the hand, and its maps would not fit in memory. + if max(size) > largest: + raise RectificationError(f"the {what} size may be at most {largest} pixels a side") + return int(size[0]), int(size[1]) + + +def _stated_matrix(value: Any) -> np.ndarray: + """An output camera matrix stated outright, refused unless it is an ideal pinhole camera's.""" + wrong = "the output camera matrix must be 3x3 with positive focal lengths, no skew and a last row of 0 0 1" + try: + matrix = np.array(value, dtype=np.float64) + except (TypeError, ValueError, OverflowError): + # Text, an object, rows of unequal length, or a whole number no float can hold. + raise RectificationError(wrong) from None + if matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)): + raise RectificationError(wrong) + # Skew and a perspective row are what no reader of the recorded matrix expects a picture to have. + pinhole = matrix[0, 0] > 0 and matrix[1, 1] > 0 and matrix[0, 1] == 0 and matrix[1, 0] == 0 + if not pinhole or matrix[2].tolist() != [0.0, 0.0, 1.0]: + raise RectificationError(wrong) + matrix.setflags(write=False) + return matrix + + +def checked_geometry(geometry: OutputGeometry) -> OutputGeometry: + """``geometry`` with every field checked and in its plain type; ``RectificationError`` says what is wrong.""" + size = _size(geometry.size_wh, "output", MAX_OUTPUT_SIDE_PX) + # The GPU step writes 4:2:0 video, whose chroma planes are half the size in each direction. + if size[0] % 2 or size[1] % 2: + raise RectificationError( + f"the output size must be even in both directions, and {size[0]}x{size[1]} is not" + ) + balance, fov_scale = _number(geometry.balance), _number(geometry.fov_scale) + if balance is None or not 0.0 <= balance <= 1.0: + raise RectificationError( + "the balance must be a number from 0 (only what the camera supplies) to 1 (the camera's whole view)" + ) + if fov_scale is None or fov_scale <= 0.0: + raise RectificationError("the field-of-view scale must be a number above 0") + # A flag read as true because it was the text "false" would let black borders into a recording. + if not isinstance(geometry.allow_border, (bool, np.bool_)): + raise RectificationError("allowing borders must be true or false") + matrix = None if geometry.K is None else _stated_matrix(geometry.K) + oversample = geometry.oversample + whole = isinstance(oversample, (int, np.integer)) and not isinstance(oversample, (bool, np.bool_)) + # The bridge's box filter divides by a whole number, and by no more than this. + if not whole or not 1 <= oversample <= MAX_OVERSAMPLE: + raise RectificationError(f"the oversample must be a whole number from 1 to {MAX_OVERSAMPLE}") + # The maps are made at the oversample times the size, and it is their side that is bounded. + if max(size) * oversample > MAX_OUTPUT_SIDE_PX: + raise RectificationError( + f"the output size times the oversample may be at most {MAX_OUTPUT_SIDE_PX} pixels a side, and " + f"{size[0]}x{size[1]} times {oversample} is more" + ) + return OutputGeometry(size, balance, fov_scale, bool(geometry.allow_border), matrix, int(oversample)) + + +# --- the gates on a calibration -------------------------------------------------------------------------------- + + +def _rays(pixels: np.ndarray, camera: Intrinsics) -> tuple[np.ndarray, np.ndarray]: + """Where each pixel looks, as normalised image coordinates, and whether the lens model reaches the pixel. + + The camera model's own inverse, which has no direction for a pixel past the radius where the distortion + turns over, or at 90 degrees and more from a fisheye's axis. + """ + rays = normalised_rays(pixels, camera) + return rays, np.isfinite(rays).all(axis=1) + + +def _lens_displacement_px(camera: Intrinsics) -> float | None: + """How far the lens moves points from where a lens without distortion would put them: the distance three + quarters of the picture stay under. + + Measured where the model can be followed, on a grid over the picture; None when that is nowhere. It asks + how much the lens bends light, not how large its coefficients are: an ideal fisheye has none. The largest + distance is not used: at the corners, past the board, a solve of corrected video extrapolates to tens of + pixels, as much as a real lens. + """ + width, height = camera.image_size_wh + columns, rows = np.meshgrid( + np.linspace(0.0, width - 1.0, _DISPLACEMENT_GRID), np.linspace(0.0, height - 1.0, _DISPLACEMENT_GRID) + ) + pixels = np.stack([columns.ravel(), rows.ravel()], axis=1) + rays, reached = _rays(pixels, camera) + if not reached.any(): + return None + focal, centre = np.diag(camera.K)[:2], camera.K[:2, 2] + moved = np.linalg.norm(rays[reached] * focal + centre - pixels[reached], axis=1) + return float(np.percentile(moved, 75)) + + +def _provenance_problems(record: Mapping[str, Any]) -> list[str]: + """What a calibration record fails to say about how well, with what and for which lens model it was made.""" + problems: list[str] = [] + # Only a solve that states how well it fitted can be judged at all. + rms = _number(record.get("rms_calibrate_camera")) + if rms is None or rms < 0: + problems.append("the calibration does not record its solve error, so its quality is unknown") + elif rms >= MAX_RECTIFICATION_RMS_PX: + problems.append( + f"the solve error is {rms:.2f} px, and rectification needs one under {MAX_RECTIFICATION_RMS_PX:g} px" + ) + # A file without its board was made some other way or edited by hand: nothing vouches for it. + if not record.get(_BOARD_KEY): + problems.append("the calibration does not record a ChArUco board, so how it was made is unknown") + # The same numbers mean different lenses in the two models, so a guess from their count is not accepted. + if record.get("model") not in (PINHOLE, FISHEYE): + problems.append("the calibration does not say which lens model it was solved with") + return problems + + +def _lens_problems(camera: Intrinsics) -> list[str]: + """Why a camera's solved lens must not drive rectification, whatever its record says of how it was made.""" + # OpenCV answers a camera without focal lengths with numbers, not with an error. + if not (camera.K[0, 0] > 0 and camera.K[1, 1] > 0): + return ["the calibration's focal lengths are not positive"] + moved = _lens_displacement_px(camera) + if moved is None: + return ["the calibration's lens model does not hold anywhere in its picture"] + # The same lens moves a point more pixels in a larger picture, so the limit is for this picture's size. + limit = MIN_LENS_DISPLACEMENT_PX * max(camera.image_size_wh) / _DISPLACEMENT_MEASURED_AT_PX + # A plan's own checks cannot see this: correcting corrected video a second time looks sound and bends it. + if moved < limit: + return [ + f"the lens model moves three quarters of the picture less than {moved:.1f} px from where a lens " + f"without distortion would put it, and a lens to correct moves it {limit:g} px or more at this " + "picture size: the calibration was probably made on video that was already corrected, and a lens " + "that bends this little needs no correcting" + ] + return [] + + +def rectification_problems(record: Mapping[str, Any]) -> list[str]: + """Why an intrinsics file's record must not drive rectification; empty means it may.""" + problems = _provenance_problems(record) + try: + camera = intrinsics_from_record(dict(record), "the calibration") + except CalibrationFileError as unusable: + # A record with no camera in it has no lens to judge; the file reader's sentence says what is missing. + return [*problems, str(unusable)] + return [*problems, *_lens_problems(camera)] + + +# --- planning -------------------------------------------------------------------------------------------------- + + +def _before_box_filter(K: np.ndarray, divisor: int) -> np.ndarray: + """The camera matrix of a picture that a box filter by ``divisor`` shrinks to the picture ``K`` is of. + + A box-filtered pixel's centre sits ``(d - 1) / 2`` pixels of the larger picture past ``d`` times its index. + """ + larger = np.array(K, dtype=np.float64) + larger[:2, :] *= divisor + larger[:2, 2] += (divisor - 1) / 2.0 + return larger + + +def _box_filtered(picture: np.ndarray, divisor: int) -> np.ndarray: + """A picture shrunk by a whole number as the camera bridge shrinks a stream: every pixel the mean of a + ``divisor`` by ``divisor`` block, and a mean of whole numbers rounded half up.""" + height, width = picture.shape[0] // divisor, picture.shape[1] // divisor + blocks = picture.reshape(height, divisor, width, divisor, *picture.shape[2:]) + # A picture of real numbers has no levels to round to. + if not np.issubdtype(picture.dtype, np.integer): + return blocks.mean(axis=(1, 3), dtype=np.float64).astype(picture.dtype) + total, count = blocks.sum(axis=(1, 3), dtype=np.int64), divisor * divisor + return ((total + count // 2) // count).astype(picture.dtype) + + +def _source_camera(calibration: Intrinsics, source_size_wh: tuple[int, int], divisor: Any) -> Intrinsics | str: + """The calibrated camera in the pixels of the picture to correct, or why the two do not belong together. + + A divisor above 1 declares that the calibration was solved on this picture after a box downscale by it. + """ + if not isinstance(divisor, (int, np.integer)) or isinstance(divisor, (bool, np.bool_)) or divisor < 1: + return "the calibration divisor must be a whole number of at least 1" + solved = calibration.image_size_wh + # No other relation is accepted: a scale, a crop or a turn that is guessed corrects the wrong lens. + if (solved[0] * divisor, solved[1] * divisor) != source_size_wh: + picture = f"{source_size_wh[0]}x{source_size_wh[1]} picture" + which = f"the {picture}" if divisor == 1 else f"the {picture} divided by {divisor}" + return f"the calibration was solved at {solved[0]}x{solved[1]}, which is not {which}" + return replace(calibration, K=_before_box_filter(calibration.K, divisor), image_size_wh=source_size_wh) + + +def _border_pixels(size_wh: tuple[int, int]) -> np.ndarray: + """The centre of every pixel on a picture's border, as ``(x, y)`` rows.""" + right, bottom = size_wh[0] - 1.0, size_wh[1] - 1.0 + columns, rows = np.arange(size_wh[0], dtype=np.float64), np.arange(1.0, bottom) + edges = [ + np.stack([columns, np.zeros_like(columns)], axis=1), + np.stack([columns, np.full_like(columns, bottom)], axis=1), + np.stack([np.zeros_like(rows), rows], axis=1), + np.stack([np.full_like(rows, right), rows], axis=1), + ] + return np.concatenate(edges) + + +def _calibrate_again(camera: Intrinsics) -> str: + """What calibrating again can do about a lens model that ends short of the picture it is asked for. + + More of the board at the edge extends a fisheye model. A radial-tangential model of a wide lens turns over + inside the picture whatever it is shown, and only the fisheye model follows such a lens there. + """ + advice = "calibrate again taking the board to the picture's edge" + return f"{advice}, or solve the lens under the fisheye model" if camera.model == PINHOLE else advice + + +def _view_centre(camera: Intrinsics, balance: float, held_rays: np.ndarray) -> np.ndarray: + """Where the corrected view of a lens is centred, in normalised image coordinates, by OpenCV's rule for the + lens model. + + ``held_rays`` are the directions of the pixels the widest view holds (of a fisheye the picture's four edge + midpoints), which the caller has checked the lens model reaches. + """ + if camera.model == FISHEYE: + # The rule of ``cv2.fisheye.estimateNewCameraMatrixForUndistortRectify``: the mean direction of the + # edge midpoints. Applied here, to the midpoints where they are, with the camera model's own inverse: + # that function takes them at whole pixels, and its inverse answers with numbers that mean nothing for + # a midpoint next to the angle where the model turns over. + return held_rays.mean(axis=0) + width, height = camera.image_size_wh + fitted, _valid_area = cv2.getOptimalNewCameraMatrix( + camera.K, camera.dist, (width, height), balance, (width, height) + ) + # That function puts its view between the outermost pixel centres, so the view's middle is theirs. + return np.array( + [((width - 1) / 2.0 - fitted[0, 2]) / fitted[0, 0], ((height - 1) / 2.0 - fitted[1, 2]) / fitted[1, 1]] + ) + + +def _fitted_matrix(camera: Intrinsics, geometry: OutputGeometry) -> np.ndarray: + """The output camera matrix for the balance and field-of-view scale asked for. + + The view is centred where OpenCV's function for the lens model centres it. Its focal lengths are not + taken: it fits them to a few border points and each direction apart, which leaves slivers without a source + pixel at balance 0 and stretches the picture. The zoom is one factor on the lens's own focal lengths, + fitted to the border OpenCV fits to: at balance 0 the view just stays inside every border pixel, at 1 it + just holds the whole border (of a fisheye the edge midpoints: its corners no pinhole picture holds). The + view is fitted + for a picture of the source's size, then scaled to cover the output and centred on it. + """ + width, height = camera.image_size_wh + out_width, out_height = geometry.size_wh + border = _border_pixels(camera.image_size_wh) + right, bottom = width - 1.0, height - 1.0 + midpoints = np.array([[right / 2, 0.0], [right, bottom / 2], [right / 2, bottom], [0.0, bottom / 2]]) + # The pixels the wide end must hold, then the pixels the tight end must stay inside. + held = midpoints if camera.model == FISHEYE else border + rays, reached = _rays(np.concatenate([held, border]), camera) + # Where the model does not reach the pixels a view is fitted to, OpenCV answers with a matrix of zeros, of + # NaN or of numbers that mean nothing, so it is not asked. + if not reached[: len(held)].all(): + raise RectificationError( + "the lens model cannot be followed to the picture's edge (it turns over first, or the edge is 90 " + "degrees or more off the axis), so no view can be fitted from a balance; state the output camera " + f"matrix, or {_calibrate_again(camera)}" + ) + looks = _view_centre(camera, geometry.balance, rays[: len(held)]) + focal = np.array([camera.K[0, 0], camera.K[1, 1]]) + # The zoom at which each pixel lies on the edge of a source-size view. The view spans the picture's whole + # extent, so its outermost pixel centres sit half a pixel inside the fit. + with np.errstate(divide="ignore"): + on_edge = np.min(np.array([width, height]) / 2.0 / (focal * np.abs(rays - looks)), axis=1) + tight, wide = np.max(on_edge[reached]), np.min(on_edge[: len(held)]) + zoom = ((1.0 - geometry.balance) * tight + geometry.balance * wide) / geometry.fov_scale + # One factor for both directions keeps pixels square; what does not fit is cut equally from both sides. + focal = focal * zoom * max(out_width / width, out_height / height) + return np.array( + [ + [focal[0], 0.0, (out_width - 1) / 2.0 - focal[0] * looks[0]], + [0.0, focal[1], (out_height - 1) / 2.0 - focal[1] * looks[1]], + [0.0, 0.0, 1.0], + ] + ) + + +def _maps(camera: Intrinsics, K_out: np.ndarray, size_wh: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]: + """For every pixel of a ``size_wh`` picture seen through ``K_out``, the source column and row it samples.""" + build = cv2.fisheye.initUndistortRectifyMap if camera.model == FISHEYE else cv2.initUndistortRectifyMap + return build(camera.K, camera.dist, np.eye(3), K_out, size_wh, cv2.CV_32FC1) + + +def _inside(map_x: np.ndarray, map_y: np.ndarray, source_size_wh: tuple[int, int]) -> np.ndarray: + """Which map entries name a source pixel, by the GPU step's own test: a positive one, so NaN is outside.""" + width, height = source_size_wh + return (map_x >= 0) & (map_x <= width - 1) & (map_y >= 0) & (map_y <= height - 1) + + +@dataclass(frozen=True) +class SourcePixelsPerOutputPixel: + """How many source pixels one step between neighbouring map entries crosses, along the direction that + crosses most: what one bilinear pass reduces the camera's picture by.""" + + #: At the centre of the corrected picture; 0 when the centre has no source pixel. + centre: float + #: At the place inside the source where it is largest. + worst: float + + +def _footprint( + map_x: np.ndarray, map_y: np.ndarray, inside: np.ndarray +) -> tuple[SourcePixelsPerOutputPixel, bool]: + """The source pixels each output step crosses, and whether the map folds anywhere inside the source. + + Both come from the map's Jacobian between neighbouring pixels. A determinant that is not positive means the + picture is mirrored there: past the radius where a lens model turns over, the map runs back into the source. + """ + # Only where every pixel of a difference samples the source: elsewhere the output is fill, not picture, and + # the map may run to numbers whose squares do not fit a float. + sampled = inside[:-1, :-1] & inside[:-1, 1:] & inside[1:, :-1] + across_x, across_y = (np.where(sampled, np.diff(values, axis=1)[:-1, :], 0.0) for values in (map_x, map_y)) + down_x, down_y = (np.where(sampled, np.diff(values, axis=0)[:, :-1], 0.0) for values in (map_x, map_y)) + determinant = across_x * down_y - down_x * across_y + folds = bool(np.any(sampled & ~(determinant > 0))) + # The larger singular value of the 2x2 Jacobian, from its squared norm and its determinant. + norm = across_x**2 + across_y**2 + down_x**2 + down_y**2 + stretch = np.sqrt((norm + np.sqrt(np.maximum(norm**2 - 4.0 * determinant**2, 0.0))) / 2.0) + centre = stretch[stretch.shape[0] // 2, stretch.shape[1] // 2] + return SourcePixelsPerOutputPixel(float(centre), float(stretch.max())), folds + + +def _field_of_view_deg(K: np.ndarray, size_wh: tuple[int, int]) -> tuple[float, float]: + """The horizontal and vertical angle a picture spans, from its first pixel's outer edge to its last's.""" + spans = [] + for axis, pixels in enumerate(size_wh): + focal, centre = K[axis, axis], K[axis, 2] + spans.append(math.degrees(math.atan((centre + 0.5) / focal) + math.atan((pixels - 0.5 - centre) / focal))) + return spans[0], spans[1] + + +def _view_reach_deg(K: np.ndarray, inside: np.ndarray) -> float: + """The largest angle from the lens's axis that a pixel of the corrected picture with a source pixel looks + along, in degrees. + + The corrected camera is not turned against the lens, so each of its pixels looks where the lens does. + """ + rows, columns = np.nonzero(inside) + off_axis = np.hypot((columns - K[0, 2]) / K[0, 0], (rows - K[1, 2]) / K[1, 1]) + return math.degrees(math.atan(off_axis.max())) + + +def _plan_id(camera: Intrinsics, K_out: np.ndarray, size_wh: tuple[int, int]) -> str: + """A hash of everything that determines a plan's maps: the two cameras, the two sizes and the OpenCV build.""" + digest = hashlib.sha256() + digest.update(camera.model.encode()) + digest.update(np.asarray([*camera.image_size_wh, *size_wh], dtype=" int: + """The largest oversample a corrected picture of this size can be planned at.""" + return min(MAX_OVERSAMPLE, MAX_OUTPUT_SIDE_PX // max(size_wh)) + + +def share_text(part: float) -> str: + """A share of a picture in percent, in digits an operator reads at a glance: none is said as none, a + sliver as a sliver and never in exponent form, and a share near a limit keeps the digit that tells them + apart.""" + percent = 100.0 * part + if percent == 0.0: + return "0%" + if percent < 0.01: + return "under 0.01%" + return f"{percent:.2f}%" if percent < 1.0 else f"{percent:.1f}%" + + +@dataclass(frozen=True, eq=False) +class RectificationPlan: + """A sound rectification of one camera's picture: the output camera, the maps and what they amount to.""" + + #: The geometry that was asked for, checked. + geometry: OutputGeometry + #: The camera matrix of the corrected picture as it is published and recorded; its distortion is zero. + K: np.ndarray + #: The camera matrix of the picture the maps make, which a box filter by the oversample shrinks to the + #: published one. The same as ``K`` at an oversample of 1. + table_K: np.ndarray + #: ``map_x[v, u]`` and ``map_y[v, u]`` are the source column and row that pixel ``(u, v)`` of the maps' + #: picture samples, with integer coordinates at pixel centres. An entry outside the source means the pixel + #: is filled. + map_x: np.ndarray + map_y: np.ndarray + #: The calibration the plan rests on, as its file states it. + calibration: Intrinsics + #: The box downscale declared between the picture and the calibration. + calibration_divisor: int + #: The only picture size this plan corrects. + source_size_wh: tuple[int, int] + #: The calibrated camera matrix in the pixels of that picture. + source_K: np.ndarray + #: The share of the maps' pixels with no source pixel. + outside_share: float + #: The horizontal and vertical field of view of the corrected picture. + field_of_view_deg: tuple[float, float] + #: How much the one bilinear pass through the maps reduces the camera's picture: above ``ALIASING_RATIO`` + #: it skips source pixels. The box filter after it skips none. + source_pixels_per_output_pixel: SourcePixelsPerOutputPixel + #: The largest angle from the lens's axis the corrected picture looks along, in degrees. + view_reach_deg: float + #: How far from the axis the calibration saw the board, in degrees: the lens model is measured out to + #: there and a guess beyond. None when the calibration's record does not say. + calibrated_to_deg: float | None + #: What an operator should know about a plan that is nevertheless sound. + warnings: tuple[str, ...] + #: The same for two plans exactly when their maps are the same. + plan_id: str + + @property + def size_wh(self) -> tuple[int, int]: + """The size of a corrected picture as it is published and recorded.""" + return self.geometry.size_wh + + @property + def table_size_wh(self) -> tuple[int, int]: + """The size of the picture the maps make: the published size times the oversample.""" + width, height = self.geometry.size_wh + return width * self.geometry.oversample, height * self.geometry.oversample + + @property + def suggested_oversample(self) -> int: + """The smallest oversample at which the one pass through the maps skips no source pixels, as far as + the picture's size allows one: what to set where the plan warns of shimmer.""" + per_published_pixel = self.source_pixels_per_output_pixel.worst * self.geometry.oversample + return max(1, min(math.ceil(per_published_pixel / ALIASING_RATIO), _largest_oversample(self.size_wh))) + + @property + def principal_point(self) -> tuple[float, float]: + """Where the lens's axis meets the corrected picture, in its pixels.""" + return float(self.K[0, 2]), float(self.K[1, 2]) + + @cached_property + def outside(self) -> np.ndarray: + """Which pixels of the maps' picture have no source pixel and are filled.""" + return ~_inside(self.map_x, self.map_y, self.source_size_wh) + + @cached_property + def _single_pass(self) -> tuple[np.ndarray, np.ndarray]: + """The maps in the fixed-point form OpenCV applies, with every entry outside the source in the border. + + OpenCV blends a position within a pixel of the edge with the border and reads a NaN as a pixel on some + machines; the GPU step fills both. Moving them out makes a preview show what the step produces. + """ + map_x = np.where(self.outside, np.float32(_NO_SOURCE), self.map_x) + map_y = np.where(self.outside, np.float32(_NO_SOURCE), self.map_y) + return cv2.convertMaps(map_x, map_y, cv2.CV_16SC2) + + def remap(self, frame_bgr: np.ndarray) -> np.ndarray: + """The corrected copy of a source-size frame as the bridge publishes it: one bilinear pass through the + maps, then a box filter by the oversample. Pixels with no source pixel are black.""" + height, width = frame_bgr.shape[:2] + # OpenCV remaps a frame of any size without complaint, and the result would be a wrong picture. + if (width, height) != self.source_size_wh: + raise RectificationError( + f"a {width}x{height} frame cannot be corrected by a plan made for " + f"{self.source_size_wh[0]}x{self.source_size_wh[1]}" + ) + made = cv2.remap(frame_bgr, *self._single_pass, cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) + # At an oversample of 1 the maps' picture is the published one. + return made if self.geometry.oversample == 1 else _box_filtered(made, self.geometry.oversample) + + def figures(self) -> dict[str, Any]: + """The numbers that describe the corrected picture, as JSON values.""" + return { + "outside_share": self.outside_share, + "field_of_view_deg": list(self.field_of_view_deg), + "source_pixels_per_output_pixel": { + "centre": self.source_pixels_per_output_pixel.centre, + "worst": self.source_pixels_per_output_pixel.worst, + }, + "principal_point": list(self.principal_point), + "K": self.K.tolist(), + "field_angle_deg": {"view": self.view_reach_deg, "calibrated": self.calibrated_to_deg}, + "oversample": self.geometry.oversample, + "table_size_wh": list(self.table_size_wh), + "suggested_oversample": self.suggested_oversample, + } + + def metadata( + self, *, calibration_file: str | None = None, calibration_sha256: str | None = None + ) -> dict[str, Any]: + """What is recorded beside video corrected by this plan: the corrected camera and what produced it. + + The top level reads as an intrinsics record of the corrected picture as it is published: at an + oversample above 1, the picture after the box filter. The caller names the calibration file and its + hash, which a plan made from parsed intrinsics does not know. + """ + stated = self.geometry.K is not None + figures = self.figures() + return { + "rectified": True, + "model": PINHOLE, + # The remap removed the distortion, so nothing measured on the output may apply the source's again. + "dist_coeffs": [0.0] * 5, + "image_size_wh": list(self.size_wh), + "K": figures["K"], + "R": np.eye(3).tolist(), + "source_model": self.calibration.model, + "source_image_size_wh": list(self.source_size_wh), + "source_K": self.source_K.tolist(), + "source_dist_coeffs": self.calibration.dist.tolist(), + "calibration_divisor": self.calibration_divisor, + # A stated matrix is the whole view: the two numbers below took no part in it. + "balance": None if stated else self.geometry.balance, + "fov_scale": None if stated else self.geometry.fov_scale, + "allow_border": self.geometry.allow_border, + "explicit_K": stated, + "oversample": figures["oversample"], + "table_size_wh": figures["table_size_wh"], + "outside_share": figures["outside_share"], + "field_of_view_deg": figures["field_of_view_deg"], + "source_pixels_per_output_pixel": figures["source_pixels_per_output_pixel"], + "field_angle_deg": figures["field_angle_deg"], + "calibration": { + "file": calibration_file, + "sha256": calibration_sha256, + "identity": intrinsics_identity(self.calibration), + "calibrated_at": self.calibration.record.get("calibrated_at"), + "rms_px": self.calibration.record.get("rms_calibrate_camera"), + }, + "plan_id": self.plan_id, + "opencv_version": cv2.__version__, + } + + +def _refuse_far_centre(K_out: np.ndarray, geometry: OutputGeometry) -> None: + """Refuse a fitted view whose principal point lies far from the corrected picture's centre. + + OpenCV centres a view on what the lens covers, which for a wide lens whose axis is off the picture's centre + is far from the axis. A stated matrix is the operator's own placement and is not brought here. + """ + width, height = geometry.size_wh + off = max(abs(K_out[0, 2] - (width - 1) / 2.0) / width, abs(K_out[1, 2] - (height - 1) / 2.0) / height) + if off > MAX_PRINCIPAL_POINT_OFFSET: + # A wider view is centred nearer the axis, but at the widest there is no balance left to raise. + remedy = "raise the balance, or state" if geometry.balance < 1.0 else "state" + limit = f"{100.0 * MAX_PRINCIPAL_POINT_OFFSET:g}%" + raise RectificationError( + f"the corrected picture would be centred far off the lens's axis (its principal point " + f"{share_text(off)} of the picture from the centre, and at most {limit} is accepted); {remedy} the " + "output camera matrix" + ) + + +def _narrower(geometry: OutputGeometry) -> str: + """What an operator can change to narrow a view that reaches past the source: only what this view used.""" + if geometry.K is not None: + return "change the output camera matrix" + return ( + "lower the balance or the field-of-view scale" + if geometry.balance > 0.0 + else "lower the field-of-view scale" + ) + + +def plan_rectification( + intrinsics: Intrinsics, + source_size_wh: Any, + geometry: OutputGeometry, + *, + calibration_divisor: int = 1, +) -> RectificationPlan: + """Plan the correction of ``source_size_wh`` pictures of a calibrated camera into ``geometry``. + + The calibration must be for those pictures: solved at their size, or at their size divided by + ``calibration_divisor`` when the pictures were box downscaled by it before the solve. The maps are made + at the geometry's oversample times its size. Every refusal is a ``RectificationError`` whose message is + one sentence for an operator. + """ + geometry = checked_geometry(geometry) + source = _size(source_size_wh, "source", MAX_SOURCE_SIDE_PX) + camera = _source_camera(intrinsics, source, calibration_divisor) + # Every reason the calibration cannot be used is told at once: each needs another fix. + problems = [*_provenance_problems(intrinsics.record), *_lens_problems(intrinsics)] + if isinstance(camera, str): + raise RectificationError("; ".join([*problems, camera])) + if problems: + raise RectificationError("; ".join(problems)) + + stated = geometry.K is not None + K_out = geometry.K if stated else _fitted_matrix(camera, geometry) + # Told before anything about the maps: a view centred this far off leaves pixels without a source and + # folds, and those are its symptoms, not what the operator can act on. + if not stated: + _refuse_far_centre(K_out, geometry) + # The maps make the picture that the bridge's box filter shrinks to the one asked for, so they are made + # for the camera of that larger picture. + oversample = geometry.oversample + table_size = (geometry.size_wh[0] * oversample, geometry.size_wh[1] * oversample) + K_table = _before_box_filter(K_out, oversample) + map_x, map_y = _maps(camera, K_table, table_size) + inside = _inside(map_x, map_y, source) + footprint, folds = _footprint(map_x, map_y, inside) + # A picture none of which is picture: a stated matrix that looks past the lens's view. + if footprint.worst == 0.0: + raise RectificationError("no part of the corrected picture comes from the camera's picture") + if folds: + raise RectificationError( + "part of the corrected picture would show the scene mirrored: the lens model turns over inside the " + f"view; narrow the view, or {_calibrate_again(camera)}" + ) + reach, limit = _view_reach_deg(K_table, inside), field_limit_deg(camera) + # Past the angle where a model's radial curve turns, and again where it changes sign, the maps still name + # source pixels, and a view lying wholly beyond shows no fold: only the angle tells. + if reach > limit: + raise RectificationError( + f"the corrected picture looks up to {reach:.0f} degrees off the lens's axis, and the lens model holds " + f"only out to {limit:.0f} degrees; narrow the view, or {_calibrate_again(camera)}" + ) + outside_share = 1.0 - float(np.mean(inside)) + if outside_share > 0.0 and not geometry.allow_border: + raise RectificationError( + f"{share_text(outside_share)} of the corrected picture has no source pixel; {_narrower(geometry)}, or " + "allow borders" + ) + + warnings = [] + if footprint.worst > ALIASING_RATIO: + # The pass through maps made larger crosses that many fewer source pixels, and the box filter after + # it crosses none: the oversample that brings the pass under the limit is what cures this. + per_published_pixel = footprint.worst * oversample + needed, largest = math.ceil(per_published_pixel / ALIASING_RATIO), _largest_oversample(geometry.size_wh) + remedy = ( + f"an oversample of {needed} avoids it" + if needed <= largest + else f"the largest oversample this size takes, {largest}, leaves {per_published_pixel / largest:.1f}, " + "so a larger output or a narrower view is needed as well" + ) + warnings.append( + f"one pass of the correction covers up to {footprint.worst:.1f} source pixels a pixel: it skips " + f"detail there, so fine texture will shimmer; {remedy}" + ) + seen = _number(intrinsics.record.get(_SEEN_KEY)) + # Said, not refused: the model is sound where the board was seen, and how far a real lens lets a board be + # detected has not been measured. A calibration that does not say how far it saw is not held to it. + if seen is not None and reach > seen + _REACH_MARGIN_DEG: + warnings.append( + f"the corrected picture looks up to {reach:.0f} degrees off the lens's axis, and the calibration saw " + f"the board only out to {seen:.0f} degrees: beyond that the lens model is a guess, so the picture's " + "rim may be bent; calibrate again taking the board further out, or narrow the view" + ) + for array in (K_out, K_table, map_x, map_y, camera.K): + array.setflags(write=False) + return RectificationPlan( + geometry=geometry, + K=K_out, + table_K=K_table, + map_x=map_x, + map_y=map_y, + calibration=intrinsics, + calibration_divisor=int(calibration_divisor), + source_size_wh=source, + source_K=camera.K, + outside_share=outside_share, + field_of_view_deg=_field_of_view_deg(K_out, geometry.size_wh), + source_pixels_per_output_pixel=footprint, + view_reach_deg=reach, + calibrated_to_deg=seen, + warnings=tuple(warnings), + plan_id=_plan_id(camera, K_table, table_size), + ) + + +# --- previews -------------------------------------------------------------------------------------------------- + + +def _border_trace(plan: RectificationPlan) -> np.ndarray: + """Where the corrected picture's border samples the source, walked once around, as ``(x, y)`` rows.""" + walk = [] + for values in (plan.map_x, plan.map_y): + walk.append(np.concatenate([values[0, :], values[1:, -1], values[-1, -2::-1], values[-2:0:-1, 0]])) + return np.stack(walk, axis=1).astype(np.float64) + + +def preview_tiles(frame_bgr: np.ndarray, plan: RectificationPlan) -> tuple[np.ndarray, np.ndarray]: + """Two BGR pictures for judging a plan by eye: the frame as received, and the frame corrected. + + The received one is a copy with the area the corrected picture is taken from outlined in green: the plan's + map followed along the output's border. + """ + corrected = plan.remap(frame_bgr) + received = frame_bgr.copy() + width, height = plan.source_size_wh + trace = _border_trace(plan) + # A wide view's border runs far outside the source, or nowhere; only what is near the picture is drawn, + # because a coordinate past OpenCV's integer range would be drawn somewhere else. + middle, reach = np.array([width, height]) / 2.0, np.array([width, height]) * 1.5 + near = (np.abs(trace - middle) <= reach).all(axis=1) + closed = bool(near.all()) + if not closed: + # Started at a break, so that no stretch of the outline is cut in two by the walk's own start. + first_gap = int(np.argmin(near)) + trace, near = np.roll(trace, -first_gap, axis=0), np.roll(near, -first_gap) + # The outline scales with the picture so it survives being shown small. + thickness = max(1, round(min(width, height) / 240)) + position = 0 + for drawn, group in groupby(near): + length = len(list(group)) + if drawn: + stretch = np.round(trace[position : position + length] * (1 << _OUTLINE_SHIFT)).astype(np.int32) + cv2.polylines(received, [stretch], closed, _OUTLINE_BGR, thickness, cv2.LINE_AA, _OUTLINE_SHIFT) + position += length + return received, corrected + + +# --- the remap table file -------------------------------------------------------------------------------------- + + +def _running_parity(bits: np.ndarray) -> np.ndarray: + """For each position, whether an odd number of ``bits`` are set up to and including it.""" + size = bits.size + packed = np.zeros(-(-size // 64) * 8, dtype=np.uint8) + packed[: -(-size // 8)] = np.packbits(bits, bitorder="little") + # Sixty-four positions a word: the parity runs along each word by doubling shifts, then from word to word. + words = packed.view("> 63) + words[1:] ^= carried[:-1] * np.uint64(_U64) + return np.unpackbits(packed, count=size, bitorder="little") + + +def fnv1a64(data: bytes | bytearray | memoryview) -> int: + """The FNV-1a 64-bit hash of ``data``, which a remap table file carries of its payload. + + The hash is a chain, one multiplication a byte. Its exclusive-or reaches only the low byte of the state, + and bit k of that byte depends on the bits below it alone, so the low bytes are found a bit at a time for a + whole block, and what remains is a sum of products modulo 2**64. + """ + octets = np.frombuffer(data, dtype=np.uint8) + multiplier = np.uint8(_FNV_PRIME & 0xFF) + state = _FNV_OFFSET + for start in range(0, octets.size, _FNV_BLOCK): + block = octets[start : start + _FNV_BLOCK] + low = state & 0xFF + # mixed[n] becomes the low byte of the state before byte n, exclusive-ored with that byte. + mixed = np.zeros(block.size, dtype=np.uint8) + for bit in range(8): + place = np.uint8(1 << bit) + carry = (mixed * multiplier) & place + found = _running_parity(((block & place) ^ carry) != 0) * place + found ^= carry + if low & place: + found ^= place + mixed |= found + # Each step adds what the exclusive-or changed, then multiplies: a sum weighted by powers of the prime. + change = mixed.astype(np.int64) + change[1:] -= (mixed[:-1] * multiplier).astype(np.int64) + change[0] -= low + total = int(np.dot(change.view(np.uint64), _FNV_POWERS[block.size - 1 :: -1])) + state = (state * int(_FNV_POWERS[block.size - 1]) + total) & _U64 + return state + + +def _even(size_wh: tuple[int, int]) -> bool: + """Whether a size is one a 4:2:0 picture can have: both sides even and not zero.""" + return all(side > 0 and side % 2 == 0 for side in size_wh) + + +def write_remap_table(path: Path | str, plan: RectificationPlan) -> dict[str, Any]: + """Write ``plan``'s maps as the remap table file the GPU step loads; returns the file's facts. + + The facts are ``{"file": base name, "fnv1a64": the payload's hash in hexadecimal, "bytes": the length}``. + Entries outside the source are written as they are: the step fills them. The file appears whole or not at + all. ``RemapTableError`` when the step could not use the table or the file cannot be written. + """ + path = Path(path) + # The step's reader refuses an odd source, and an operator should hear it before the stack is started. + if not _even(plan.source_size_wh): + raise RemapTableError( + f"{path.name}: the GPU step corrects pictures with an even width and height, and the source is " + f"{plan.source_size_wh[0]}x{plan.source_size_wh[1]}" + ) + payload = np.stack([plan.map_x, plan.map_y], axis=-1).astype(" tuple[tuple[int, int], tuple[int, int], int]: + """A table file's source size, output size and payload hash, after the checks that need the header alone.""" + if header[: len(_TABLE_MAGIC)] != _TABLE_MAGIC: + raise RemapTableError(f"{name} is not a remap table") + if len(header) < _TABLE_HEADER.size: + raise RemapTableError(f"{name} ends inside its header") + _magic, header_bytes, source_w, source_h, out_w, out_h, flags, digest, _reserved = _TABLE_HEADER.unpack(header) + if header_bytes != _TABLE_HEADER.size: + raise RemapTableError( + f"{name} has a header of {header_bytes} bytes, and this reader knows the {_TABLE_HEADER.size}-byte one" + ) + if flags != 0: + raise RemapTableError(f"{name} has flags this reader does not know") + sizes = f"source {source_w}x{source_h}, output {out_w}x{out_h}" + if not _even((source_w, source_h)) or not _even((out_w, out_h)): + raise RemapTableError(f"{name} has a zero or odd size ({sizes})") + if max(source_w, source_h, out_w, out_h) > _TABLE_MAX_SIDE: + raise RemapTableError(f"{name} has a size above {_TABLE_MAX_SIDE} ({sizes})") + return (source_w, source_h), (out_w, out_h), digest + + +def read_remap_table(path: Path | str) -> RemapTable: + """Read a remap table file, refusing what the GPU step's own reader refuses; errors name the file.""" + path = Path(path) + name = path.name + try: + with open(path, "rb") as file: + source, output, digest = _table_header(file.read(_TABLE_HEADER.size), name) + expected = output[0] * output[1] * 8 + # Asked of the file, not found by reading: a header may announce more than any memory holds. + length = os.fstat(file.fileno()).st_size + if length != _TABLE_HEADER.size + expected: + raise RemapTableError( + f"{name} is {length} bytes, which is not the length of a {output[0]}x{output[1]} table" + ) + payload = file.read(expected) + except OSError: + raise RemapTableError(f"{name} could not be read") from None + if fnv1a64(payload) != digest: + raise RemapTableError(f"{name} is damaged: its payload does not match its hash") + entries = np.frombuffer(payload, dtype=" Path: + """Where an episode's rectified copy goes unless told otherwise: ``_rectified/``.""" + episode = Path(episode_dir).resolve() + return episode.parent.with_name(f"{episode.parent.name}_rectified") / episode.name + + +def _left_out(reason: str) -> dict[str, Any]: + """The record of a camera whose video was not rectified, and why.""" + return {"rectified": False, "reason": reason} + + +def _lies_in(path: Path, directory: Path) -> bool: + """Whether ``path``, which need not exist, is ``directory`` or lies inside it. + + Asked of the file system, not of the spelling: on a volume that ignores case, or through a link, two + spellings name one directory, and comparing them as text would let a copy into the recording. + """ + for ancestor in (path, *path.parents): + # What does not exist yet cannot be the directory; an ancestor that exists can. + with contextlib.suppress(OSError): + if os.path.samefile(ancestor, directory): + return True + return False + + +def _output_dir(sessions: list[Path], out_episode_dir: Path) -> Path: + """The resolved directory to publish into, refused unless it is new and apart from the recorded session.""" + out = out_episode_dir.resolve() + # The session covers the episode, and whatever holds the session holds every recording beside it. + if any(_lies_in(out, session) or _lies_in(session, out) for session in sessions): + raise RectifyTakeError("a rectified copy must be written outside the recorded session") + # Looked for where the copy will land: under its resolved parent, so that a link leading nowhere counts as + # something there, and at the resolved path, which a spelling through a missing directory hides. + for there in (out_episode_dir.parent.resolve() / out_episode_dir.name, out): + # Named as it was found: a link leading nowhere is there under its own name, not its target's. + if os.path.lexists(there): + raise RectifyTakeError(f"{there.name} already exists; a rectified episode is never replaced") + return out + + +def _checked_request(cameras: Mapping[str, CameraRectification], encoder: str) -> None: + """Refuse, before any video is opened, what cannot work whatever the take holds.""" + if encoder not in get_args(VideoEncoderKind): + raise RectifyTakeError(f"the video encoder {encoder!r} is not supported") + # The pipe encoders are named for the program they start; its absence would surface as a failed write. + if encoder.startswith("ffmpeg") and shutil.which("ffmpeg") is None: + raise RectifyTakeError(f"the video encoder {encoder!r} needs ffmpeg, which was not found") + for camera, request in cameras.items(): + if request.role not in ROLE_INTRINSICS: + roles = ", ".join(ROLE_INTRINSICS) + raise RectifyTakeError(f"{camera}: {request.role!r} is not a camera role ({roles})") + # An odd or empty output size is refused here in words; an encoder would refuse it mid-write in none. + try: + checked_geometry(request.geometry) + except RectificationError as refused: + raise RectifyTakeError(f"{camera}: {refused}") from None + + +def _calibration_file(role: str, sessions: list[Path], station_dir: Path | None) -> tuple[Path, str] | None: + """The lens file of a role and whose it is: the take's session's, else the station's, else None. + + In a session it is the role's lens file where the run corrected that camera, since the role's own file + there describes the corrected picture, and the role's own file otherwise. Whatever stands under the name + is chosen, a file that cannot be looked at included: reading it then fails by name, where passing it over + would say there is none or fall back to another calibration. + """ + for session in sessions: + held = lens_file_in(session, role) + if held is not None: + return held, "session" + # The station's file may have been solved after the take; it is only better than no correction at all. + held = None if station_dir is None else lens_file_in(station_dir, role) + return None if held is None else (held, "station") + + +def _videos(episode: Path) -> list[Path]: + """The camera videos an episode holds, in name order; ``RectifyTakeError`` when it cannot be listed.""" + try: + names = sorted(os.listdir(episode)) + except OSError: + # Taken for an episode without videos, one that may not be read would be said to hold none. + raise RectifyTakeError(f"{episode.name} could not be read") from None + # A dot file is a system's or a tool's leftover, not a camera, and a directory is no video. A name that + # cannot be looked at stays: opening it fails by name. + named = (episode / name for name in names if name.endswith(".mp4") and not name.startswith(".")) + return [video for video in named if not os.path.isdir(video)] + + +def _declared_divisor(intrinsics: Intrinsics, video_size_wh: tuple[int, int]) -> int: + """The box downscale a calibration declares between itself and a video of this size; 1 when it declares none. + + A solve made on a stream published at a divisor says so in its ``stream`` stamp. The number is passed on + only when it is the exact relation between the two sizes; the planner refuses every other. + """ + stamp = intrinsics.record.get("stream") + divisor = stamp.get("divisor") if isinstance(stamp, dict) else None + solved = intrinsics.image_size_wh + declared = type(divisor) is int and divisor > 1 and (solved[0] * divisor, solved[1] * divisor) == video_size_wh + return divisor if declared else 1 + + +def _first_frame(video: Path) -> tuple[np.ndarray, float, int] | None: + """A video's first frame, frame rate and declared frame count, or None when it cannot be read as one.""" + capture = cv2.VideoCapture(str(video)) + try: + ok, frame = capture.read() + fps = float(capture.get(cv2.CAP_PROP_FPS)) + declared = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) + finally: + capture.release() + # Without a frame there is no size to plan for, and without a frame rate the copy could not keep the timing. + if not ok or not fps > 0: + return None + return frame, fps, declared + + +def _planned( + video: Path, + request: CameraRectification | None, + episode_dir: Path, + sessions: list[Path], + station_dir: Path | None, +) -> _Stream | dict[str, Any]: + """How one camera video of the take at ``episode_dir`` will be rectified, or the record of why it is left + out.""" + # A camera nobody asked for stays as recorded, which is always safe. + if request is None: + return _left_out("no camera role was given for this video") + # Correcting corrected video bends it again, and the session's own calibration is of the lens, not of it. + try: + corrected = recorded_rectification(episode_dir, video.stem) is not None + except TakeRecordError as unknown: + return _left_out(str(unknown)) + if corrected: + return _left_out("this video was recorded already corrected") + found = _calibration_file(request.role, sessions, station_dir) + if found is None: + return _left_out(f"neither the take's session nor the station holds {ROLE_INTRINSICS[request.role]}") + calibration, source = found + try: + # Read once: the hash recorded beside the copy is of the very bytes the plan was made from. + intrinsics, digest = load_intrinsics_with_sha256(calibration) + except CalibrationFileError as unusable: + return _left_out(str(unusable)) + # One unreadable video is that camera's loss alone; the others are still rectified. + opened = _first_frame(video) + if opened is None: + return _left_out(f"{video.name} could not be read") + frame, fps, declared = opened + # The size is taken from a decoded frame: it is what the plan will be handed. + size = (frame.shape[1], frame.shape[0]) + divisor = _declared_divisor(intrinsics, size) + try: + plan = plan_rectification(intrinsics, size, request.geometry, calibration_divisor=divisor) + # Planned once to learn how much one pass reduces the picture, then again at the oversample that + # keeps the pass from skipping source pixels. + if request.oversample_as_needed and plan.suggested_oversample > plan.geometry.oversample: + sharper = replace(plan.geometry, oversample=plan.suggested_oversample) + plan = plan_rectification(intrinsics, size, sharper, calibration_divisor=divisor) + except RectificationError as refused: + return _left_out(str(refused)) + return _Stream(video.stem, video, plan, fps, declared, calibration, digest, source) + + +def _recorded_frames(episode: Path, camera: str) -> int | None: + """How many frames the recorder wrote for a camera, by the rows of its frame times; None when the episode + does not say (a directory of videos alone has no such rows).""" + try: + return CalibrationTake(episode).frame_count(camera) + except CalibrationError: + return None + + +@contextlib.contextmanager +def _unwritable(what: str) -> Iterator[None]: + """Turn a failure of a video writer or of the disk into one fit to show an operator: theirs name full paths.""" + try: + yield + except (RuntimeError, OSError) as failure: + raise RectifyTakeError(f"{what} could not be written") from failure + + +def _write_rectified(stream: _Stream, path: Path, encoder: str, progress: Progress | None) -> int: + """Write every frame of a stream's video, rectified, to ``path``; returns how many frames that was.""" + width, height = stream.plan.size_wh + what = f"{stream.video.name}: the rectified video" + capture = cv2.VideoCapture(str(stream.video)) + frames = 0 + # The source is closed whatever becomes of the writer. + try: + with _unwritable(what): + writer = create_video_writer(encoder, str(path), width, height, stream.fps) + try: + # Every decodable frame is written, in order, so frame indices mean the same in the copy. + while True: + ok, frame = capture.read() + if not ok: + break + rectified = stream.plan.remap(frame) + with _unwritable(what): + writer.write(rectified) + frames += 1 + if progress is not None: + progress(stream.camera, frames, stream.declared_frames) + finally: + # An encoder reports a failed encode only when it is closed. + with _unwritable(what): + writer.release() + finally: + capture.release() + return frames + + +def _entry(stream: _Stream, frames: int) -> dict[str, Any]: + """The record of one rectified camera: the plan's own, and what this copy adds to it.""" + return { + **stream.plan.metadata( + calibration_file=stream.calibration.name, calibration_sha256=stream.calibration_sha256 + ), + "calibration_source": stream.calibration_source, + "source_video": stream.video.name, + "frames": frames, + } + + +def _remove_created(directories: list[Path]) -> None: + """Remove the directories a failed attempt made, deepest first. + + One that holds anything by now is another run's as well, and stays, as does everything above it. A run + that made the same directory at the same moment can lose it to this; it then fails by name and may be + repeated. + """ + for directory in directories: + with contextlib.suppress(OSError): + directory.rmdir() + + +def rectify_episode( + episode_dir: Path, + out_episode_dir: Path, + cameras: Mapping[str, CameraRectification], + *, + station_calibration_dir: Path | None = None, + encoder: str = DEFAULT_ENCODER, + progress: Progress | None = None, + video_as_received: bool = False, +) -> dict[str, Any]: + """Write a rectified copy of an episode's camera videos to ``out_episode_dir`` and return its record. + + ``cameras`` maps a video's name without ``.mp4`` to the station role of its camera and the geometry + wanted. Each is corrected with the intrinsics file of that role in the take's own session, or, when the + session has none, the one in ``station_calibration_dir``. A video that is not named, was recorded already + corrected, has no usable calibration or is refused by the planner is left out, and the record says why. + Each is made as the camera bridge makes a corrected stream: one pass through the plan's maps at its + oversample, then a box filter. Where a camera asks for it, the oversample is raised to what keeps the pass + from skipping source pixels; the record's ``oversample`` says what was used. + The record, also written into the copy under ``RECORD_NAME``, is ``{"version": ..., "written_at": ..., + "cameras": {camera: description}}``. The output must be new and outside the recorded session; it appears + complete or not at all. + + A take that is not in its recorded session and carries no record of its own cannot say whether its video + was recorded corrected, and is refused unless ``video_as_received`` states that it was not. + ``RectifyTakeError`` then, and when the request or the output is refused, no camera can be rectified, or + the copy cannot be written. + """ + given = Path(episode_dir) + # Links are resolved first: what must be protected is the session the episode really lies in. + episode = given.resolve() + if not os.path.isdir(episode): + # Nothing there, or a file, is no episode. What stands there and cannot be looked at is said to be that. + out_of_reach = not absent(episode) and not os.path.exists(episode) + raise RectifyTakeError( + f"{episode.name} could not be read" if out_of_reach else f"{episode.name} is not a recorded episode" + ) + # The record of a run that corrected its video stays in the session. Away from it a take reads as recorded + # as received, and correcting corrected video bends it a second time. + if not video_as_received and not knows_how_recorded(given): + raise RectifyTakeError(TAKE_OUTSIDE_SESSION) + sessions = take_sessions(given) + out = _output_dir(sessions, Path(out_episode_dir)) + _checked_request(cameras, encoder) + station_dir = None if station_calibration_dir is None else Path(station_calibration_dir) + + # Every refusal is settled before anything is created, so a take that cannot be rectified leaves no trace. + entries: dict[str, dict[str, Any]] = {} + streams: list[_Stream] = [] + for video in _videos(episode): + planned = _planned(video, cameras.get(video.stem), given, sessions, station_dir) + if isinstance(planned, _Stream): + streams.append(planned) + else: + logger.info("%s is left as recorded: %s", video.name, planned["reason"]) + entries[video.stem] = planned + # An episode with nothing rectified in it would only stand in the way of a later, calibrated attempt. + if not streams: + reasons = "; ".join(f"{camera}: {entry['reason']}" for camera, entry in entries.items()) + raise RectifyTakeError(f"no camera video could be rectified ({reasons or 'the episode holds none'})") + + what = f"{out.name}: the rectified episode" + # Deepest first, which is the order they can be removed in again. + created = [directory for directory in (out.parent, *out.parent.parents) if not directory.exists()] + published = False + try: + # Built in a private directory beside the destination, on the same filesystem, and moved in by one rename. + with _unwritable(what): + out.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=f".{out.name}.staging-", dir=out.parent)) + try: + # The staging directory is owner-only; the episode inside it gets the permissions any new one would. + built = staging / out.name + with _unwritable(what): + built.mkdir() + for stream in streams: + frames = _write_rectified(stream, built / stream.video.name, encoder, progress) + # A video that stops decoding part-way would give a shorter copy that passes for the whole. + recorded = _recorded_frames(episode, stream.camera) + if recorded is not None and frames != recorded: + raise RectifyTakeError( + f"{stream.video.name} gave {frames} frames and the take recorded {recorded}: the video " + "is damaged, so no copy was made of it" + ) + logger.info( + "rectified %s: %d frames with the %s's %s, at an oversample of %d", + stream.video.name, + frames, + stream.calibration_source, + stream.calibration.name, + stream.plan.geometry.oversample, + ) + entries[stream.camera] = _entry(stream, frames) + record = { + "version": RECORD_VERSION, + "written_at": datetime.now().astimezone().isoformat(timespec="seconds"), + "cameras": dict(sorted(entries.items())), + } + with _unwritable(what): + write_json_atomic(built / RECORD_NAME, record) + # Flushed before it is published, so a power loss cannot leave a published episode half written. + fsync_tree(built) + # A destination that appeared meanwhile and holds anything makes this fail, and is left alone. + os.rename(built, out) + fsync_dir(out.parent) + published = True + finally: + shutil.rmtree(staging, ignore_errors=True) + finally: + # Nothing of a failed attempt stays behind, the directories made to hold it included. + if not published: + _remove_created(created) + return record diff --git a/examples/egocap/recording/egocap/calibration/station_store.py b/examples/egocap/recording/egocap/calibration/station_store.py new file mode 100644 index 0000000000..31909a16fe --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/station_store.py @@ -0,0 +1,388 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Installing solved calibrations into a station's calibration directory. + +Beside the live files the recorder copies into every session, the directory keeps a ``history`` of every file +installed through here and a ledger of when each kind of calibration was last done, and by whom. Errors here +name a file, never a directory: they are shown to an operator in a browser. +""" + +from __future__ import annotations + +import fcntl +import logging +import math +import os +import re +import threading +import unicodedata +from collections.abc import Iterator +from contextlib import contextmanager +from datetime import date, datetime +from pathlib import Path +from typing import Any + +from .files import ( + HEAD_EXTRINSICS, + HEAD_INTRINSICS, + LEFT_WRIST_INTRINSICS, + RIGHT_WRIST_INTRINSICS, + ROLE_INTRINSICS, + WRIST_OFFSETS, + CalibrationFileError, + read_json_object, + write_json, +) + +logger = logging.getLogger("isaaccapture.egocap.station_store") + +#: Every calibration file a station keeps, in the order an operator is shown them. +CALIBRATION_FILES = ( + HEAD_INTRINSICS, + HEAD_EXTRINSICS, + LEFT_WRIST_INTRINSICS, + RIGHT_WRIST_INTRINSICS, + WRIST_OFFSETS, +) +#: The ledger of the last calibration of each kind, hidden so nothing mistakes it for a calibration file. +LEDGER_NAME = ".calibration_log.json" +#: The directory of dated copies of every installed file. +HISTORY_DIR = "history" +#: Where a tool's work files go, under the calibration directory: never inside a recording. +RUNS_DIR = "runs" +#: The tool a camera solve's run folder is named for: what the page's solve and the command line's both hand +#: to ``run_directory``. +CAMERA_RUN_TOOL = "camera" +#: The ledger kind each camera role's files are installed under. The page and the command line both install +#: through here, so one station's ledger never splits a camera in two. +ROLE_KINDS = {"ego": "headset", "wrist_left": "wrist_left_camera", "wrist_right": "wrist_right_camera"} +#: The longest operator name: the bound the recording controls put on the name a take carries. +MAX_OPERATOR_LENGTH = 128 + +#: The files whose headline quality is a solve's reprojection error. +_INTRINSICS_FILES = frozenset(ROLE_INTRINSICS.values()) +#: A kind is a ledger key chosen by code, never free text: bounded so a route cannot grow the ledger with it. +_KIND = re.compile(r"[a-z][a-z0-9_]{0,39}") +#: The longest a line of text read from a file is shown, such as the time a file says it was made. +_MAX_TEXT_LENGTH = 80 +#: Control characters, and lone surrogates, which cannot be encoded when the text is later sent to a page. +_UNPRINTABLE_CATEGORIES = ("Cc", "Cs") +#: One install at a time among this process's threads; ``_exclusive`` adds the other processes. +_INSTALL_LOCK = threading.Lock() + + +class StationStoreError(ValueError): + """A calibration that cannot be installed as asked; the message is fit to show an operator.""" + + +def _one_line(text: Any, limit: int = _MAX_TEXT_LENGTH) -> str: + """Text typed on a page, or read from a file that may have been edited by hand, made fit to store and + show: printable, one line, at most ``limit`` characters. Anything that is not text gives none.""" + text = text if isinstance(text, str) else "" + # Replaced by a space, not dropped, so the words either side of a line break stay apart. + printable = "".join(" " if unicodedata.category(char) in _UNPRINTABLE_CATEGORIES else char for char in text) + return " ".join(printable.split())[:limit].rstrip() + + +def operator_name(raw: Any) -> str | None: + """An operator's name as takes carry it and as the ledger records it, or None for one that is refused. + + Trimmed, each run of white space one underscore: the recording controls' spelling, so one person's takes + and installs go under one name. None for anything that is not text, for a blank or over-long name, and + for one holding a character the ledger would not keep (an install would then be recorded under a name + its operator's takes do not carry). Every installer asks here, so the rule cannot differ between them. + """ + if not isinstance(raw, str) or len(raw) > MAX_OPERATOR_LENGTH: + return None + name = "_".join(raw.split()) + # White space is gone by now, so what is left of these categories is a character with no spelling. + if not name or any(unicodedata.category(char) in _UNPRINTABLE_CATEGORIES for char in name): + return None + return name + + +def run_directory(directory: Path, tool: str, role: str, now: datetime | None = None) -> Path: + """A folder of its own for one run of ``tool`` on ``role``, under the calibration directory's runs. + + The page's solves and the command line's are named alike, so a station's review folders sort as one + series. The folder is not created here. + """ + moment = now or datetime.now() + base = Path(directory) / RUNS_DIR / f"{moment:%Y%m%d-%H%M%S}_{tool}_{role}" + out, attempt = base, 1 + # Two runs within one second would otherwise share a folder, and the second show the first's frames. + while os.path.exists(out): + attempt += 1 + out = base.with_name(f"{base.name}_{attempt}") + return out + + +def _number(value: Any) -> int | float | None: + """``value`` when it is a real, finite number; a bool is not one.""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + try: + return value if math.isfinite(value) else None + except OverflowError: + # A whole number too large for a float is no measurement, and arithmetic on it fails the same way. + return None + + +def _known_files(files: Any) -> list[str]: + """The calibration file names in a ledger entry's list, each once, and nothing else a hand edit left.""" + # A hand edit can leave anything where the list was. + if not isinstance(files, list): + return [] + return list(dict.fromkeys(name for name in files if name in CALIBRATION_FILES)) + + +def _stored_ledger(directory: Path) -> dict[str, Any]: + """The ledger exactly as its file holds it; empty when there is no readable ledger.""" + try: + return read_json_object(Path(directory) / LEDGER_NAME) + except CalibrationFileError: + # A damaged ledger costs a hint; it must never stand between an operator and calibrating. + return {} + + +def _shown_entry(entry: dict[str, Any]) -> dict[str, Any]: + """One ledger entry as far as it has the shape this store writes, its text fit to show.""" + # A day or a time with nothing printable in it is left out, so a page falls back on the other one. + shown: dict[str, Any] = {key: text for key in ("date", "at") if (text := _one_line(entry.get(key)))} + # A blank operator stays: that is how an install made without a name is recorded. + if isinstance(entry.get("operator"), str): + shown["operator"] = _one_line(entry["operator"], MAX_OPERATOR_LENGTH) + shown["files"] = _known_files(entry.get("files")) + return shown + + +def _shown(entries: dict[str, Any]) -> dict[str, Any]: + """A stored ledger as far as this store could have written it: its kinds, each entry's text fit to show.""" + return { + kind: _shown_entry(entry) + for kind, entry in entries.items() + if _KIND.fullmatch(kind) is not None and isinstance(entry, dict) + } + + +def ledger(directory: Path) -> dict[str, Any]: + """When each kind of calibration was last installed and by whom; empty when there is no readable ledger. + + The file can be edited by hand and what is returned is sent to a page, so only kinds and file names this + store could have written are passed on, and text only as one printable, bounded line. + """ + return _shown(_stored_ledger(directory)) + + +@contextmanager +def _exclusive(directory: Path) -> Iterator[None]: + """Hold a station's calibration directory against every other install, in this process or another. + + An install reads the archive and the ledger and then writes both; two at once would each write back + what the other had not yet added. + """ + with _INSTALL_LOCK: + # The directory is locked, not the ledger: a rename replaces the ledger, and a lock on the file that + # was replaced excludes nobody. It also leaves no lock file among the calibration files. + handle = os.open(directory, os.O_RDONLY) + try: + try: + # flock, not lockf: every durable write opens and closes this directory to sync it, and + # closing any descriptor of a file drops a POSIX lock on it. + fcntl.flock(handle, fcntl.LOCK_EX) + except OSError as exc: + # A filesystem that cannot lock a directory still gets its calibration: the thread lock + # holds, and only an install from another process at the same moment is unguarded. + logger.warning("The calibration directory could not be locked against other programs: %s", exc) + yield + finally: + # Closing releases the lock, whether or not the install succeeded. + os.close(handle) + + +def _note(directory: Path, kind: str, name: str, operator: Any, moment: datetime) -> dict[str, Any]: + """Record in the ledger that ``name`` was installed under ``kind`` at ``moment``; returns the entry. + + The ledger is read, changed and written back whole, so the caller holds the directory (``_exclusive``). + """ + # Bounded as the name itself is, so the ledger holds every accepted name whole, as the takes carry it. + day, who = moment.strftime("%Y-%m-%d"), _one_line(operator, MAX_OPERATOR_LENGTH) + # Read as stored, not as shown: whatever else the file holds goes back as it was found, where it can. + entries = _stored_ledger(directory) + previous = entries.get(kind) + # Files one operator installs under one kind on one day are one calibration, so they are listed together. + # Another operator's are not carried over: the entry names one person, who did not install those. + same = isinstance(previous, dict) and previous.get("date") == day and previous.get("operator") == who + earlier = _known_files(previous.get("files")) if same else [] + # Installed again, a file moves to the end and is not listed twice. + files = [*(listed for listed in earlier if listed != name), name] + entry = {"date": day, "at": moment.isoformat(timespec="seconds"), "operator": who, "files": files} + entries[kind] = entry + try: + write_json(directory / LEDGER_NAME, entries) + except RecursionError: + # The reader follows nesting deeper than the writer does, so a hand edit can be read and still not go + # back. The calibration is live by now and must have its entry: what this store could have written + # always can be written, so that much is kept and the rest given up. + logger.warning("The calibration ledger is nested too deep to write back whole; only its entries are kept") + write_json(directory / LEDGER_NAME, _shown(entries)) + return entry + + +def _archived_order(path: Path, name: str) -> tuple[str, str, int, bool, str]: + """Where an archived copy of ``name`` falls in time: by day, by stamp, by its turn within one second, and + within one install the copy it kept as replaced before the copy it installed.""" + stamp, _, turn = path.name.partition("_")[0].partition("-") + # A name without a counter is the first of its second. The file name last, so the order is total even + # among copies someone dropped in by hand. + return ( + path.parent.name, + stamp, + int(turn) if turn.isdecimal() else 1, + not path.name.endswith(f"_replaced_{name}"), + path.name, + ) + + +def _newest_archived(directory: Path, name: str) -> bytes | None: + """The content of the most recent archived copy of ``name``, or None when there is none to read.""" + try: + copies = (directory / HISTORY_DIR).glob(f"*/*_{name}") + newest = max(copies, key=lambda path: _archived_order(path, name), default=None) + return None if newest is None else newest.read_bytes() + except OSError: + # History that cannot be read vouches for nothing. + return None + + +def _free_prefix(day: Path, stamp: str, name: str) -> str: + """``stamp``, or ``stamp`` with a counter, under which the archive holds no copy of ``name`` that day.""" + prefix, turn = stamp, 1 + # Two installs within one second share a stamp, and the later one must not overwrite the earlier one's + # copies: nothing else holds them. + while any(os.path.exists(day / f"{prefix}{middle}{name}") for middle in ("_", "_replaced_")): + turn += 1 + prefix = f"{stamp}-{turn}" + return prefix + + +def _keep_replaced(directory: Path, name: str, destination: Path) -> None: + """Copy the installed ``name`` to ``destination`` before it is replaced, unless the archive already holds + exactly that content as its newest copy (the usual case: this store installed it).""" + try: + current = (directory / name).read_bytes() + except OSError: + # Nothing installed yet, or nothing readable to keep. + return + if current != _newest_archived(directory, name): + # Once the live file is renamed away nothing else holds this content, so it is synced like every + # other write here; the archived copy written next syncs the directory entry. Created, never + # overwritten: an existing copy is somebody's only one too. + with open(destination, "xb") as handle: + handle.write(current) + handle.flush() + os.fsync(handle.fileno()) + + +def install( + directory: Path, + name: str, + record: dict[str, Any], + *, + kind: str, + operator: str, + now: datetime | None = None, + archive: bool = True, +) -> dict[str, Any]: + """Install ``record`` as the station's calibration file ``name`` and return its ledger entry. + + ``kind`` groups the files of one calibration in the ledger. With ``archive`` a dated copy is kept under + ``history`` so an earlier calibration can be recovered, and so is the file being replaced when the archive + does not already hold it. ``StationStoreError`` for a name, kind or record that is not acceptable. + """ + # Reachable from a web route: only the station's own file names are ever joined to the directory, and + # what was sent is not echoed back. + if name not in CALIBRATION_FILES: + raise StationStoreError("that is not a calibration file a station keeps") + # The kind becomes a key of the ledger, which arbitrary text from a request must not be able to grow. + if not isinstance(kind, str) or _KIND.fullmatch(kind) is None: + raise StationStoreError("a calibration kind is a short lower-case name") + # Any other value would be written as valid JSON that no reader of a calibration file accepts. + if not isinstance(record, dict): + raise StationStoreError(f"{name} must hold a JSON object") + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + # The page and the command line both install here. What the archive and the ledger hold is read and + # then added to, so one install finishes before the next begins. + with _exclusive(directory): + # One moment stamps the archive and the ledger alike. It is local time: a station's "today" is its + # own day. Read once the directory is held: an install that waited its turn must not be archived + # as earlier than the one that went in ahead of it. + moment = now or datetime.now().astimezone() + if archive: + day = directory / HISTORY_DIR / moment.strftime("%Y-%m-%d") + day.mkdir(parents=True, exist_ok=True) + # One prefix for the copy kept and the copy installed, so the two of one install stay together. + prefix = _free_prefix(day, moment.strftime("%H%M%S"), name) + # A file this store did not archive (placed by hand, or by another tool) would be lost here. + _keep_replaced(directory, name, day / f"{prefix}_replaced_{name}") + # Archived before it goes live, so a calibration in use has a copy that outlasts its replacement. + write_json(day / f"{prefix}_{name}", record) + # Replaced by one rename, so a recorder copying the calibration never reads half a file. + write_json(directory / name, record) + return _note(directory, kind, name, operator, moment) + + +def _headline(name: str, record: dict[str, Any]) -> dict[str, int | float]: + """The one number that says how good a calibration is, under the name its record gives it.""" + # Each kind of file measures itself differently: a solve's error, a board's apparent wander, a sample count. + if name in _INTRINSICS_FILES: + key, value = "rms_calibrate_camera", record.get("rms_calibrate_camera") + elif name == HEAD_EXTRINSICS: + # Several methods are solved and compared; the one the solver chose is the one in use. + methods, best = record.get("methods"), record.get("best_method") + chosen = methods.get(best) if isinstance(methods, dict) and isinstance(best, str) else None + key = "board_position_std_norm_m" + value = chosen.get(key) if isinstance(chosen, dict) else None + else: + key, value = "n_samples", record.get("n_samples") + number = _number(value) + return {} if number is None else {key: number} + + +def _described(path: Path) -> dict[str, Any]: + """One calibration file for a page: whether it is there and readable, when it was made, how good it is.""" + # os.path swallows every error, where Path.exists raises on a directory it may not search. + if not os.path.exists(path): + return {"name": path.name, "present": False} + try: + record = read_json_object(path) + modified = path.stat().st_mtime + except (CalibrationFileError, OSError): + # There but unusable is something a page shows about one file, not a failure of the whole listing. + return {"name": path.name, "present": True, "readable": False} + # What the file says may have been typed into it by hand, so it is shown only as one printable line. A + # file that does not say when it was made was at least made no later than it was last written. + stated = _one_line(record.get("calibrated_at")) + written = datetime.fromtimestamp(modified).astimezone().isoformat(timespec="seconds") + return { + "name": path.name, + "present": True, + "readable": True, + "calibrated_at": stated or written, + **_headline(path.name, record), + } + + +def installed(directory: Path) -> list[dict[str, Any]]: + """The state of every calibration file a station keeps, in a fixed order; a bad file is listed, not raised.""" + return [_described(Path(directory) / name) for name in CALIBRATION_FILES] + + +def done_today(directory: Path, kind: str, today: date) -> bool: + """Whether the ledger says a calibration of ``kind`` was installed on the day ``today``.""" + # Only a well-formed entry counts: the ledger may have been edited by hand. + entry = ledger(directory).get(kind) + return isinstance(entry, dict) and entry.get("date") == today.strftime("%Y-%m-%d") diff --git a/examples/egocap/recording/egocap/calibration/take.py b/examples/egocap/recording/egocap/calibration/take.py new file mode 100644 index 0000000000..1b5b9093fa --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/take.py @@ -0,0 +1,259 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A recorded calibration take: one episode directory, read and never changed. + +An episode holds, per camera, ``.mp4`` and a Zarr group of the same name with one ``capture_time`` +row per frame; frame ``i`` of the video is row ``i``. Head and controller poses are rows of the tracking +group and glove joints rows of the glove group, each on its own times, so a pose at a frame's time is +interpolated with the rule the aligner uses for that field. Times are seconds; poses are 4x4, world from +body, in OpenXR axes. +""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Iterator, Mapping +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import zarr + +from egocap.recording.alignment import FRAME_FIELD_RULES, interpolate_field + +from .board import CalibrationError + +#: The group holding head and controller poses, and the group holding glove joints. +TRACKING_SOURCE = "pico_controller" +GLOVE_SOURCE = "manus_glove" + +#: Where an episode says what its tracking times are: the recorder's timing evidence, an attribute of the +#: episode, has an entry for each source, and that entry states the latency taken off the source's times, if +#: any was. +_TIMING_PATH = ("timing", "event_time", TRACKING_SOURCE) +_TAKEN_OFF_KEY = "latency_s" +#: The largest tracking latency believed: a station measures a few hundredths of a second. +MAX_TRACKING_LATENCY_S = 1.0 + +#: Frames worth decoding and discarding rather than seeking over: a seek restarts at a key frame, so over a +#: short gap it decodes more than walking does. +_SEEK_GAP_FRAMES = 48 + + +#: What is said of an episode that stands there and may not be looked into: not that it is no episode, nor that +#: it recorded no camera. +_UNREADABLE = "the take could not be read" + + +class TakeError(CalibrationError): + """A take that cannot be read as a recorded episode, or does not hold what was asked of it.""" + + +class CalibrationTake: + """Read-only view of one recorded episode, as the calibrations need it.""" + + def __init__(self, episode_dir: Path | str) -> None: + """Open the episode read-only; a directory that is not an episode is a ``TakeError``.""" + self._path = Path(episode_dir) + try: + self._group = zarr.open_group(str(self._path), mode="r") + except PermissionError: + raise TakeError(_UNREADABLE) from None + except (OSError, ValueError): + raise TakeError("the take could not be opened: it is not a recorded episode") from None + # Listed from the videos: walking the Zarr hierarchy would warn about every video beside it. + try: + names = os.listdir(self._path) + except OSError: + # A directory that may be entered and not listed opens, and would read as one without a camera. + raise TakeError(_UNREADABLE) from None + videos = sorted( + Path(name).stem for name in names if name.endswith(".mp4") and os.path.isfile(self._path / name) + ) + self._cameras = tuple(camera for camera in videos if self._array(camera, "capture_time") is not None) + + def _array(self, source: str, field: str) -> zarr.Array | None: + """One field of a source, or None when the episode has no such source or field.""" + group = self._group.get(source) + member = group.get(field) if isinstance(group, zarr.Group) else None + return member if isinstance(member, zarr.Array) else None + + def _require_camera(self, camera: str) -> None: + """Refuse a camera this take did not record.""" + if camera not in self._cameras: + raise TakeError(f"camera {camera!r} is not in this take") + + def cameras(self) -> list[str]: + """Names of the cameras that have both a video and frame times, sorted.""" + return list(self._cameras) + + def frame_count(self, camera: str) -> int: + """Frames recorded for a camera: the rows of its time array.""" + self._require_camera(camera) + return int(self._array(camera, "capture_time").shape[0]) + + def _open_video(self, camera: str) -> cv2.VideoCapture: + """A decoder on a camera's video; the caller releases it.""" + self._require_camera(camera) + capture = cv2.VideoCapture(str(self._path / f"{camera}.mp4")) + if not capture.isOpened(): + capture.release() + raise TakeError(f"{camera}.mp4 could not be opened") + return capture + + def image_size(self, camera: str) -> tuple[int, int]: + """A camera's frame size as (width, height), from its video.""" + capture = self._open_video(camera) + try: + return int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) + finally: + capture.release() + + def tracking_latency_s(self) -> float | None: + """The latency the recorder took off this take's head and controller times, in seconds: zero when it + took none off. None when the take does not say what those times are, as one from another recorder + does not. + + A camera's lag is measured against these times, so a lag solved from one take holds for another only + as far as the two were recorded under the same latency. + """ + entry: Any = dict(self._group.attrs) + # The attributes are JSON a hand can have edited, so each level is looked into only while it is an + # object. + for key in _TIMING_PATH: + entry = entry.get(key) if isinstance(entry, Mapping) else None + if not isinstance(entry, Mapping): + return None + # A source with no latency configured states none: its times are the host's poll times as they were. + if _TAKEN_OFF_KEY not in entry: + return 0.0 + stated = entry[_TAKEN_OFF_KEY] + # A bool is not a number. The range also rejects NaN and the infinities, which compare false, and + # whole numbers no float can hold. + believed = type(stated) in (int, float) and 0.0 <= stated <= MAX_TRACKING_LATENCY_S + return float(stated) if believed else None + + def camera_times(self, camera: str, latency_s: float = 0.0) -> np.ndarray: + """When each frame was exposed: its recorded capture time less the camera's latency.""" + self._require_camera(camera) + return np.asarray(self._array(camera, "capture_time")[:], dtype=np.float64) - latency_s + + def frames(self, camera: str, indices: Iterable[int]) -> Iterator[tuple[int, np.ndarray]]: + """Yield ``(index, BGR frame)`` for ascending frame indices, decoding the video once, front to back.""" + total = self.frame_count(camera) + capture = self._open_video(camera) + try: + position = 0 + for index in indices: + index = int(index) + # The decoder only moves forward; an index behind it would silently return a later frame. + if not position <= index < total: + raise ValueError(f"frame indices must ascend within 0..{total - 1}") + # A long gap is sought across; the frames after a seek are still decoded in order. + if index - position > _SEEK_GAP_FRAMES: + capture.set(cv2.CAP_PROP_POS_FRAMES, index) + position = index + # Grabbing advances the decoder without converting the skipped frames to images. + while position < index: + if not capture.grab(): + raise TakeError(f"{camera}.mp4 ends before frame {index}; the take is damaged") + position += 1 + decoded, frame = capture.read() + if not decoded: + raise TakeError(f"{camera}.mp4 ends before frame {index}; the take is damaged") + position = index + 1 + yield index, frame + finally: + capture.release() + + def _samples(self, source: str, fields: tuple[str, ...]) -> tuple[np.ndarray, dict[str, np.ndarray]] | None: + """A source's rows in time order, one per distinct time; None when too few remain to interpolate.""" + arrays = [self._array(source, name) for name in ("capture_time", *fields)] + # Checked before loading: a recording without the source, or with a single row, has nothing to read. + if any(array is None for array in arrays) or arrays[0].shape[0] < 2: + return None + times = np.asarray(arrays[0][:], dtype=np.float64) + values = {name: np.asarray(array[:], dtype=np.float64) for name, array in zip(fields, arrays[1:])} + # A row with a hole in it would poison every pose interpolated next to it. + usable = np.isfinite(times) + for value in values.values(): + usable &= np.isfinite(value).reshape(len(times), -1).all(axis=1) + # The interpolators need strictly increasing times; unique sorts and keeps one row per time. + times, first = np.unique(times[usable], return_index=True) + # Two distinct times are the least an interpolator can span. + if times.size < 2: + return None + rows = np.flatnonzero(usable)[first] + return times, {name: value[rows] for name, value in values.items()} + + def _poses_at( + self, + source: str, + frame_type: str, + fields: dict[str, str], + row_shape: tuple[int, ...], + times: np.ndarray, + max_gap_s: float | None, + ) -> tuple[dict[str, np.ndarray], np.ndarray]: + """Fields of a source interpolated at ``times`` as ``{key: values}``, and which times they hold for. + + ``fields`` maps each output key to its field name, and ``frame_type`` names the aligner's rules for + them. A time outside the source's samples, or inside a gap in them longer than ``max_gap_s``, is + invalid and its values are identity transforms of ``row_shape``. + """ + targets = np.asarray(times, dtype=np.float64).reshape(-1) + valid = np.zeros(len(targets), dtype=bool) + samples = self._samples(source, tuple(fields.values())) + # With nothing to interpolate, no time is valid; the stored row shape is unknown, so the usual one. + if samples is None: + return {key: np.broadcast_to(np.eye(4), (len(targets), *row_shape)).copy() for key in fields}, valid + sample_times, values = samples + # The interpolators raise outside the sampled range, so those times are masked, not passed. + valid = np.isfinite(targets) & (targets >= sample_times[0]) & (targets <= sample_times[-1]) + if max_gap_s is not None: + inside = np.flatnonzero(valid) + # A time exactly on a sample has that sample on both sides, so it is never inside a gap. + before = np.searchsorted(sample_times, targets[inside], side="right") - 1 + after = np.searchsorted(sample_times, targets[inside], side="left") + valid[inside] = sample_times[after] - sample_times[before] <= max_gap_s + out = {} + for key, name in fields.items(): + # Shaped from the stored rows, so a recording with another joint count still reads. + out[key] = np.broadcast_to(np.eye(4), (len(targets), *values[name].shape[1:])).copy() + # The interpolators are not asked for an empty set of times. + if valid.any(): + rule = FRAME_FIELD_RULES[frame_type][name] + out[key][valid] = interpolate_field(rule, sample_times, values[name], targets[valid]) + return out, valid + + def head_poses_at(self, times: np.ndarray, *, max_gap_s: float | None = None) -> tuple[np.ndarray, np.ndarray]: + """The head pose at each time, shape (M, 4, 4), and a mask of the times it is known for. + + Position is interpolated linearly and rotation by slerp, as the aligner does. A time outside the + recorded tracking is marked invalid rather than extrapolated, as is one inside a tracking gap longer + than ``max_gap_s`` when that is given. Invalid rows hold the identity. + """ + fields = {"head": "head_pose"} + poses, valid = self._poses_at(TRACKING_SOURCE, "PicoTrackingFrame", fields, (4, 4), times, max_gap_s) + return poses["head"], valid + + def controller_poses_at( + self, times: np.ndarray, *, max_gap_s: float | None = None + ) -> tuple[dict[str, np.ndarray], np.ndarray]: + """Both controllers' poses at each time as ``{"left", "right"}`` of (M, 4, 4), and the validity mask.""" + fields = {"left": "left_pose", "right": "right_pose"} + return self._poses_at(TRACKING_SOURCE, "PicoTrackingFrame", fields, (4, 4), times, max_gap_s) + + def hand_poses_at( + self, times: np.ndarray, *, max_gap_s: float | None = None + ) -> tuple[dict[str, np.ndarray], np.ndarray]: + """Both gloves' joint transforms at each time as ``{"left", "right"}`` of (M, 25, 4, 4), and the mask. + + Joints are interpolated element by element, as the aligner does for glove frames. An episode with no + glove rows gives an all-invalid mask. + """ + fields = {"left": "left_hand_pose", "right": "right_hand_pose"} + return self._poses_at(GLOVE_SOURCE, "ManusFrame", fields, (25, 4, 4), times, max_gap_s) diff --git a/examples/egocap/recording/egocap/calibration/wrist_offset.py b/examples/egocap/recording/egocap/calibration/wrist_offset.py new file mode 100644 index 0000000000..d7f534b03f --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/wrist_offset.py @@ -0,0 +1,461 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The controller-to-glove wrist offset: the fixed transform from a tracked PICO controller worn at the wrist +to the glove's wrist frame, and the fit that finds it from fingertips clicked in head-camera frames. + +Everything here is math on plain arrays, with every pose in forward-left-up world axes (see ``frames``). +Choosing the frames of a take, the overlay a browser draws and the live recording guide are in ``hand_view``. +""" + +from __future__ import annotations + +import itertools +import logging +from collections.abc import Collection, Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + +from egocap.calibration.camera_model import project +from egocap.calibration.files import OPENXR_POSES, POSE_SOURCE_KEY, WRIST_OFFSETS, CalibrationFileError, Intrinsics +from egocap.calibration.frames import R_FLU_FROM_OPENXR, euler_pose, homogeneous, invert_pose + +_LOG = logging.getLogger("isaaccapture.egocap.wrist_offset") + +SIDES = ("left", "right") + +#: Slots of each finger's joints in the recorded skeleton, from the palm out to the tip; slot 0 is the wrist. +FINGER_SLOTS = { + "thumb": (1, 2, 3, 4), + "index": (5, 6, 7, 8, 9), + "middle": (10, 11, 12, 13, 14), + "ring": (15, 16, 17, 18, 19), + "little": (20, 21, 22, 23, 24), +} +FINGERS = tuple(FINGER_SLOTS) +#: The fingertip slot of each finger, in the order of ``FINGERS``. +TIP_SLOTS = tuple(slots[-1] for slots in FINGER_SLOTS.values()) +#: Joint slot pairs to join with a line when drawing the skeleton. +BONES = tuple(bone for slots in FINGER_SLOTS.values() for bone in zip((0, *slots[:-1]), slots)) +JOINT_COUNT = 1 + sum(len(slots) for slots in FINGER_SLOTS.values()) + +#: The turn (fixed-axis xyz Euler, degrees) from the offset controller frame to the hand frame that readers of +#: the saved file treat as the wrist. A convention shared with those readers and the same for both hands. +CORR_DEG = (0.0, -90.0, 0.0) +_CORR = euler_pose(*CORR_DEG) + +# The recorder stores the skeleton relative to the wrist joint and re-oriented from the OpenXR hand-joint axes +# (x, y, z) to (-y, -x, -z): +Z runs from the wrist toward the fingers, +X points out of the palm and +Y to the +# left of a palm-down hand (the little-finger side of a left hand, the thumb side of a right one). These +# half and quarter turns seat that skeleton in the wrist frame. The left pair undoes the re-orientation, so the +# left wrist frame has the OpenXR wrist joint's axes, and the right mirrors the Z turn; for both hands wrist X +# points to the thumb side and wrist Z back along the forearm. They are conventions, not measurements. +_SKELETON_FLIP = euler_pose(0.0, 180.0, 0.0) +_SKELETON_Z_TURN_DEG = {"left": 90.0, "right": -90.0} +#: The recorded skeleton's frame expressed in the wrist frame, per hand. +SKELETON_IN_WRIST = { + side: euler_pose(0.0, 0.0, turn) @ _SKELETON_FLIP for side, turn in _SKELETON_Z_TURN_DEG.items() +} + +# The fit's limits. The translation bound keeps the hand from being pushed into the camera plane, where a +# fingertip's pixel runs off to infinity. It is measured from the controller pose's own origin, so a mounting +# that puts the wrist further out is not fitted: the fit stops on the bound and its result says so. +_ROTATION_BOUND_DEG = 180.0 +#: How far along each controller axis, in meters, a fitted wrist origin can lie from the controller's origin. +#: Wide enough that a controller worn on a bracket well up the forearm is still fitted. +TRANSLATION_BOUND_M = 0.20 +_BOUNDS = np.array([_ROTATION_BOUND_DEG] * 3 + [TRANSLATION_BOUND_M] * 3) +#: A fitted shift this near the bound, in meters, is on it: the solver keeps every unknown just inside. +_ON_BOUND_M = 1e-6 +#: The size of a typical change in each unknown, which is what makes degrees and meters comparable steps. +_STEP_SCALE = np.array([60.0, 60.0, 60.0, 0.1, 0.1, 0.1]) +#: Pixel error beyond which a click counts as an outlier and pulls on the fit only linearly. +_OUTLIER_SCALE_PX = 50.0 +#: How many times one start may evaluate the residuals before it is taken as it stands. +_MAX_EVALUATIONS = 400 +#: What a fingertip the camera cannot place during the fit (behind it, or past its lens model's reach) +#: contributes in place of a pixel error. +_NO_PIXEL_RESIDUAL_PX = 1e4 +#: Fewer clicks than this cannot pin down a hand's six unknowns. +_MIN_CLICKS = 3 + +#: A click: the sample's index, the hand, the finger's index in ``FINGERS``, and the true pixel ``u, v``. +Click = tuple[int, str, int, float, float] +#: What identifies a click across optimisations: sample index, hand, finger index. +ClickKey = tuple[int, str, int] + +_NOTE = ( + "Controller-to-wrist offsets solved by least squares on the pixel distance between projected glove " + "fingertips and operator clicks in head-camera frames; per hand, T_world_wrist = T_world_controller @ " + "inv([R|t]) @ R_corr, where R and t are that hand's pico rotation and translation entries and R_corr is " + "the fixed-axis xyz Euler turn in its corr entry. T_world_controller is the recorded controller aim pose " + "re-expressed from OpenXR axes (X right, Y up, Z back) in X-forward, Y-left, Z-up axes, in meters: " + f"R_flu = C @ R_openxr @ C^T and t_flu = C @ t_openxr with C = {R_FLU_FROM_OPENXR.astype(int).tolist()}. " + "T_world_wrist is then in the same forward-left-up world axes." +) + + +@dataclass(frozen=True) +class WristOffset: + """One hand's offset, the six numbers a fit solves for; the default is the zero offset a station starts at.""" + + #: Turn of the hand about its wrist origin: fixed-axis xyz Euler angles in degrees. + rot_deg: tuple[float, float, float] = (0.0, 0.0, 0.0) + #: Shift of the wrist origin along the controller's axes, in meters. + trans_m: tuple[float, float, float] = (0.0, 0.0, 0.0) + + +@dataclass(frozen=True) +class HandSample: + """One head-camera frame of a take and what was tracked at its time, in forward-left-up world axes.""" + + frame_index: int + #: The head camera as it delivered this frame: its lens model, and its matrix at the frame's size. + intrinsics: Intrinsics + #: Maps a world point into the camera's optical frame. + T_camera_world: np.ndarray + #: Hand -> the 4x4 pose of its controller in the world. + controller_world: Mapping[str, np.ndarray] + #: Hand -> its (25, 4, 4) recorded skeleton, relative to the wrist. + hand_local: Mapping[str, np.ndarray] + #: Hand -> whether the glove delivered a pose for this frame. + hand_valid: Mapping[str, bool] + + +@dataclass(frozen=True) +class FitResult: + """A hand's fitted offset and how well it explains the clicks it was fitted to.""" + + offset: WristOffset + #: Unweighted pixel distance between each clicked fingertip and its projection, as a root mean square. + rms_px: float + n_clicks: int + #: Whether the fit stopped on ``TRANSLATION_BOUND_M``. The wrist may then lie further from the controller + #: than is fitted, and the offset is the nearest one allowed, not a solution to trust. + at_translation_limit: bool = False + + +def wrist_in_controller(offset: WristOffset) -> np.ndarray: + """The wrist frame in the controller frame: ``T_world_wrist = T_world_controller @ wrist_in_controller``. + + The rotation comes last, at the wrist origin, so it turns the hand in place; the translation moves that + origin along the controller's axes. + """ + shift = homogeneous(np.eye(3), -np.asarray(offset.trans_m, dtype=np.float64)) + return shift @ _CORR @ euler_pose(*offset.rot_deg) + + +def offset_from_wrist_in_controller(pose: np.ndarray) -> WristOffset: + """The offset whose ``wrist_in_controller`` is ``pose``, with the canonical Euler angles of its rotation.""" + turn = Rotation.from_matrix(_CORR[:3, :3].T @ pose[:3, :3]) + # At a quarter turn about Y the angles are not unique. Any of them is the same wrist, so the warning + # scipy gives there would only alarm. + angles = turn.as_euler("xyz", degrees=True, suppress_warnings=True) + return WristOffset(rot_deg=tuple(float(a) for a in angles), trans_m=tuple(float(-v) for v in pose[:3, 3])) + + +def export_offset(offset: WristOffset) -> tuple[np.ndarray, np.ndarray]: + """The rotation ``R`` and translation ``t`` the saved file carries for an offset. + + Readers of the file rebuild the wrist as ``T_world_wrist = T_world_controller @ inv([R | t]) @ CORR``. + """ + exported = invert_pose(wrist_in_controller(offset) @ invert_pose(_CORR)) + return exported[:3, :3], exported[:3, 3] + + +def offset_from_export(rotation: np.ndarray, translation: np.ndarray) -> WristOffset: + """The offset an exported rotation and translation stand for, whatever tool produced them.""" + return offset_from_wrist_in_controller(invert_pose(homogeneous(rotation, translation)) @ _CORR) + + +def joints_in_wrist(side: str, hand_local: np.ndarray) -> np.ndarray: + """Positions (25, 3) of a recorded skeleton's joints in the wrist frame; NaN for a joint the glove left out.""" + local = np.asarray(hand_local, dtype=np.float64) + positions = local[:, :3, 3] @ SKELETON_IN_WRIST[side][:3, :3].T + # The recorder zeroes the whole matrix of a joint it has no pose for; that is not a joint at the wrist. + positions[~np.isclose(local[:, 3, 3], 1.0)] = np.nan + return positions + + +def fingers_run_outward(hand_local: np.ndarray) -> bool | None: + """Whether every finger's joints in a recorded skeleton lie successively further from the wrist; None for + a skeleton with a joint missing, which cannot be judged. + + True of a hand in most poses: only a finger curled far back on itself brings a joint nearer the wrist + than the one before it. A skeleton whose joints arrive in another order than ``FINGER_SLOTS`` assumes + breaks it in every pose, where one finger's tip is followed by the next finger's first joint. + """ + local = np.asarray(hand_local, dtype=np.float64) + # The recorder zeroes the whole matrix of a joint it has no pose for. + if not np.isclose(local[:, 3, 3], 1.0).all(): + return None + # The skeleton is relative to the wrist joint, so a joint's distance from the wrist is its own length. + reach = np.linalg.norm(local[:, :3, 3], axis=1) + return all(bool(np.all(np.diff(reach[list(slots)]) > 0.0)) for slots in FINGER_SLOTS.values()) + + +def joints_px(sample: HandSample, side: str, offset: WristOffset) -> np.ndarray: + """Pixels (25, 2) of a hand's joints in a sample under an offset; NaN where a joint has no pixel.""" + camera_from_wrist = sample.T_camera_world @ sample.controller_world[side] @ wrist_in_controller(offset) + joints = joints_in_wrist(side, sample.hand_local[side]) + return project(joints @ camera_from_wrist[:3, :3].T + camera_from_wrist[:3, 3], sample.intrinsics) + + +def _axis_aligned_rotations() -> tuple[np.ndarray, ...]: + """Every rotation that maps the coordinate axes onto one another: the signed permutations that are proper.""" + rotations = [] + for order in itertools.permutations(range(3)): + for signs in itertools.product((1.0, -1.0), repeat=3): + matrix = np.zeros((3, 3)) + matrix[range(3), order] = signs + # Half of the signed permutations are reflections, which no mounting can produce. + if np.linalg.det(matrix) > 0: + rotations.append(matrix) + return tuple(rotations) + + +#: Where a fit asked for many starts also starts from, so that some start is within reach of any mounting of +#: the controller. +AXIS_ALIGNED_ROTATIONS = _axis_aligned_rotations() + + +def _click_weights(earlier: np.ndarray) -> np.ndarray: + """Per-click weights with mean 1, given which clicks an earlier optimisation already used. + + When both kinds are present each kind shares half the weight, so clicks piling up over many rounds never + outvote the ones just added. A mean of 1 keeps residuals at pixel scale, where the outlier scale applies. + """ + weights = np.ones(len(earlier)) + # With one kind only there is nothing to balance, and every click weighs the same. + if earlier.any() and not earlier.all(): + weights[earlier] = 0.5 / earlier.sum() + weights[~earlier] = 0.5 / (~earlier).sum() + return weights / weights.mean() + + +@dataclass(frozen=True) +class _ClickSet: + """One hand's usable clicks as arrays with a row per click, so a wrist pose is scored against all at once.""" + + camera_from_controller: np.ndarray + tip_in_wrist: np.ndarray + clicked_px: np.ndarray + sqrt_weight: np.ndarray + #: ``(intrinsics, rows)`` for each distinct camera: the rows it saw, projected in a single call. + cameras: tuple[tuple[Intrinsics, np.ndarray], ...] + + def pixels(self, wrist_pose: np.ndarray) -> np.ndarray: + """Where each clicked fingertip projects when the wrist sits at ``wrist_pose`` in its controller.""" + in_controller = self.tip_in_wrist @ wrist_pose[:3, :3].T + wrist_pose[:3, 3] + rotation, translation = self.camera_from_controller[:, :3, :3], self.camera_from_controller[:, :3, 3] + in_camera = np.einsum("nij,nj->ni", rotation, in_controller) + translation + pixels = np.full((len(in_camera), 2), np.nan) + # Each camera has its own intrinsics, so each projects the rows it saw. + for intrinsics, rows in self.cameras: + pixels[rows] = project(in_camera[rows], intrinsics) + return pixels + + def residuals(self, wrist_pose: np.ndarray) -> np.ndarray: + """Weighted pixel errors, u then v per click, with a constant where a fingertip has no pixel.""" + errors = (self.pixels(wrist_pose) - self.clicked_px) * self.sqrt_weight[:, None] + # A NaN would stop the solver; a large constant makes leaving the camera's view costly instead. + return np.nan_to_num(errors, nan=_NO_PIXEL_RESIDUAL_PX).ravel() + + def rms_px(self, wrist_pose: np.ndarray) -> float: + """The unweighted per-fingertip pixel error at ``wrist_pose``, as a root mean square.""" + errors = np.nan_to_num(self.pixels(wrist_pose) - self.clicked_px, nan=_NO_PIXEL_RESIDUAL_PX) + return float(np.sqrt(2.0 * np.mean(errors**2))) + + +def _usable_clicks( + samples: Sequence[HandSample], clicks: Sequence[Click], side: str, start: WristOffset +) -> list[Click]: + """The clicks of ``side`` that a fit starting at ``start`` can use.""" + usable = [] + for click in clicks: + sample, finger = samples[click[0]], click[2] + # A click on a hand whose glove gave no pose in that frame points at a placeholder skeleton. + if click[1] != side or not sample.hand_valid[side]: + continue + # A fingertip with no pixel at the start gives the solver a constant to chase, not an error to shrink. + if np.isfinite(joints_px(sample, side, start)[TIP_SLOTS[finger]]).all(): + usable.append(click) + return usable + + +def _click_set( + samples: Sequence[HandSample], clicks: Sequence[Click], side: str, earlier: Collection[ClickKey] +) -> _ClickSet: + """Lay out one hand's clicks for scoring, weighted by which of them an earlier optimisation used.""" + cameras: dict[tuple[str, bytes, bytes], tuple[Intrinsics, list[int]]] = {} + camera_from_controller, tips = [], [] + for row, (sample_index, _, finger, _, _) in enumerate(clicks): + sample = samples[sample_index] + camera_from_controller.append(sample.T_camera_world @ sample.controller_world[side]) + tips.append(joints_in_wrist(side, sample.hand_local[side])[TIP_SLOTS[finger]]) + # Samples of one take share a camera; grouping by its model and numbers lets one call project all of + # them. The model is part of what tells cameras apart: the same numbers mean another lens under it. + camera = sample.intrinsics + key = (camera.model, np.asarray(camera.K).tobytes(), np.asarray(camera.dist).tobytes()) + cameras.setdefault(key, (camera, []))[1].append(row) + used_before = np.array([tuple(click[:3]) in earlier for click in clicks]) + return _ClickSet( + camera_from_controller=np.array(camera_from_controller), + tip_in_wrist=np.array(tips), + clicked_px=np.array([click[3:5] for click in clicks], dtype=np.float64), + sqrt_weight=np.sqrt(_click_weights(used_before)), + cameras=tuple((camera, np.array(rows)) for camera, rows in cameras.values()), + ) + + +def _solve(clicks: _ClickSet, base: np.ndarray, translation: np.ndarray) -> tuple[float, np.ndarray, bool]: + """Fit from the wrist rotation ``base``: the robust cost reached, the wrist pose that reaches it, and + whether that pose's translation ended on its bound. + + The rotation unknowns are the Euler angles of a turn applied after ``base``, starting at zero, where + they are well behaved. Do not solve for the offset's own angles instead: an answer across the half-turn + bound from the start is then out of reach, and near a quarter turn about Y two of the angles merge. + """ + + def wrist_pose(unknowns: np.ndarray) -> np.ndarray: + """The wrist in its controller for a turn after ``base`` and a translation.""" + return homogeneous(np.eye(3), -unknowns[3:]) @ base @ euler_pose(*unknowns[:3]) + + # A start beyond the bound, which a file from another tool can hold, begins on the bound; a fit that + # stays there is reported as stopped by it. + start = np.concatenate([np.zeros(3), np.clip(translation, -TRANSLATION_BOUND_M, TRANSLATION_BOUND_M)]) + # The soft loss keeps one badly placed click, or a start that throws fingertips far off, from trapping + # the fit the way a plain sum of squares does. + solution = least_squares( + lambda unknowns: clicks.residuals(wrist_pose(unknowns)), + start, + bounds=(-_BOUNDS, _BOUNDS), + x_scale=_STEP_SCALE, + loss="soft_l1", + f_scale=_OUTLIER_SCALE_PX, + max_nfev=_MAX_EVALUATIONS, + ) + # A shift resting on the bound was stopped by it, and neither the cost nor the pose shows that. + on_bound = bool(np.any(np.abs(solution.x[3:]) > TRANSLATION_BOUND_M - _ON_BOUND_M)) + return float(solution.cost), wrist_pose(solution.x), on_bound + + +def optimize( + samples: Sequence[HandSample], + clicks: Sequence[Click], + side: str, + start: WristOffset, + *, + earlier: Collection[ClickKey] = frozenset(), + multi_start: bool = False, +) -> FitResult | None: + """Fit one hand's offset to its clicked fingertips, or ``None`` with fewer than three usable clicks. + + ``earlier`` holds the keys of clicks an earlier optimisation already used, which then share half the + weight. ``multi_start`` also tries every axis-aligned rotation and keeps the lowest robust cost: one + start, a zero offset or an installed one the controller no longer sits at, can be too far from the + answer in rotation to reach it. A fit that the translation bound stopped is returned with + ``at_translation_limit`` set. + """ + usable = _usable_clicks(samples, clicks, side, start) + # Too few clicks leave the offset free to slide; the caller keeps the offset it had. + if len(usable) < _MIN_CLICKS: + return None + scored = _click_set(samples, usable, side, earlier) + turns = [euler_pose(*start.rot_deg)] + # The controller can be strapped on any way round, and some axis-aligned turn is near every way. + if multi_start: + turns += [homogeneous(rotation, np.zeros(3)) for rotation in AXIS_ALIGNED_ROTATIONS] + translation = np.asarray(start.trans_m, dtype=np.float64) + # Every start scores the same clicks with the same weights, so their costs compare directly. + _, pose, on_bound = min((_solve(scored, _CORR @ turn, translation) for turn in turns), key=lambda fit: fit[0]) + result = FitResult( + offset=offset_from_wrist_in_controller(pose), + rms_px=scored.rms_px(pose), + n_clicks=len(usable), + at_translation_limit=on_bound, + ) + _LOG.info("wrist offset fit, %s hand: %d clicks, %.2f px RMS", side, result.n_clicks, result.rms_px) + # The RMS of a fit the bound stopped can look ordinary, so the log names what the number hides. + if on_bound: + _LOG.warning( + "wrist offset fit, %s hand: stopped on the %.2f m translation bound", side, TRANSLATION_BOUND_M + ) + return result + + +def offsets_record( + offsets: Mapping[str, WristOffset], *, n_samples: int, now: datetime | None = None +) -> dict[str, Any]: + """The saved file's content for both hands' offsets, fitted on ``n_samples`` frames. + + ``now`` is the calibration time and defaults to the present; it is written with its offset from UTC. + """ + # A time without a zone is taken as local, so the stamp always says how far it is from UTC. + moment = (datetime.now() if now is None else now).astimezone() + record: dict[str, Any] = { + "calibrated_at": moment.isoformat(timespec="seconds"), + # The offsets are from the OpenXR controller pose, and are wrong for any other tracking of the wrist. + POSE_SOURCE_KEY: OPENXR_POSES, + "note": _NOTE, + "n_samples": int(n_samples), + "corr_left_deg": list(CORR_DEG), + "corr_right_deg": list(CORR_DEG), + } + for side in SIDES: + rotation, translation = export_offset(offsets[side]) + # The first two are this tool's own unknowns; readers use only the exported pair after them. + record[side] = { + "rot_about_origin_deg": list(offsets[side].rot_deg), + "trans_offset_m": list(offsets[side].trans_m), + f"hand_{side}_pico_rotation": rotation.tolist(), + f"hand_{side}_pico_translation": translation.tolist(), + } + return record + + +def _numbers(entry: Mapping[str, Any], key: str, shape: tuple[int, ...], name: str) -> np.ndarray: + """A finite array of the given shape from one hand's entry of the saved file.""" + # Text or ragged lists cannot become numbers at all, nor can a whole number too large for a float; the + # operator is told which key, not shown a trace. + try: + values = np.asarray(entry.get(key), dtype=np.float64) + except (TypeError, ValueError, OverflowError): + raise CalibrationFileError(f"{name}: {key} is not numeric") from None + # A missing key arrives here as a lone NaN and fails on shape like any other wrong size. + if values.shape != shape or not np.all(np.isfinite(values)): + size = "x".join(str(n) for n in shape) + raise CalibrationFileError(f"{name}: {key} must hold {size} finite numbers") + return values + + +def offsets_from_record(record: Mapping[str, Any], name: str = WRIST_OFFSETS) -> dict[str, WristOffset]: + """Both hands' offsets from a saved file's record; ``name`` is the file named in an error. + + They are read through the exported rotation and translation, which mean the same whatever produced the + file; its ``rot_about_origin_deg`` and ``trans_offset_m`` depend on the base their producer started from. + The correction applied is this module's own, whatever the file's ``corr_*_deg`` say. + + Only the record's shape is read here. Whether its numbers are for this project's controller pose is the + record's ``pose_source`` stamp to say, and ``files.pose_source_problem`` reads it: a caller that builds + on the offsets asks that first, since another tracking source's offsets have this very shape. + """ + offsets = {} + for side in SIDES: + entry = record.get(side) + # A file holding one hand, or something else under a hand's name, is not a calibration to start from. + if not isinstance(entry, dict): + raise CalibrationFileError(f"{name}: the {side} hand's entry is missing") + rotation = _numbers(entry, f"hand_{side}_pico_rotation", (3, 3), name) + translation = _numbers(entry, f"hand_{side}_pico_translation", (3,), name) + # Anything else would be bent into the nearest rotation without a word: an offset nobody solved. + if not np.allclose(rotation @ rotation.T, np.eye(3), atol=1e-6) or np.linalg.det(rotation) < 0: + raise CalibrationFileError(f"{name}: hand_{side}_pico_rotation is not a rotation matrix") + offsets[side] = offset_from_export(rotation, translation) + return offsets diff --git a/examples/egocap/recording/egocap/recording/aligned_writer.py b/examples/egocap/recording/egocap/recording/aligned_writer.py index d3184821af..2eb631079c 100644 --- a/examples/egocap/recording/egocap/recording/aligned_writer.py +++ b/examples/egocap/recording/egocap/recording/aligned_writer.py @@ -11,17 +11,25 @@ array, the attributes, the session's ``config.yaml`` and sidecars, and the videos are carried over unchanged. The aligned root's ``zarr.json`` records which source was the index. -This module writes the files; the caller chooses the times, qualification and the staging that makes publication +A camera's pictures are older than their recorded times say by the lag the headset calibration measured. When +the head-camera extrinsics file the session carries states that lag, it is taken off every camera's times +before pictures are paired with tracking (see :mod:`egocap.calibration.camera_lag` for the rule), and the +aligned episode's ``camera_lag`` attribute says what was taken off and what it was made from. An aligned +episode without that attribute was aligned on the recorded times as they are: its session has no such file, +or one that states no lag, cannot be read, or was not made with this project's tracking. + +This module writes the files; the caller chooses the qualification and the staging that makes publication all-or-nothing. """ from __future__ import annotations import json +import logging import os import shutil import tempfile -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any @@ -29,6 +37,18 @@ import yaml import zarr +from egocap.calibration.board import CalibrationError +from egocap.calibration.camera_lag import CAMERA_LAG_KEY, TRACKING_LATENCY_KEY, CameraLag, camera_lag_of_take +from egocap.calibration.files import ( + HEAD_EXTRINSICS, + ROLE_LENS_INTRINSICS, + CalibrationFileError, + absent, + pose_source_problem, + read_json_object, +) +from egocap.calibration.take import CalibrationTake + from .alignment import AlignedEpisode, align_episode, check_continuity, qualified_sources, source_rules from .episode_layout import ( FINALIZATION_KEEP, @@ -40,6 +60,7 @@ __all__ = [ "ALIGNED_SESSION_SIDECARS", + "CAMERA_LAG_ATTR", "AlignedWriteError", "align_kept_episode", "check_kept_episode", @@ -48,7 +69,11 @@ "write_aligned_episode", ] -#: Session-level files carried into the aligned session when the raw session has them. +logger = logging.getLogger("isaaccapture.egocap.aligned_writer") + +#: Session-level files carried into the aligned session when the raw session has them. A session whose video +#: was corrected while it was recorded holds, per corrected camera, the lens file its correction was built +#: from beside the file describing the recorded picture; a reader needs both, so both are carried. ALIGNED_SESSION_SIDECARS = ( "config.yaml", "data_check_config.yaml", @@ -58,7 +83,11 @@ "left_wrist_camera_intrinsics.json", "right_wrist_camera_intrinsics.json", "rectification.json", + *ROLE_LENS_INTRINSICS.values(), ) +#: The aligned episode's attribute saying what was taken off its cameras' times and what that was made from. +#: Written only when the session states a lag, so its absence means the recorded times were aligned as they are. +CAMERA_LAG_ATTR = "camera_lag" #: Video container suffixes that are carried into the aligned episode. _VIDEO_SUFFIXES = (".mp4", ".mkv", ".avi", ".mov") #: Arrays at most this large are read back by validation to catch stale or empty chunks. @@ -122,6 +151,53 @@ def _write_root(raw_session: Path, aligned_session: Path, index_source: str) -> shutil.copy2(source, target) +def _session_camera_lag(raw_session: Path, episode_dir: Path) -> CameraLag | None: + """How far the take's pictures lag its tracking, from the head-camera extrinsics file its session carries; + None when the session states no lag that can be used, and the take then aligns on its recorded times. + + A session states none when it has no such file, or one that cannot be read, was not made with this + project's tracking, or holds no lag. Raises ``AlignedWriteError`` when the lag was stored for a stated + tracking latency and the take does not say which it was recorded under: pairing its pictures on a guess + would be wrong without a sign of it. + """ + path = raw_session / HEAD_EXTRINSICS + # A session recorded before the station's headset was calibrated carries no such file. + if absent(path): + return None + try: + record = read_json_object(path) + except CalibrationFileError as exc: + # A recorded session is never mended, so a damaged file must not keep its takes from being aligned: + # it states no lag, and the log says why nothing was taken off. + logger.warning("%s; pictures are paired with tracking unshifted", exc) + return None + # A lag measured against another tracking source's times is no lag against this take's tracking, and no + # tool of this project builds on such a file. + untrusted = pose_source_problem(record, HEAD_EXTRINSICS) + if untrusted is not None: + logger.warning("%s; pictures are paired with tracking unshifted", untrusted) + return None + try: + lag = camera_lag_of_take(record, CalibrationTake(episode_dir).tracking_latency_s()) + except CalibrationError as exc: + # The library's sentence names no directory, so it is the refusal as it stands. + raise AlignedWriteError(str(exc)) from None + return lag if lag.stated else None + + +def _camera_lag_record(lag: CameraLag, cameras: Sequence[str]) -> dict[str, Any]: + """What an aligned episode says about the lag taken off its cameras' times: the figure, the cameras it came + off, and the values it was made from, the stored ones under the names the extrinsics file gives them.""" + return { + "taken_off_s": lag.seconds, + "cameras": list(cameras), + "source": HEAD_EXTRINSICS, + CAMERA_LAG_KEY: lag.stored_s, + TRACKING_LATENCY_KEY: lag.solved_under_s, + "take_tracking_latency_s": lag.recorded_under_s, + } + + def _write_source(raw_group: Any, target_group: Any, aligned_source: Any) -> None: """Write one source: its attributes, the raw arrays that are not resampled, and what the alignment adds.""" _copy_attrs(raw_group, target_group) @@ -190,7 +266,10 @@ def write_aligned_episode( ``qualified`` says, per source, whether its recorded capture time is a qualified event time (a measured one, or a configured estimate the recorder already applied). A source that is not, or is not listed, refuses the - alignment, so nothing is written for it. The times aligned on are the recorded capture times, used unchanged. + alignment, so nothing is written for it. The times aligned on are the recorded capture times, less, for + every camera, the lag the session's head-camera extrinsics file states (see ``_session_camera_lag``); the + episode's ``camera_lag`` attribute records it, and a session that states none is aligned on the recorded + times and gains no such attribute. ``continuity`` is the episode's stored per-source continuity evidence (None if it recorded none): a source whose evidence is missing, unknown or records a break refuses it too. Raises ``AlignedWriteError`` if the written episode does not validate. @@ -214,13 +293,18 @@ def write_aligned_episode( if broken: raise AlignedWriteError("; ".join(broken)) fields = {name: {a: raw_episode[name][a][:] for a in raw_episode[name].array_keys()} for name in present} + recorded_cameras = [c for c in cameras if c in present] + # One lag for every camera: the head camera's is the only one a headset calibration can measure, and it is + # taken to hold for the station's other cameras, whose pictures are stamped the same way. + lag = _session_camera_lag(raw_session, raw_session / key) aligned = align_episode( index_source, times, - [c for c in cameras if c in present], + recorded_cameras, fields, {name: rules[name] for name in present}, downsample=downsample, + camera_lag_s=0.0 if lag is None else lag.seconds, ) _write_root(raw_session, aligned_session, index_source) @@ -230,6 +314,9 @@ def write_aligned_episode( raise AlignedWriteError(f"{key} already exists in the aligned session") episode = root.require_group(key) _copy_attrs(raw_episode, episode) + # Said only when the session states a lag, so a reader tells such an episode from one aligned without. + if lag is not None: + episode.attrs[CAMERA_LAG_ATTR] = _camera_lag_record(lag, recorded_cameras) episode["valid_indices"] = aligned.valid_indices episode["valid_timestamps"] = aligned.valid_timestamps for name in present: diff --git a/examples/egocap/recording/egocap/recording/alignment.py b/examples/egocap/recording/egocap/recording/alignment.py index 0c8569ece2..353c6ad1ae 100644 --- a/examples/egocap/recording/egocap/recording/alignment.py +++ b/examples/egocap/recording/egocap/recording/alignment.py @@ -8,6 +8,9 @@ aligned dataset format and are implemented exactly as stated, because consumers read the result by array name and expect these values: +* a camera's picture can be older than its recorded time says by a measured lag; the lag comes off every + camera's times first, so a picture is paired with the tracking of the moment it shows, and a camera's times + in the rules below are its times with the lag taken off; * the valid range runs from the latest first time to the earliest last time over all sources; an index frame is kept when it is in that range and on the downsampling stride (``valid_indices``, ``valid_timestamps``); * a camera other than the index source contributes the position of its frame nearest each kept time @@ -18,8 +21,8 @@ transforms: linear position, slerp rotation), ``linear`` (element-wise, also used for a 4x4 field with extra leading dimensions) or ``nearest`` (the value at the nearest sample); ``raw`` fields are not resampled. -There is no file access here. The times passed in are the ones to align on: each source's recorded capture time, -used exactly as given and never adjusted here. +There is no file access here. The times passed in are each source's recorded capture time; the only adjustment +made to them is the camera lag the caller passes, which is zero unless the caller knows one. """ from __future__ import annotations @@ -211,11 +214,13 @@ class AlignedEpisode: index_source: str #: Boolean mask over the index source's frames: in the valid range and on the downsampling stride. valid_indices: np.ndarray - #: The index source's times at the kept frames. + #: The index source's times at the kept frames, less the camera lag when the index source is a camera. valid_timestamps: np.ndarray #: The valid range that was used, as (first, last). valid_range: tuple[float, float] sources: dict[str, AlignedSource] + #: Seconds taken off every camera's recorded times before anything was paired. + camera_lag_s: float = 0.0 #: How each field of a frame type is resampled when an episode is time aligned. A session's config.yaml names the @@ -274,12 +279,18 @@ def source_rules(config: Mapping[str, object]) -> dict[str, dict[str, FieldRule] return rules -def _check_inputs(index_source: str, times: Mapping[str, np.ndarray], downsample: int) -> None: - """Refuse input that cannot be aligned: a missing index source, a bad stride, or unusable times.""" +def _check_inputs( + index_source: str, times: Mapping[str, np.ndarray], downsample: int, camera_lag_s: float +) -> None: + """Refuse input that cannot be aligned: a missing index source, a bad stride, a lag that is no number of + seconds, or unusable times.""" if index_source not in times: raise AlignmentError(f"the index source {index_source!r} has no times") if downsample < 1: raise AlignmentError("downsample must be at least 1") + # A lag that is not finite would turn every camera time into one no range contains. + if not np.isfinite(camera_lag_s): + raise AlignmentError("the camera lag must be a finite number of seconds") for name, source_times in times.items(): arr = np.asarray(source_times) # The forward walk and the range logic assume sorted, finite times. @@ -297,16 +308,25 @@ def align_episode( rules: Mapping[str, Mapping[str, FieldRule]], *, downsample: int = 1, + camera_lag_s: float = 0.0, ) -> AlignedEpisode: """Align every source in ``times`` onto ``index_source``. - ``times`` maps each source to the times to align on (sorted, finite); ``cameras`` names the sources that are + ``times`` maps each source to its recorded times (sorted, finite); ``cameras`` names the sources that are cameras; ``fields[source][name]`` are a source's arrays and ``rules[source][name]`` how each is resampled (a - field with no rule is not resampled). Raises ``AlignmentError`` if the index source has no frame in the valid - range, so an alignment is never an empty success. + field with no rule is not resampled). ``camera_lag_s`` is how much older every camera's picture is than + its recorded time says, against the other sources' times: it is taken off the cameras' times before + anything is paired, so ``valid_timestamps`` of a camera index are its recorded times less the lag. Raises + ``AlignmentError`` if the index source has no frame in the valid range, so an alignment is never an empty + success. """ - _check_inputs(index_source, times, downsample) - index_times = np.asarray(times[index_source], dtype=np.float64) + _check_inputs(index_source, times, downsample, camera_lag_s) + # Taking off a lag of zero leaves a time as it is to the last bit, so an episode with no lag is untouched. + times = { + name: np.asarray(recorded, dtype=np.float64) - (camera_lag_s if name in cameras else 0.0) + for name, recorded in times.items() + } + index_times = times[index_source] # The valid range: every source has data on both sides of a kept time. lo = max(float(np.min(t)) for t in times.values()) @@ -322,7 +342,6 @@ def align_episode( sources: dict[str, AlignedSource] = {} for name, source_times in times.items(): - source_times = np.asarray(source_times, dtype=np.float64) interpolated: dict[str, np.ndarray] = {} for field_name, rule in rules.get(name, {}).items(): # A rule for a field that was not recorded, or a raw field, adds nothing. @@ -342,4 +361,4 @@ def align_episode( else find_nearest_timestamp_indices(source_times, kept) ) sources[name] = AlignedSource(frames, interpolated) - return AlignedEpisode(index_source, valid, kept, (lo, hi), sources) + return AlignedEpisode(index_source, valid, kept, (lo, hi), sources, float(camera_lag_s)) diff --git a/examples/egocap/recording/tools/align_episode.py b/examples/egocap/recording/tools/align_episode.py index a657869704..eed5741a26 100755 --- a/examples/egocap/recording/tools/align_episode.py +++ b/examples/egocap/recording/tools/align_episode.py @@ -8,7 +8,9 @@ The raw session is only read. The episode's stored continuity evidence comes from its manifest, and which sources have a qualified event time from the episode's own ``timing`` attribute; an episode that lacks either is -refused with the reason, never assumed good. +refused with the reason, never assumed good. When the head-camera extrinsics file the session carries states +the camera's lag, it is taken off the cameras' times before pictures are paired with tracking; the line printed +on success says how much was taken off, or that nothing was. Usage (from any directory outside ``egocap`` itself):: @@ -68,7 +70,9 @@ def main(argv: list[str] | None = None) -> int: print(f"not aligned: {exc}", file=sys.stderr) return 1 kept, total = int(aligned.valid_indices.sum()), len(aligned.valid_indices) - print(f"aligned episode_{args.episode}: {kept} of {total} frames") + # Said either way: a take aligned without the lag looks the same in every other respect. + lag = f"{aligned.camera_lag_s * 1000.0:.1f} ms of" if aligned.camera_lag_s else "no" + print(f"aligned episode_{args.episode}: {kept} of {total} frames, {lag} camera lag taken off") return 0 diff --git a/examples/egocap/recording/tools/calibrate_station.py b/examples/egocap/recording/tools/calibrate_station.py new file mode 100755 index 0000000000..4a519bf4f0 --- /dev/null +++ b/examples/egocap/recording/tools/calibrate_station.py @@ -0,0 +1,1018 @@ +#!/usr/bin/env python + +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Calibrate a station camera from a recorded take, write a rectified copy of a take, or build a remap table. + +``camera`` and ``rectify`` only read the take, and write nothing into the recorded session the take lies in. +``camera`` runs the solve the Headset calibration tool runs and writes its review files to ``--out``; with +``--install`` the parts the grade allows are installed into the station's calibration directory. A take recorded +already corrected is treated as the page treats it: its lens is not solved, and its position is solved against +the corrected picture's camera. ``rectify`` +writes the named cameras' videos again, corrected into the picture asked for, into a new directory outside the +recorded session. Each is corrected with the intrinsics frozen in the take's own session, or the station's where +the session holds none, and the report says which. ``table`` plans one camera's rectification from the station's +intrinsics and writes the remap table a camera bridge's ``rectify`` step loads, for bringing a bridge up by hand. + +Where the corrected picture is much smaller than the camera's, one pass of the correction skips source pixels. +``--oversample N`` corrects into a picture N times the output size a side and box-filters it down by N, which is +what a station whose rectification plan states that oversample publishes and records. ``rectify`` without the +option uses the oversample each camera needs; ``table`` without it plans none, and says which would be needed. + +Whether a take's video was recorded corrected is written in its session, beside the episode. A take named +outside the session it was recorded in cannot say, and ``camera`` and ``rectify`` refuse it unless +``--video-as-received`` states that its video was recorded without rectification. + +Usage, from this example's ``egocap`` directory:: + + uv run python recording/tools/calibrate_station.py camera EPISODE_DIR --camera NAME \ + --role {ego,wrist_left,wrist_right} [--mode {both,intrinsic,extrinsic}] [--model {pinhole,fisheye}] \ + [--squares 14x9] [--square-mm 40] [--marker-mm 30] [--dictionary DICT_5X5_1000] \ + [--camera-latency-ms auto] [--latency-search-ms 200] [--scan-step 1] [--picks 30] [--out DIR] \ + [--calibration-dir DIR] [--install --operator NAME] [--video-as-received] [--verbose] + + uv run python recording/tools/calibrate_station.py rectify EPISODE_DIR --camera ROLE=NAME \ + [--camera ROLE=NAME ...] [--out DIR] [--calibration-dir DIR] [--out-size 640x480] [--balance 0] \ + [--fov-scale 1] [--matrix FX FY CX CY] [--allow-border] [--oversample N] [--encoder NAME] \ + [--video-as-received] [--verbose] + + uv run python recording/tools/calibrate_station.py table --role {ego,wrist_left,wrist_right} \ + --source-size WxH --out FILE [--out-size WxH] [--balance 0] [--fov-scale 1] \ + [--matrix FX FY CX CY] [--allow-border] [--oversample N] [--calibration-divisor D] \ + [--calibration-dir DIR] [--verbose] + +``camera`` exits 0 when the take was solved, whatever its grade, and 1 when it could not be solved, a file +could not be written or a place it was told to write is refused. ``rectify`` exits 0 when at least one camera +was rectified and 1 otherwise, ``table`` 0 when the table was written and 1 otherwise. An argument error exits +2. Progress and the reason for a failure are on stderr, the reason as one line. ``--verbose`` adds the log +there, and with it the traceback of a failure ``camera`` has no words for. +""" + +from __future__ import annotations + +import argparse +import contextlib +import logging +import math +import os +import shutil +import sys +from collections.abc import Iterator +from datetime import datetime +from pathlib import Path +from typing import Any, get_args + +from egocap.calibration import station_store +from egocap.calibration.board import BoardError, BoardSpec, CalibrationError +from egocap.calibration.camera_pipeline import ( + DEFAULT_LAG_SEARCH_S, + DEFAULT_PICKS, + MODES, + CameraCalibrationResult, + run_camera_calibration, +) +from egocap.calibration.files import ( + FISHEYE, + HEAD_EXTRINSICS, + PINHOLE, + ROLE_INTRINSICS, + CalibrationFileError, + absent, + intrinsics_identity, + load_intrinsics, +) +from egocap.calibration.rectification_files import ( + TAKE_OUTSIDE_SESSION, + TAKE_RECORDED_CORRECTED, + TakeCamera, + TakeRecordError, + camera_as_recorded, + declared_divisor, + knows_how_recorded, + recorded_rectification, + take_sessions, +) +from egocap.calibration.rectify import ( + OutputGeometry, + RectificationError, + RectificationPlan, + RemapTableError, + checked_geometry, + plan_rectification, + read_remap_table, + share_text, + write_remap_table, +) +from egocap.calibration.rectify_take import ( + DEFAULT_ENCODER, + CameraRectification, + RectifyTakeError, + default_rectified_dir, + rectify_episode, +) +from egocap.calibration.take import CalibrationTake +from egocap.core.data_root import calibration_dir +from egocap.recording.video_writer_backends import VideoEncoderKind + +logger = logging.getLogger("isaaccapture.egocap.calibrate_station") + +#: The logger this tool and the calibration library both log under, which ``--verbose`` shows. +_LOG_ROOT = "isaaccapture.egocap" +#: The role whose camera rides on the tracked headset, the only one with a position to solve. +_HEAD_ROLE = "ego" +#: The subcommands. +_CAMERA, _RECTIFY, _TABLE = "camera", "rectify", "table" +#: The default board is the library's, so the page and this tool cannot drift apart. +_BOARD = BoardSpec() +#: The word that has the camera's lag found from the take. +_AUTO = "auto" +#: The furthest either side of no lag the search may be sent, in milliseconds. A camera lags its tracking by tens +#: of milliseconds, and every step of the range is one more solve: without a bound a slip of the hand asks for a +#: search that does not end. +_MAX_LATENCY_SEARCH_MS = 1000.0 +#: How an operator states what a take outside its session cannot: said after the library's sentence. +_AS_RECEIVED_HINT = "; pass --video-as-received if it was recorded without rectification" +#: The size rectified videos are written at unless another is asked for. +_OUT_SIZE = (640, 480) +#: The balance and the field-of-view scale of a view nobody chose: what both arguments default to. +_FITTED_VIEW = (0.0, 1.0) +#: Frames between progress lines for a video whose container does not say how many frames it holds. +_UNDECLARED_STEP = 100 +#: The program the encoders named after it launch to write a video; it is looked for on PATH. +_FFMPEG = "ffmpeg" + + +def _pair(text: str) -> tuple[int, int]: + """Two whole numbers written ``AxB``, as a board's squares and an image size are given.""" + # One part, three parts and a part that is no number all fail here, in the unpacking or the conversion. + try: + first, second = (int(part) for part in text.lower().split("x")) + except ValueError: + raise argparse.ArgumentTypeError(f"{text!r} is not two whole numbers written like 14x9") from None + return first, second + + +def _count(text: str) -> int: + """A whole number of at least 1.""" + # Text that is no number is refused in the same words as a number that is too small. + try: + value = int(text) + except ValueError: + value = 0 + if value < 1: + raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1") + return value + + +def _finite(text: str) -> float: + """A finite number; ``float`` alone would accept ``nan`` and ``inf``.""" + # Text that is no number joins the two that are numbers only in name. + try: + value = float(text) + except ValueError: + value = math.nan + if not math.isfinite(value): + raise argparse.ArgumentTypeError(f"{text!r} is not a number") + return value + + +def _positive(text: str) -> float: + """A finite number above zero.""" + value = _finite(text) + # A search range reaches that far either side of a lag; nothing reaches zero or less. + if not value > 0: + raise argparse.ArgumentTypeError(f"{text!r} is not more than 0") + return value + + +def _search_range(text: str) -> float: + """How far either side of no lag to look, in milliseconds: above zero and no further than the bound.""" + value = _positive(text) + if value > _MAX_LATENCY_SEARCH_MS: + raise argparse.ArgumentTypeError( + f"{text!r} is more than {_MAX_LATENCY_SEARCH_MS:g}, the furthest a camera's lag is looked for" + ) + return value + + +def _latency(text: str) -> float | None: + """A camera lag in milliseconds to use as given, or None for ``auto``: find the lag from the take.""" + return None if text.lower() == _AUTO else _finite(text) + + +def _role_camera(text: str) -> tuple[str, str]: + """A camera named ``ROLE=NAME``: the station role whose intrinsics rectify the video ``NAME.mp4``.""" + role, separator, name = text.partition("=") + # A role decides which calibration file is used, so one this station has no file for is refused here. + if not separator or role not in ROLE_INTRINSICS or not name: + raise argparse.ArgumentTypeError( + f"{text!r} is not ROLE=NAME, where ROLE is one of {', '.join(ROLE_INTRINSICS)} " + "and NAME is a camera in the take" + ) + return role, name + + +def _add_take(parser: argparse.ArgumentParser) -> None: + """The recorded take a subcommand reads, and what an operator may state about it.""" + parser.add_argument( + "episode", type=Path, metavar="EPISODE_DIR", help="the recorded take, read and never written" + ) + parser.add_argument( + "--video-as-received", + action="store_true", + help="state that the take's video was recorded as received, without rectification; needed for a take " + "named outside the session it was recorded in, where the record of a corrected run is kept", + ) + + +def _add_common(parser: argparse.ArgumentParser, used_for: str = "") -> None: + """The arguments every subcommand takes; ``used_for`` says what this one reads the calibration files for.""" + parser.add_argument( + "--calibration-dir", + type=Path, + metavar="DIR", + help=f"the station's calibration directory{used_for} (default: $EGOCAP_CALIBRATION_DIR, or " + "/calibration)", + ) + parser.add_argument( + "--verbose", + action="store_true", + help="show the log on stderr, and with it the traceback of a failure the tool has no words for", + ) + + +def _add_camera_parser(commands: Any) -> None: + """The ``camera`` subcommand: solve one camera from a take.""" + parser = commands.add_parser(_CAMERA, help="solve a camera's calibration from a recorded take") + _add_take(parser) + _add_common(parser) + parser.add_argument("--camera", required=True, metavar="NAME", help="the camera's name in the take") + parser.add_argument("--role", required=True, choices=tuple(ROLE_INTRINSICS), help="the station role it fills") + parser.add_argument( + "--mode", choices=MODES, help="what to solve (default: both for ego, intrinsic for a wrist role)" + ) + parser.add_argument( + "--model", + choices=(PINHOLE, FISHEYE), + help=f"the lens model the intrinsics are solved under: {PINHOLE} (OpenCV's radial-tangential model) or " + f"{FISHEYE} (OpenCV's fisheye model, for a wide-angle lens) (default {PINHOLE})", + ) + squares = f"{_BOARD.squares[0]}x{_BOARD.squares[1]}" + parser.add_argument( + "--squares", type=_pair, default=_BOARD.squares, metavar="COLSxROWS", help=f"the board (default {squares})" + ) + parser.add_argument( + "--square-mm", + type=float, + default=1000.0 * _BOARD.square_length_m, + metavar="MM", + help="side of a square (default %(default)g)", + ) + parser.add_argument( + "--marker-mm", + type=float, + default=1000.0 * _BOARD.marker_length_m, + metavar="MM", + help="side of a marker (default %(default)g)", + ) + parser.add_argument( + "--dictionary", + default=_BOARD.dictionary, + metavar="DICT", + help="the ArUco dictionary (default %(default)s)", + ) + parser.add_argument( + "--camera-latency-ms", + type=_latency, + metavar=f"MS|{_AUTO}", + help="how far the camera's frame times lag the head tracking: a number to use as it is given, or " + f"{_AUTO} to find the lag from the take (default {_AUTO})", + ) + parser.add_argument( + "--latency-search-ms", + type=_search_range, + metavar="MS", + help=f"with {_AUTO}, how far either side of no lag to look, at most {_MAX_LATENCY_SEARCH_MS:g} " + f"(default {1000.0 * DEFAULT_LAG_SEARCH_S:g})", + ) + parser.add_argument( + "--scan-step", type=_count, default=1, metavar="N", help="look at every N-th frame only (default 1)" + ) + parser.add_argument( + "--picks", + type=_count, + default=DEFAULT_PICKS, + metavar="N", + help="frames to solve from (default %(default)s)", + ) + parser.add_argument( + "--out", + type=Path, + metavar="DIR", + help="the review folder: a new or empty one outside the recorded session " + f"(default: /{station_store.RUNS_DIR}/