Skip to content

API Reference

This page provides detailed information about the Locus Python API.

Core Interface

The primary entry point is the Detector class. It can be initialized with various configuration parameters passed as keyword arguments.

import locus

# Initialize with keyword arguments
detector = locus.Detector(
    families=[locus.TagFamily.AprilTag36h11, locus.TagFamily.ArUco4x4_50],
    decimation=2,
    threads=4,
)

batch = detector.detect(img)

locus.Detector

High-level detector.

Construction

Detector(profile="standard") — load a shipped JSON profile by name. Detector(config=my_cfg) — use a pre-built :class:DetectorConfig. Detector() — equivalent to profile="standard".

Per-call orchestration options (decimation, threads, families) stay outside the profile because they describe how the detector is invoked, not what it looks for.

Source code in crates/locus-py/locus/__init__.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
class Detector:
    """High-level detector.

    Construction:
        ``Detector(profile="standard")`` — load a shipped JSON profile by name.
        ``Detector(config=my_cfg)`` — use a pre-built :class:`DetectorConfig`.
        ``Detector()`` — equivalent to ``profile="standard"``.

    Per-call orchestration options (``decimation``, ``threads``, ``families``)
    stay outside the profile because they describe *how* the detector is
    invoked, not *what* it looks for.
    """

    def __init__(
        self,
        profile: ProfileName | None = None,
        config: DetectorConfig | None = None,
        *,
        decimation: int | None = None,
        threads: int | None = None,
        families: list[TagFamily] | None = None,
    ) -> None:
        if profile is not None and config is not None:
            raise ValueError("Pass either `profile` or `config`, not both.")

        if config is None:
            config = DetectorConfig.from_profile(profile or "standard")

        if families is None:
            families = [TagFamily.AprilTag36h11]

        self._inner = _create_detector_from_config(
            config=config._to_ffi_config(),
            decimation=decimation,
            threads=threads,
            families=[int(f) for f in families],
        )

    def config(self) -> DetectorConfig:
        """Returns the current detector configuration as a nested model."""
        raw = self._inner.config()
        return DetectorConfig(
            threshold=ThresholdConfig(
                tile_size=raw.threshold_tile_size,
                min_range=raw.threshold_min_range,
                enable_sharpening=raw.enable_sharpening,
                enable_adaptive_window=raw.enable_adaptive_window,
                min_radius=raw.threshold_min_radius,
                max_radius=raw.threshold_max_radius,
                constant=raw.adaptive_threshold_constant,
                gradient_threshold=raw.adaptive_threshold_gradient_threshold,
            ),
            quad=QuadConfig(
                min_area=raw.quad_min_area,
                max_aspect_ratio=raw.quad_max_aspect_ratio,
                min_fill_ratio=raw.quad_min_fill_ratio,
                max_fill_ratio=raw.quad_max_fill_ratio,
                min_edge_length=raw.quad_min_edge_length,
                min_edge_score=raw.quad_min_edge_score,
                subpixel_refinement_sigma=raw.subpixel_refinement_sigma,
                upscale_factor=raw.upscale_factor,
                max_elongation=raw.quad_max_elongation,
                min_density=raw.quad_min_density,
                extraction_mode=raw.quad_extraction_mode,
                edlines_imbalance_gate=raw.edlines_imbalance_gate,
                edlines_phase3_erf=raw.edlines_phase3_erf,
            ),
            decoder=DecoderConfig(
                min_contrast=raw.decoder_min_contrast,
                refinement_mode=raw.refinement_mode,
                max_hamming_error=raw.max_hamming_error,
                gwlf_transversal_alpha=raw.gwlf_transversal_alpha,
            ),
            pose=PoseConfig(
                huber_delta_px=raw.huber_delta_px,
                tikhonov_alpha_max=raw.tikhonov_alpha_max,
                sigma_n_sq=raw.sigma_n_sq,
                structure_tensor_radius=raw.structure_tensor_radius,
            ),
            segmentation=SegmentationConfig(
                connectivity=raw.segmentation_connectivity,
                margin=raw.segmentation_margin,
            ),
        )

    def set_families(self, families: list[TagFamily]):
        """Update the tag families to be detected."""
        family_values = [int(f) for f in families]
        self._inner.set_families(family_values)

    def detect(
        self,
        img: np.ndarray,
        intrinsics: CameraIntrinsics | None = None,
        tag_size: float | None = None,
        debug_telemetry: bool = False,
        **kwargs,
    ) -> DetectionBatch:
        """
        Detect tags in the image.

        Args:
            img: Input grayscale image (np.uint8).
            intrinsics: Optional CameraIntrinsics for 3D pose estimation.
            tag_size: Optional physical tag size (meters).

        Returns:
            A vectorized DetectionBatch object.
        """
        if img.dtype != np.uint8:
            raise ValueError(f"Input image must be uint8, got {img.dtype}")

        raw = self._inner.detect(
            img,
            intrinsics=intrinsics,
            tag_size=tag_size,
            debug_telemetry=debug_telemetry,
            **kwargs,
        )

        telemetry = None
        if raw.telemetry is not None:
            t = raw.telemetry
            telemetry = PipelineTelemetry(
                binarized=t.binarized,
                threshold_map=t.threshold_map,
                gwlf_fallback_count=t.gwlf_fallback_count,
                gwlf_avg_delta=t.gwlf_avg_delta,
                subpixel_jitter=t.subpixel_jitter,
                reprojection_errors=t.reprojection_errors,
            )

        return DetectionBatch(
            ids=raw.ids,
            corners=raw.corners,
            error_rates=raw.error_rates,
            poses=raw.poses,
            rejected_corners=raw.rejected_corners,
            rejected_error_rates=raw.rejected_error_rates,
            rejected_funnel_status=raw.rejected_funnel_status,
            telemetry=telemetry,
        )

    def detect_concurrent(
        self,
        frames: list[np.ndarray],
        intrinsics: CameraIntrinsics | None = None,
        tag_size: float | None = None,
    ) -> list[DetectionBatch]:
        """
        Detect tags in multiple frames concurrently.

        Releases the GIL for the entire parallel section. Telemetry and
        rejected-corner data are not available via this method.

        Args:
            frames: List of grayscale uint8 images.
            intrinsics: Optional CameraIntrinsics for 3D pose estimation.
            tag_size: Optional physical tag size (meters).

        Returns:
            A list of DetectionBatch, one per input frame, in the same order.
        """
        for i, img in enumerate(frames):
            if img.dtype != np.uint8:
                raise ValueError(f"Frame {i} must be uint8, got {img.dtype}")

        raw_results = self._inner.detect_concurrent(
            frames,
            intrinsics=intrinsics,
            tag_size=tag_size,
        )

        return [
            DetectionBatch(
                ids=r.ids,
                corners=r.corners,
                error_rates=r.error_rates,
                poses=r.poses,
                rejected_corners=r.rejected_corners,
                rejected_error_rates=r.rejected_error_rates,
                rejected_funnel_status=r.rejected_funnel_status,
            )
            for r in raw_results
        ]

