utils
sleap_nn.tracking.utils
¶
Helper functions for Tracker module.
Classes:
| Name | Description |
|---|---|
MaskFeature |
Compact mask feature for fast IoU: a tight bbox crop + absolute offset. |
Functions:
| Name | Description |
|---|---|
compute_cosine_sim |
Return cosine similarity between appearance-embedding vectors |
compute_euclidean_distance |
Return the negative euclidean distance between vectors |
compute_iou |
Return the intersection over union for given a and b bounding boxes [xmin, ymin, xmax, ymax]. |
compute_mask_iou |
Return the IoU of two segmentation masks (higher = more similar). |
count_valid_points |
Number of valid points used to gate track spawning/matching. |
cull_frame_instances |
Removes instances (for single frame) over instance per frame threshold. |
cull_instances |
Removes instances from frames over instance per frame threshold. |
get_bbox |
Return the bounding box coordinates for the |
get_centroid |
Return the centroid of the |
get_embedding |
Return the appearance re-ID embedding vector for a detection. |
get_keypoints |
Return keypoints as np.array from the |
get_mask |
Return a compact :class: |
greedy_matching |
Match new instances to existing tracks using greedy bipartite matching. |
hungarian_matching |
Match new instances to existing tracks using Hungarian matching. |
is_segmentation_mask |
True if |
nms_fast |
From: https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/. |
nms_instances |
NMS for instances. |
MaskFeature
¶
Compact mask feature for fast IoU: a tight bbox crop + absolute offset.
A full-resolution segmentation mask (e.g. 1280x1024) is almost all
background, so the per-pair mask-IoU only needs the foreground bbox: store
the cropped boolean array (crop), its absolute top-left (y0, x0) in
the original image frame, and the foreground area (px, precomputed). IoU
between two features then AND-s only the overlap of their bboxes (usually
tiny or empty) and reads area in O(1) — vs. allocating + AND/OR-ing a
full-resolution canvas per pair. Coordinates are absolute, so this matches
the full-canvas :func:sleap_nn.evaluation._mask_iou exactly.
Methods:
| Name | Description |
|---|---|
__init__ |
Store the bbox crop, its absolute top-left |
Source code in sleap_nn/tracking/utils.py
__init__(crop, y0, x0, area)
¶
Store the bbox crop, its absolute top-left (y0, x0) and area.
compute_cosine_sim(a, b)
¶
Return cosine similarity between appearance-embedding vectors a and b.
The "cosine_sim" scoring method, paired with the "embeddings" feature
(:func:get_embedding). Higher = more similar (a similarity like oks /
iou; the cost negation cost = -score happens in
:meth:Tracker.scores_to_cost_matrix, so it must NOT be negated here).
Output range is [-1, 1].
Hardened against the degenerate inputs the embedding path can produce
(utils.py:249, SPEC §7): a None feature (a detection with no appearance
embedding -> :func:get_embedding returns None), a zero-norm vector, a
shape mismatch, or non-finite values all reduce to NaN rather than a
ZeroDivisionError / RuntimeWarning. NaN flows to inf cost in
:meth:Tracker.scores_to_cost_matrix (no match), so a missing/garbage
embedding spawns a fresh track instead of crashing the run.
Source code in sleap_nn/tracking/utils.py
compute_euclidean_distance(a, b)
¶
Return the negative euclidean distance between vectors a and b.
A similarity (higher = closer); the cost negation happens in
:meth:Tracker.scores_to_cost_matrix. Hardened against the same degenerate
inputs as :func:compute_cosine_sim (it is the one explicit alternative metric
for features="embeddings", so a detection lacking an appearance vector ->
:func:get_embedding returns None, and embeddings of differing dim can
co-occur): a None operand, an empty/shape-mismatched pair, or a non-finite
result reduces to NaN (-> inf cost -> no match) instead of raising. The
real-array centroid path is unaffected (its inputs are never None).
Source code in sleap_nn/tracking/utils.py
compute_iou(a, b)
¶
Return the intersection over union for given a and b bounding boxes [xmin, ymin, xmax, ymax].
Source code in sleap_nn/tracking/utils.py
compute_mask_iou(a, b)
¶
Return the IoU of two segmentation masks (higher = more similar).
The "mask_iou" scoring method. Operates on :class:MaskFeature (the
"masks" feature); raw dense bool arrays are accepted too (coerced via
:func:get_mask). The intersection is computed only over the overlap of
the two foreground bboxes — see :class:MaskFeature — which is numerically
identical to the full-canvas :func:sleap_nn.evaluation._mask_iou (top-left
aligned, shape-mismatch safe, empty/empty -> 1.0) but avoids touching the
background. This is a similarity, like oks/iou; the cost negation
(cost = -score) happens in :meth:Tracker.scores_to_cost_matrix, so it
must NOT be negated here. Pixel IoU (not bbox-IoU on mask.bbox) sidesteps
the XYWH-vs-XYXY bbox-format issue.
Source code in sleap_nn/tracking/utils.py
count_valid_points(obj)
¶
Number of valid points used to gate track spawning/matching.
For a keypoint instance this is the count of non-NaN nodes; for a
segmentation mask there are no keypoints, so the mask area (foreground px)
is the analogous "support" measure (min_new_track_points /
min_match_points then read as a pixel-area threshold; default 0 keeps
every non-empty mask and drops empty ones).
Source code in sleap_nn/tracking/utils.py
cull_frame_instances(instances_list, instance_count, iou_threshold=None)
¶
Removes instances (for single frame) over instance per frame threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances_list
|
List[PredictedInstance]
|
The list of instances for a single frame. |
required |
instance_count
|
int
|
The maximum number of instances we want per frame. |
required |
iou_threshold
|
Optional[float]
|
Intersection over Union (IOU) threshold to use when removing overlapping instances over target count; if None, then only use score to determine which instances to remove. |
None
|
Returns:
| Type | Description |
|---|---|
List[PredictedInstance]
|
Updated list of frames, also modifies frames in place. |
Source code in sleap_nn/tracking/utils.py
cull_instances(frames, instance_count, iou_threshold=None)
¶
Removes instances from frames over instance per frame threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
List[LabeledFrame]
|
The list of |
required |
instance_count
|
int
|
The maximum number of instances we want per frame. |
required |
iou_threshold
|
Optional[float]
|
Intersection over Union (IOU) threshold to use when removing overlapping instances over target count; if None, then only use score to determine which instances to remove. |
None
|
Returns:
| Type | Description |
|---|---|
|
The (possibly empty) input |
Source code in sleap_nn/tracking/utils.py
get_bbox(pred_instance)
¶
Return the bounding box coordinates for the PredictedInstance object.
Source code in sleap_nn/tracking/utils.py
get_centroid(pred_instance)
¶
Return the centroid of the PredictedInstance object.
Source code in sleap_nn/tracking/utils.py
get_embedding(pred_instance)
¶
Return the appearance re-ID embedding vector for a detection.
The "embeddings" feature extractor (mirrors :func:get_keypoints /
:func:get_mask). Reads the appearance vector attached by the embedding
(re-ID) model into the single identity_embedding slot (sleap-io #535); works
on any embedding-carrying detection (PredictedInstance or
PredictedSegmentationMask — both carry identity_embedding), so embedding
tracking is keypoint/mask agnostic. Scored by :func:compute_cosine_sim.
Returns the vector as a float32 np.ndarray of shape (D,), or
None when the detection carries no embedding. None is the "no feature"
sentinel: :func:compute_cosine_sim maps it to NaN (-> inf cost in
:meth:Tracker.scores_to_cost_matrix), so a detection that is missing its
embedding simply never matches and spawns a fresh track instead of crashing the
run. An np.ndarray is passed through unchanged (a precomputed feature).
Source code in sleap_nn/tracking/utils.py
get_keypoints(pred_instance)
¶
Return keypoints as np.array from the PredictedInstance object.
get_mask(pred_mask)
¶
Return a compact :class:MaskFeature for a PredictedSegmentationMask.
Mirrors :func:get_keypoints/:func:get_bbox as the "masks" feature
extractor. The mask is decoded onto the image-pixel grid first, then
cropped to its foreground bbox (using the mask's own .bbox when available,
avoiding a scan); the crop is cached as the candidate feature so scoring
reuses it without re-decoding and only touches the foreground region.
The image-grid decode is essential: sio .data decodes at the mask's
stored resolution, which for the default inference path
(full_res_masks=False, masks encoded at output-stride, scale~=0.5) is
NOT the image grid, while .bbox is always in IMAGE space. Cropping the
stride-res .data with image-space bbox indices would slice the wrong
region (often entirely out of bounds -> empty -> compute_mask_iou 1.0 for
every pair, scrambling identity). :func:decode_mask_to_image_res is a
zero-copy passthrough for scale==1 masks (legacy full-res), so that path
is unchanged.
Source code in sleap_nn/tracking/utils.py
greedy_matching(cost_matrix)
¶
Match new instances to existing tracks using greedy bipartite matching.
Source code in sleap_nn/tracking/utils.py
hungarian_matching(cost_matrix)
¶
Match new instances to existing tracks using Hungarian matching.
Source code in sleap_nn/tracking/utils.py
is_segmentation_mask(obj)
¶
True if obj is a segmentation mask rather than a keypoint instance.
Mask tracking flows sio.PredictedSegmentationMask objects through the
same code paths as sio.PredictedInstance; this is the single predicate
used to dispatch the pose-vs-mask differences (no .numpy() keypoints).
Source code in sleap_nn/tracking/utils.py
nms_fast(boxes, scores, iou_threshold, target_count=None)
¶
From: https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/.
Source code in sleap_nn/tracking/utils.py
nms_instances(instances, iou_threshold, target_count=None)
¶
NMS for instances.