SpatialEngine
spe.engine.SpatialEngine is a stateful local facade bundling a calibration, a calibrated grid size, and optional source dimensions.
from spe import SpatialEngine
engine = SpatialEngine(
grid_rows=4, # default 3
grid_columns=6, # default 3
source_dimensions={"width": 1280, "height": 720}, # optional
calibration=None, # optional pre-built Calibration or mapping
)
Constructor
SpatialEngine(
*,
calibration: Calibration | Mapping[str, Any] | None = None,
grid_rows: int = 3,
grid_columns: int = 3,
source_dimensions: Mapping[str, Any] | None = None,
) -> None
When calibration is supplied, its rows/columns override grid_rows/ grid_columns.
Attributes
| Attribute | Type | Description |
|---|---|---|
grid_rows | int | Calibrated grid row count. |
grid_columns | int | Calibrated grid column count. |
source_dimensions | dict | None | {"width": ..., "height": ...}. |
calibration | Calibration | None | The installed calibration, if any. |
State methods
calibrate
calibrate(
source_points: Sequence[Sequence[float]],
source_width: int,
source_height: int,
*,
reference_plane: ReferencePlane | None = None,
rows: int | None = None,
columns: int | None = None,
) -> Calibration
Validates four TL, TR, BR, BL points and installs a reusable calibration. rows/columns default to the engine's current grid size. Updates source_dimensions and returns the new Calibration.
Raises SPEValidationError for invalid geometry, or when the resolved grid rows or columns are not positive.
load_calibration
load_calibration(data: Calibration | Mapping[str, Any]) -> Calibration
Installs a previously serialized calibration and adopts its grid size.
clear_calibration
clear_calibration() -> None
Removes the installed calibration.
is_calibrated (property)
True when a calibration with a homography is installed.
Transform methods
These require a calibration and raise SPEEngineError when the engine is not calibrated.
| Method | Returns |
|---|---|
image_to_reference(points) | list[list[float]] — image points in reference coordinates. |
reference_to_image(points) | list[list[float]] — reference points in image coordinates. |
cell_for_reference_point(point) | GridCell | None. |
zone_for_reference_point(point) | str | None. |
cell_for_image_point(point) | GridCell | None. |
zone_for_image_point(point) | str | None. |
zones() | list[Zone] for the configured grid. |
Inspection
spatial_state
spatial_state() -> dict[str, Any]
Returns the canonical state contract consumed by inspect_point:
{
"calibration": {...}, # Calibration.to_dict()
"grid": {"rows": 4, "columns": 6},
"source_dimensions": {"width": 1280, "height": 720}, # when known
}
inspect
inspect(image_point: Sequence[float]) -> dict[str, Any]
Inspects one image-space point against the installed state. See inspect_point for the returned shape.
Spatialization
| Method | Description |
|---|---|
spatialize_detection(detection) | Enrich one detection mapping with spatial data. |
spatialize_result(result) | Enrich a normalized {"detections": [...]} result. |
spatialize(detections) | Enrich a sequence of detection mappings, returning a list. |
zone_polygons() | Map each zone id to its source-pixel quadrilateral. |
detections_in_zone(detections, zone) | Return spatialized detections in one zone. |
These require a calibration and raise SPEEngineError when uncalibrated. The per-detection payload matches spatialize_detection.
Rendering
render_grid
render_grid(
image: np.ndarray,
*,
rows: int = 8,
columns: int = 12,
line_thickness: int = 1,
line_color: tuple[int, int, int] = (91, 243, 168),
show_coordinates: bool = True,
) -> tuple[np.ndarray, dict]
Draws a regular image-space grid on a copy of image. This does not require a calibration. See generate_grid.
render_calibrated_grid
render_calibrated_grid(
image: np.ndarray,
*,
show_grid: bool = True,
show_roi: bool = True,
line_color: tuple[int, int, int] = (91, 243, 168),
roi_color: tuple[int, int, int] = (48, 59, 255),
overlay_only: bool = False,
) -> tuple[np.ndarray, dict]
Renders the calibrated grid, projected back into image space through the inverse homography. Requires a calibration (raises SPEEngineError otherwise). See generate_calibrated_grid.
Persistence
to_dict
to_dict() -> dict[str, Any]
{
"grid_rows": 4,
"grid_columns": 6,
"source_dimensions": {"width": 1280, "height": 720},
"calibration": {...} | None,
}
from_dict (classmethod)
SpatialEngine.from_dict(data: Mapping[str, Any]) -> SpatialEngine
Restores an engine from to_dict() output.
Value objects
All value objects live in spe.models and round-trip through to_dict() / from_dict().
BoundingBox
Frozen dataclass; an axis-aligned box in source-pixel coordinates.
BoundingBox(x: float, y: float, width: float, height: float)
Validation: x/y must be >= 0; width/height must be > 0.
| Member | Type | Description |
|---|---|---|
x, y, width, height | float | Box geometry. |
center (property) | dict[str, float] | {"x": ..., "y": ...} box center. |
foot_point (property) | dict[str, float] | Bottom-center {"x": ..., "y": ...}. |
area, x2, y2 (properties) | float | Area and right/bottom edges. |
as_xyxy() | tuple[float, float, float, float] | (x1, y1, x2, y2) bounds. |
from_xyxy(x1, y1, x2, y2) | BoundingBox | Classmethod; builds from corners. |
intersection(other) | BoundingBox | None | Overlapping box, or None. |
iou(other) | float | Intersection-over-union in [0, 1]. |
union(other) | BoundingBox | Smallest enclosing box. |
contains(point, *, strict=False) | bool | Point-in-box test; accepts a mapping or (x, y). |
translate(dx, dy) | BoundingBox | Shifted copy. |
scale(factor) | BoundingBox | Copy scaled about its center. |
to_dict() | dict | {"x", "y", "width", "height"}. |
from_dict(data) | BoundingBox | Classmethod. |
Detection
Frozen dataclass; a single perception observation in source pixels.
Detection(
class_name: str,
bbox: BoundingBox,
confidence: float = 0.0,
id: str | None = None,
class_id: int | None = None,
track_id: str | None = None,
coordinate_system: str = "source_pixels",
)
Validation: class_name must be non-empty; confidence must be within [0, 1]; coordinate_system must be "source_pixels".
to_dict() returns class_name, confidence, bbox, center, foot_point, coordinate_system, and (when set) id, class_id, track_id. from_dict accepts class_name or a label fallback.
ReferencePlane
Dataclass; the calibration target plane.
ReferencePlane(width: float = 1000, height: float = 600, units: str = "normalized")
from_dict(None) yields the defaults.
GridCell
Frozen dataclass.
GridCell(row: int, column: int)
coordinate (property) returns [column, row]. to_dict() returns {"row", "column", "coordinate"}.
Zone
Frozen dataclass.
Zone(id: str, row: int, column: int)
to_dict() returns {"id", "row", "column"}.
Calibration
Dataclass; a four-point planar calibration and its reusable transforms.
Fields
| Field | Type | Default |
|---|---|---|
source_points | list[list[float]] | — |
homography | list[list[float]] | None | — |
inverse_homography | list[list[float]] | None | — |
reference_plane | ReferencePlane | ReferencePlane() |
rows | int | 3 |
columns | int | 3 |
status | str | "calibrated" |
method | str | "manual_four_point" |
coordinate_system | str | "calibrated_reference_plane" |
point_order | Sequence[str] | POINT_ORDER |
destination_points | list[list[float]] | [] |
reprojection_error | float | 0.0 |
source_roi | dict | {} |
inlier_mask | list[int] | [] |
transformation | dict | {} |
Constructors
| Method | Description |
|---|---|
Calibration.from_points(source_points, source_width, source_height, reference_plane=None, rows=3, columns=3) | Compute a calibration from four points. |
Calibration.from_record(record, rows=None, columns=None) | Build from a calculate_calibration record. |
Calibration.from_dict(data) | Alias of from_record. |
Serialization and transforms
| Method | Description |
|---|---|
to_dict(*, include_grid=True) | Serialize; include_grid=False omits calibrated_grid. |
require_homography() | Return the image→reference matrix or raise SPEValidationError. |
require_inverse_homography() | Return the reference→image matrix or raise. |
image_to_reference(points) | Transform image points to reference coordinates. |
reference_to_image(points) | Transform reference points to image coordinates. |
cell_for(reference_point) | GridCell | None. |
zone_for(reference_point) | str | None. |
Geometry reference
spe.geometry. Constants:
| Name | Value |
|---|---|
REFERENCE_WIDTH | 1000 |
REFERENCE_HEIGHT | 600 |
POINT_ORDER | ("top_left", "top_right", "bottom_right", "bottom_left") |
calculate_calibration
calculate_calibration(
points, width, height,
reference_width=REFERENCE_WIDTH,
reference_height=REFERENCE_HEIGHT,
units="normalized",
) -> dict
Validates four TL, TR, BR, BL points and returns a calibration record:
{
"status": "calibrated",
"method": "manual_four_point",
"coordinate_system": "calibrated_reference_plane",
"point_order": ["top_left", "top_right", "bottom_right", "bottom_left"],
"source_points": [[x, y], ...],
"destination_points": [[x, y], ...],
"reference_plane": {"width": ..., "height": ..., "units": ...},
"roi": {"status": "active", "type": "calibrated_planar_region"},
"homography": [[...], [...], [...]],
"inverse_homography": [[...], [...], [...]],
"reprojection_error": 0.0,
"source_roi": {"area_px": ..., "area_percent": ...},
"transformation": {"direction": "image_to_calibrated_reference_plane", "reusable": True},
"inlier_mask": [...],
}
Raises SPEValidationError for invalid points, source dimensions, reference dimensions, or units.
calculate_homography
calculate_homography(source_points, destination_points) -> tuple[np.ndarray, np.ndarray]
Returns the 3 x 3 matrix and the per-point inlier mask (both NumPy arrays). Requires exactly four points per side.
validate_homography
validate_homography(homography) -> np.ndarray
Returns a finite, invertible 3 x 3 matrix as float64, else raises SPEValidationError.
transform_points
transform_points(points, homography) -> list[list[float]]
Transforms one point or many through homography. Non-finite results raise SPEValidationError.
inverse_homography
inverse_homography(homography) -> np.ndarray
Returns the inverse matrix normalized so that its [2, 2] element is 1.
reprojection_error
reprojection_error(source_points, destination_points, homography) -> float
Mean Euclidean destination-space error of the transformed source points.
warp_image
warp_image(image: np.ndarray, homography, width: int, height: int) -> np.ndarray
Warps an image into the reference plane using INTER_LINEAR. Requires a non-empty image and integer dimensions > 1.
validate_source_points
validate_source_points(points, width, height) -> np.ndarray
Validates TL, TR, BR, BL points against width x height (inside-frame, non-duplicate, convex, non-degenerate) and returns float32 coordinates.
Spatial reference
spe.spatial.
point_in_roi
point_in_roi(image_point, source_points) -> bool
True when the point is inside or on the four-point ROI.
image_to_spatial
image_to_spatial(image_point, calibration) -> dict
Maps one image point through an existing calibration record:
{
"x": ...,
"y": ...,
"coordinate_system": "calibrated_reference_plane",
"units": "normalized",
"width": ...,
"height": ...,
}
spatial_point_to_grid_cell
spatial_point_to_grid_cell(spatial_point, rows, columns, width, height) -> dict | None
Returns {"row": ..., "column": ..., "coordinate": [column, row]} or None when the point lies outside the plane. Boundary points clamp to the edge cell.
inspect_point
inspect_point(image_point, spatial_state) -> dict
Inspects a point using the canonical state contract produced by SpatialEngine.spatial_state().
- Invalid input returns status
"invalid"with areasonof"point_outside_image"or"calibration_unavailable". - A point outside the ROI returns status
"outside_roi"withimage,roi,reference: None,physical, andgrid_cell: None. - A valid point returns status
"valid"and addsreference,grid_cell, and (only when the units are notnormalized) a populatedphysicalblock.
spatialize_detection
spatialize_detection(detection, calibration, roi=None, grid=None) -> dict
Adds calibrated spatial data to one detection mapping without mutating its source-pixel fields. The ground point is the bottom-center (foot_point) of the bounding box. Returns:
{
"status": "valid" | "outside_roi" | "unavailable",
"ground_point": {"x", "y", "coordinate_system": "source_pixels", "units": "px"},
"position": {"x", "y", "coordinate_system", "units"} | None,
"grid_cell": {"row", "column", "coordinate"} | None,
"zone": "C4" | None,
"in_roi": bool | None,
"coordinate_system": "calibrated_reference_plane",
"units": str | None,
"reason": "invalid_bbox" | "calibration_unavailable" | "roi_unavailable" | "invalid_roi" | "spatialization_error",
}
reason is present only on unavailable results.
spatialize_detection_result
spatialize_detection_result(result, calibration, roi=None, grid=None) -> dict
Returns a copy of result with each entry in detections enriched under a "spatial" key.
Two aliases are defined in the module: is_point_in_spatial_roi (= point_in_roi) and point_to_grid_cell (= spatial_point_to_grid_cell).
Grid reference
spe.grid.
GridConfig
Frozen dataclass configuring an image-space grid.
GridConfig(
rows: int = 8,
columns: int = 12,
line_thickness: int = 1, # must be 1..12
show_coordinates: bool = True,
line_color: tuple[int, int, int] = (91, 243, 168), # 0..255 each
)
generate_grid
generate_grid(image: np.ndarray, config: GridConfig | None = None) -> tuple[np.ndarray, dict]
Draws a regular grid on a copy of image. The metadata dict reports the source size, grid geometry, coordinate_system: "image", and status: "grid generated".
generate_calibrated_grid
generate_calibrated_grid(
image, homography,
rows=4, columns=6,
reference_width=1000, reference_height=600,
source_points=None,
show_grid=True, show_roi=True,
line_color=(91, 243, 168), roi_color=(48, 59, 255),
overlay_only=False,
) -> tuple[np.ndarray, dict]
Projects reference-plane grid lines back into image space through the inverse homography. When overlay_only is True, the returned image is a 4-channel transparent overlay. Metadata reports the grid geometry, show_grid/show_roi/ overlay_only, the source size, coordinate_system: "calibrated_reference_plane", and status: "calibrated grid generated".
Zones reference
spe.zones.
row_label
row_label(index: int) -> str
Spreadsheet-style row label: A..Z, AA, AB, .... Rejects negative or non-integer input with SPEValidationError.
generate_zones
generate_zones(rows: int, columns: int) -> list[dict]
Returns every zone in row-major order, each {"id", "row", "column"}.
zone_for_cell
zone_for_cell(cell: dict | None, rows: int, columns: int) -> str | None
Returns the zone id for a grid-cell dict, or None when unknown.