Functions

__init__

__init__(profile: ProfileName | None = None, config: DetectorConfig | None = None, *, decimation: int | None = None, threads: int | None = None, families: list[TagFamily] | None = None) -> None
Source code in crates/locus-py/locus/__init__.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def __init__(
    self,
    profile: ProfileName | None = None,
    config: DetectorConfig | None = None,
    *,
    decimation: int | None = None,
    threads: int | None = None,
    families: list[TagFamily] | None = None,
) -> None:
    if profile is not None and config is not None:
        raise ValueError("Pass either `profile` or `config`, not both.")

    if config is None:
        config = DetectorConfig.from_profile(profile or "standard")

    if families is None:
        families = [TagFamily.AprilTag36h11]

    self._inner = _create_detector_from_config(
        config=config._to_ffi_config(),
        decimation=decimation,
        threads=threads,
        families=[int(f) for f in families],
    )

detect

detect(img: ndarray, intrinsics: CameraIntrinsics | None = None, tag_size: float | None = None, debug_telemetry: bool = False, **kwargs) -> DetectionBatch

Detect tags in the image.

Parameters:

Name Type Description Default
img ndarray

Input grayscale image (np.uint8).

required
intrinsics CameraIntrinsics | None

Optional CameraIntrinsics for 3D pose estimation.

None
tag_size float | None

Optional physical tag size (meters).

None

Returns:

Type Description
DetectionBatch

A vectorized DetectionBatch object.

Source code in crates/locus-py/locus/__init__.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def detect(
    self,
    img: np.ndarray,
    intrinsics: CameraIntrinsics | None = None,
    tag_size: float | None = None,
    debug_telemetry: bool = False,
    **kwargs,
) -> DetectionBatch:
    """
    Detect tags in the image.

    Args:
        img: Input grayscale image (np.uint8).
        intrinsics: Optional CameraIntrinsics for 3D pose estimation.
        tag_size: Optional physical tag size (meters).

    Returns:
        A vectorized DetectionBatch object.
    """
    if img.dtype != np.uint8:
        raise ValueError(f"Input image must be uint8, got {img.dtype}")

    raw = self._inner.detect(
        img,
        intrinsics=intrinsics,
        tag_size=tag_size,
        debug_telemetry=debug_telemetry,
        **kwargs,
    )

    telemetry = None
    if raw.telemetry is not None:
        t = raw.telemetry
        telemetry = PipelineTelemetry(
            binarized=t.binarized,
            threshold_map=t.threshold_map,
            gwlf_fallback_count=t.gwlf_fallback_count,
            gwlf_avg_delta=t.gwlf_avg_delta,
            subpixel_jitter=t.subpixel_jitter,
            reprojection_errors=t.reprojection_errors,
        )

    return DetectionBatch(
        ids=raw.ids,
        corners=raw.corners,
        error_rates=raw.error_rates,
        poses=raw.poses,
        rejected_corners=raw.rejected_corners,
        rejected_error_rates=raw.rejected_error_rates,
        rejected_funnel_status=raw.rejected_funnel_status,
        telemetry=telemetry,
    )

Concurrent Detection

Detector supports concurrent multi-frame processing via detect_concurrent. To configure the internal pool size (max_concurrent_frames), you must use the DetectorBuilder.

See the Concurrent Detection how-to for full usage examples.

DetectorBuilder

The fluent builder is used to construct Detector instances with advanced settings not yet exposed in the primary Detector constructor, specifically max_concurrent_frames.

import locus

detector = (
    locus.DetectorBuilder()
    .with_family(locus.TagFamily.AprilTag36h11)
    .with_threads(4)
    .with_max_concurrent_frames(8) # Enable parallel batch processing
    .build()
)
Method Description
with_family(family) Add a tag family to detect.
with_decimation(n) Spatial decimation factor (default 1).
with_threads(n) Rayon intra-frame thread count (0 = all cores).
with_corner_refinement(mode) CornerRefinementMode for subpixel accuracy.
with_max_concurrent_frames(n) Pool size for detect_concurrent (default 1 = sequential).
build() Build the Detector.

detect_concurrent(frames, *, intrinsics=None, tag_size=None) -> list[DetectionResult]

Detect tags in multiple frames concurrently using Rayon. Releases the GIL for the entire parallel section. Pool contexts are managed internally. Rejected-corner data and telemetry are not available via this method.

Parameter Type Description
frames list[np.ndarray] List of (H, W) uint8 grayscale frames.
intrinsics CameraIntrinsics \| None Camera intrinsics for 3D pose estimation.
tag_size float \| None Physical tag side length in metres.

Configuration

Locus uses Pydantic for robust configuration validation.

locus.DetectorConfig

Bases: BaseModel

Nested detector configuration — Python source of truth.

The three shipped profiles live in crates/locus-core/profiles/*.json and are embedded into the Rust crate at compile time; the wheel reads the exact same bytes through the FFI. Load via :meth:from_profile for a shipped profile or :meth:from_profile_json for a user-supplied JSON string.

Source code in crates/locus-py/locus/_config.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
class DetectorConfig(BaseModel):
    """Nested detector configuration — Python source of truth.

    The three shipped profiles live in ``crates/locus-core/profiles/*.json``
    and are embedded into the Rust crate at compile time; the wheel reads
    the exact same bytes through the FFI. Load via :meth:`from_profile`
    for a shipped profile or :meth:`from_profile_json` for a user-supplied
    JSON string.
    """

    model_config = ConfigDict(extra="forbid", frozen=False, arbitrary_types_allowed=True)

    name: str | None = None
    extends: str | None = None
    threshold: ThresholdConfig = Field(default_factory=ThresholdConfig)
    quad: QuadConfig = Field(default_factory=QuadConfig)
    decoder: DecoderConfig = Field(default_factory=DecoderConfig)
    pose: PoseConfig = Field(default_factory=PoseConfig)
    segmentation: SegmentationConfig = Field(default_factory=SegmentationConfig)

    @model_validator(mode="after")
    def _check_extends_unresolved(self) -> DetectorConfig:
        if self.extends is not None:
            raise NotImplementedError(
                f"Profile inheritance (extends={self.extends!r}) is declared in the schema "
                "but not yet resolved by the loader. Inline the parent profile's values for "
                "now; resolution will land in a follow-up."
            )
        return self

    @model_validator(mode="after")
    def _check_cross_group_compat(self) -> DetectorConfig:
        if (
            self.quad.extraction_mode == QuadExtractionMode.EdLines
            and self.decoder.refinement_mode == CornerRefinementMode.Erf
        ):
            raise ValueError(
                "quad.extraction_mode=EdLines is incompatible with decoder.refinement_mode=Erf"
            )
        # Mirrors `DetectorConfig::validate` in `crates/locus-core/src/config.rs`.
        if isinstance(self.quad.extraction_policy, _AdaptivePpbPolicy):
            p = self.quad.extraction_policy.AdaptivePpb
            if p.low_extraction == p.high_extraction:
                raise ValueError(
                    "quad.extraction_policy.AdaptivePpb has identical low/high extraction "
                    'modes; use "Static" for single-mode operation'
                )
            # `threshold` bounds are already enforced by the Pydantic Field
            # constraints (gt=1.0, lt=5.0) on AdaptivePpbConfig; re-checking
            # here would duplicate the message surface.
            for ext, refine in (
                (p.low_extraction, p.low_refinement),
                (p.high_extraction, p.high_refinement),
            ):
                if ext == QuadExtractionMode.EdLines and refine == CornerRefinementMode.Erf:
                    raise ValueError(
                        "quad.extraction_policy.AdaptivePpb route uses EdLines with "
                        "refinement_mode=Erf, which is incompatible"
                    )
        return self

    @classmethod
    def from_profile(cls, name: ProfileName) -> DetectorConfig:
        """Load a shipped profile by name.

        General-purpose profiles must stay on ``QuadExtractionPolicy::Static``.
        Adaptive routing lives in explicit opt-in profiles
        (currently only ``max_recall_adaptive``).
        """
        if name not in SHIPPED_PROFILES:
            raise ValueError(
                f"Unknown shipped profile {name!r}; expected one of {sorted(SHIPPED_PROFILES)}"
            )
        cfg = cls.model_validate_json(_shipped_profile_json(name))
        if name in _STATIC_ONLY_PROFILES and cfg.quad.extraction_policy != "Static":
            raise ValueError(
                f'Shipped profile {name!r} must carry quad.extraction_policy="Static"; '
                "adaptive routing lives in opt-in profiles only"
            )
        return cfg

    @classmethod
    def from_profile_json(cls, json_str: str) -> DetectorConfig:
        """Load a user-supplied profile from a JSON string."""
        return cls.model_validate_json(json_str)

    def _to_ffi_config(self) -> PyDetectorConfig:
        # Cross-group validation has already fired in this Pydantic model;
        # Rust's `DetectorConfig::validate()` remains the final gate.
        #
        # `PyDetectorConfig` stays `Copy` on the Rust side, so the enum-shaped
        # `quad.extraction_policy` is flattened across a boolean discriminator
        # + five scalar fields here. Rust's `From<PyDetectorConfig>` rebuilds
        # the enum. See `crates/locus-py/src/lib.rs` for the round-trip.
        is_adaptive = isinstance(self.quad.extraction_policy, _AdaptivePpbPolicy)
        if is_adaptive:
            assert isinstance(self.quad.extraction_policy, _AdaptivePpbPolicy)
            p = self.quad.extraction_policy.AdaptivePpb
            ppb_threshold = p.threshold
            ppb_low_ext = p.low_extraction
            ppb_high_ext = p.high_extraction
            ppb_low_ref = p.low_refinement
            ppb_high_ref = p.high_refinement
        else:
            # Placeholder scalars — Rust's `From<PyDetectorConfig>` ignores
            # them when `quad_extraction_policy_is_adaptive == False`.
            ppb_threshold = 0.0
            ppb_low_ext = QuadExtractionMode.ContourRdp
            ppb_high_ext = QuadExtractionMode.EdLines
            ppb_low_ref = CornerRefinementMode.Erf
            ppb_high_ref = getattr(CornerRefinementMode, "None")

        return PyDetectorConfig(
            threshold_tile_size=self.threshold.tile_size,
            threshold_min_range=self.threshold.min_range,
            enable_sharpening=self.threshold.enable_sharpening,
            enable_adaptive_window=self.threshold.enable_adaptive_window,
            threshold_min_radius=self.threshold.min_radius,
            threshold_max_radius=self.threshold.max_radius,
            adaptive_threshold_constant=self.threshold.constant,
            adaptive_threshold_gradient_threshold=self.threshold.gradient_threshold,
            quad_min_area=self.quad.min_area,
            quad_max_aspect_ratio=self.quad.max_aspect_ratio,
            quad_min_fill_ratio=self.quad.min_fill_ratio,
            quad_max_fill_ratio=self.quad.max_fill_ratio,
            quad_min_edge_length=self.quad.min_edge_length,
            quad_min_edge_score=self.quad.min_edge_score,
            subpixel_refinement_sigma=self.quad.subpixel_refinement_sigma,
            upscale_factor=self.quad.upscale_factor,
            quad_max_elongation=self.quad.max_elongation,
            quad_min_density=self.quad.min_density,
            quad_extraction_mode=self.quad.extraction_mode,
            edlines_imbalance_gate=self.quad.edlines_imbalance_gate,
            edlines_phase3_erf=self.quad.edlines_phase3_erf,
            quad_extraction_policy_is_adaptive=is_adaptive,
            adaptive_ppb_threshold=ppb_threshold,
            adaptive_ppb_low_extraction=ppb_low_ext,
            adaptive_ppb_high_extraction=ppb_high_ext,
            adaptive_ppb_low_refinement=ppb_low_ref,
            adaptive_ppb_high_refinement=ppb_high_ref,
            decoder_min_contrast=self.decoder.min_contrast,
            refinement_mode=self.decoder.refinement_mode,
            max_hamming_error=self.decoder.max_hamming_error,
            gwlf_transversal_alpha=self.decoder.gwlf_transversal_alpha,
            post_decode_refinement=self.decoder.post_decode_refinement,
            huber_delta_px=self.pose.huber_delta_px,
            tikhonov_alpha_max=self.pose.tikhonov_alpha_max,
            sigma_n_sq=self.pose.sigma_n_sq,
            structure_tensor_radius=self.pose.structure_tensor_radius,
            pose_consistency_fpr=self.pose.pose_consistency_fpr,
            pose_consistency_gate_sigma_px=self.pose.pose_consistency_gate_sigma_px,
            pose_consistency_min_decisive_ratio=self.pose.pose_consistency_min_decisive_ratio,
            segmentation_connectivity=self.segmentation.connectivity,
            segmentation_margin=self.segmentation.margin,
        )

Functions

from_profile classmethod
from_profile(name: ProfileName) -> DetectorConfig

Load a shipped profile by name.

General-purpose profiles must stay on QuadExtractionPolicy::Static. Adaptive routing lives in explicit opt-in profiles (currently only max_recall_adaptive).

Source code in crates/locus-py/locus/_config.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
@classmethod
def from_profile(cls, name: ProfileName) -> DetectorConfig:
    """Load a shipped profile by name.

    General-purpose profiles must stay on ``QuadExtractionPolicy::Static``.
    Adaptive routing lives in explicit opt-in profiles
    (currently only ``max_recall_adaptive``).
    """
    if name not in SHIPPED_PROFILES:
        raise ValueError(
            f"Unknown shipped profile {name!r}; expected one of {sorted(SHIPPED_PROFILES)}"
        )
    cfg = cls.model_validate_json(_shipped_profile_json(name))
    if name in _STATIC_ONLY_PROFILES and cfg.quad.extraction_policy != "Static":
        raise ValueError(
            f'Shipped profile {name!r} must carry quad.extraction_policy="Static"; '
            "adaptive routing lives in opt-in profiles only"
        )
    return cfg
from_profile_json classmethod
from_profile_json(json_str: str) -> DetectorConfig

Load a user-supplied profile from a JSON string.

Source code in crates/locus-py/locus/_config.py
424
425
426
427
@classmethod
def from_profile_json(cls, json_str: str) -> DetectorConfig:
    """Load a user-supplied profile from a JSON string."""
    return cls.model_validate_json(json_str)

locus.DetectOptions

Bases: BaseModel

Per-call options for tag detection.

Source code in crates/locus-py/locus/_config.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
class DetectOptions(BaseModel):
    """Per-call options for tag detection."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

    families: list[TagFamily] = Field(default_factory=list)
    decimation: int = Field(default=1, ge=1)
    intrinsics: tuple[float, float, float, float] | CameraIntrinsics | None = Field(default=None)
    tag_size: float | None = Field(default=None, ge=0.0)

    @classmethod
    def all(cls) -> DetectOptions:
        return cls(
            families=[
                TagFamily.AprilTag36h11,
                TagFamily.ArUco4x4_50,
                TagFamily.ArUco4x4_100,
            ]
        )

Data Models

These classes represent the output and internal state of the detection pipeline.

locus.DetectionBatch dataclass

Vectorized detection results.

This dataclass contains parallel NumPy arrays representing a batch of detections.

Source code in crates/locus-py/locus/__init__.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@dataclass(frozen=True)
class DetectionBatch:
    """
    Vectorized detection results.

    This dataclass contains parallel NumPy arrays representing a batch of detections.
    """

    ids: np.ndarray  # Shape: (N,), Dtype: int32
    corners: np.ndarray  # Shape: (N, 4, 2), Dtype: float32
    error_rates: np.ndarray  # Shape: (N,), Dtype: float32
    poses: np.ndarray | None = None  # Shape: (N, 7), Dtype: float32. [tx, ty, tz, qx, qy, qz, qw]
    telemetry: "PipelineTelemetry | None" = None
    rejected_corners: np.ndarray | None = None  # Shape: (M, 4, 2), Dtype: float32
    rejected_error_rates: np.ndarray | None = None  # Shape: (M,), Dtype: float32
    # Shape: (M,), Dtype: uint8. Codes from `FunnelStatus`.
    rejected_funnel_status: np.ndarray | None = None

    @property
    def centers(self) -> np.ndarray:
        """Compute centers from corners: (N, 2)"""
        return np.mean(self.corners, axis=1)

    def __len__(self) -> int:
        return len(self.ids)

Attributes

centers property
centers: ndarray

Compute centers from corners: (N, 2)

locus.Pose

Geometry

locus.CameraIntrinsics

Board Pose Estimation

Locus supports board-level 6-DOF pose estimation for AprilGrid and ChAruco boards. All board types enforce dictionary bounds at construction time — a ValueError is raised if the board requires more marker IDs than the target TagFamily provides.

For the underlying algorithm, see Board-Level Pose Estimation.

AprilGrid

locus.AprilGrid(
    rows: int,
    cols: int,
    spacing: float,        # gap between markers (metres)
    marker_length: float,  # physical marker side length (metres)
    family: TagFamily,
)

Immutable topology for an AprilTag grid board. spacing = square_length - marker_length. Raises ValueError if rows * cols > family.max_id_count().

Attribute Type Description
rows int Number of tag rows.
cols int Number of tag columns.

CharucoBoard

locus.CharucoBoard(
    rows: int,
    cols: int,
    square_length: float,  # physical checkerboard square side (metres)
    marker_length: float,  # physical ArUco marker side (metres)
    family: TagFamily,
)

Immutable topology for a ChAruco board. Markers occupy squares where (row + col) is even. Saddle points are at the outer corners of each square ((rows-1)*(cols-1) total). Raises ValueError if the required marker count exceeds family.max_id_count().

Attribute Type Description
rows int Number of square rows.
cols int Number of square columns.

BoardEstimator

Unified stateful estimator for both AprilGrid and ChAruco boards. All scratch buffers are pre-allocated at construction; estimate() performs zero heap allocations.

Construction:

# AprilGrid board
estimator = locus.BoardEstimator(board: AprilGrid)

# ChAruco board
estimator = locus.BoardEstimator.from_charuco(board: CharucoBoard)

Estimation:

result: BoardEstimateResult = estimator.estimate(
    detector: locus.Detector,
    img: np.ndarray,           # (H, W) uint8 grayscale
    intrinsics: CameraIntrinsics,
)

BoardEstimateResult attributes:

Attribute Shape / Type Description
ids (N,) int32 Decoded tag IDs visible in this frame.
corners (N, 4, 2) float32 Refined tag corner image coordinates.
board_pose (7,) float64 or None [tx, ty, tz, qx, qy, qz, qw] in camera frame — None if insufficient observations. Pose origin is the board's top-left marker corner.
board_cov (6, 6) float64 or None Pose covariance in \(\mathfrak{se}(3)\) tangent space [t, ω].

Enumerations

locus.TagFamily

Bases: IntEnum

locus.CornerRefinementMode

Bases: IntEnum

locus.SegmentationConnectivity

Bases: IntEnum