bboxes
sleap_nn.data.bboxes
¶
Bounding-box ground truth, augmentation geometry and training targets.
Shared by the bbox_* detection model types (bbox_centernet, bbox_ssd):
- Ground truth. Boxes come from
LabeledFrame.bboxes(sio.UserBoundingBox). :func:add_bboxes_to_labelscan derive them in memory from pose instances or segmentation masks through sleap-io (Instance.to_bbox/SegmentationMask.to_bbox), so a pose dataset trains a detector unchanged. - Geometry. A box rides the shared augmentation chain (size-match, scale, pad,
rotate, scale, translate, flip) as a 4-corner pseudo-instance
(:func:
bboxes_to_corners) and is re-boxed afterwards as the corners' extent (:func:corners_to_bboxes), then clipped to the frame (:func:clip_bboxes). - Targets. One encoder per detection style turns a frame's boxes into the dense
tensors its loss reads: :class:
CenterNetTargetEncoder(center heatmap + size and offset maps) and :class:SSDTargetEncoder(per-anchor class + box targets). The matching decoders live in :mod:sleap_nn.inference.bbox.
Box coordinates are (x1, y1, x2, y2) in pixels, with the same convention as
pose keypoints (a pixel's center is at its integer coordinate).
Classes:
| Name | Description |
|---|---|
CenterNetTargetEncoder |
Frame boxes -> CenterNet training targets. |
SSDTargetEncoder |
Frame boxes -> SSD training targets. |
Functions:
| Name | Description |
|---|---|
add_bboxes_to_labels |
Give every frame of |
anchor_shapes |
|
auto_anchor_sizes |
Per-level SSD anchor sizes spanning the training boxes' size range. |
bbox_category_name |
The class name of a box; boxes without a category are |
bbox_head_categories |
Ordered class names of a |
bbox_head_leaf |
The head config leaf of a |
bbox_size_stats |
|
bboxes_to_corners |
|
clip_bboxes |
Clip boxes to the frame and flag the ones still worth supervising. |
corners_to_bboxes |
|
decode_boxes |
Inverse of :func: |
draw_gaussian |
Max-merge an unnormalized Gaussian (peak 1) centered at |
encode_boxes |
SSD box encoding of matched |
frame_bbox_arrays |
A frame's user boxes as |
frame_user_bboxes |
A frame's usable user boxes: not predicted and not degenerate. |
gaussian_radius |
CenterNet's size-adaptive Gaussian radius for a |
get_bbox_target_encoder |
The target encoder of a |
instance_crop_bbox |
The box a box-scaled crop of one pose instance is cut from. |
labels_bbox_categories |
Ordered category names of the user boxes in |
make_anchors |
All anchors of an |
match_anchors |
Assign each anchor to a box (SSD/RetinaNet matching). |
resolve_bbox_source |
Resolve |
CenterNetTargetEncoder
¶
Frame boxes -> CenterNet training targets.
For each box, the center cell floor(center / stride) gets a Gaussian peak
of 1 in its class's heatmap channel, the box size in grid cells in the size
map, and the center's sub-cell position in the offset map; reg_mask marks
the center cells (where size/offset are supervised). Two boxes whose centers
fall in the same cell: the later one wins the regression targets (as in
CenterNet).
Attributes:
| Name | Type | Description |
|---|---|---|
num_classes |
Heatmap channels. |
|
output_stride |
Heatmap stride relative to the input. |
|
sigma |
Fixed Gaussian sigma in input pixels, or |
|
min_overlap |
IoU for the size-adaptive radius. |
Methods:
| Name | Description |
|---|---|
__call__ |
Encode |
__init__ |
Initialize the encoder. |
Source code in sleap_nn/data/bboxes.py
__call__(boxes, classes, img_hw)
¶
Encode (n, 4) boxes / (n,) classes for an img_hw input.
Returns:
| Type | Description |
|---|---|
Dict[str, Tensor]
|
|
Source code in sleap_nn/data/bboxes.py
__init__(num_classes, output_stride, sigma=None, min_overlap=0.7)
¶
Initialize the encoder.
Source code in sleap_nn/data/bboxes.py
SSDTargetEncoder
¶
Frame boxes -> SSD training targets.
Attributes:
| Name | Type | Description |
|---|---|---|
num_classes |
Foreground classes (logit 0 is background). |
|
strides |
Pyramid level strides, finest first. |
|
sizes |
Base anchor size per level (input pixels). |
|
scales |
Anchor size multipliers. |
|
aspect_ratios |
Anchor |
|
pos_iou_threshold, |
neg_iou_threshold
|
Matching thresholds
(:func: |
variances |
Box-coding variances (:func: |
Methods:
| Name | Description |
|---|---|
__call__ |
Encode |
__init__ |
Initialize the encoder. |
anchors |
|
Source code in sleap_nn/data/bboxes.py
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | |
anchors_per_location
property
¶
Anchors at each feature-map cell of every level.
__call__(boxes, classes, img_hw)
¶
Encode (n, 4) boxes / (n,) classes for an img_hw input.
Returns:
| Type | Description |
|---|---|
Dict[str, Tensor]
|
|
Source code in sleap_nn/data/bboxes.py
__init__(num_classes, strides, sizes, scales, aspect_ratios, pos_iou_threshold=0.5, neg_iou_threshold=0.4, variances=(0.1, 0.1, 0.2, 0.2))
¶
Initialize the encoder.
Source code in sleap_nn/data/bboxes.py
anchors(img_hw)
¶
(A, 4) anchors of an img_hw input (cached per size).
Source code in sleap_nn/data/bboxes.py
add_bboxes_to_labels(labels, source='auto', padding=0.0)
¶
Give every frame of labels its ground-truth boxes for source, in place.
With bboxes the frames are left as they are. With instances / masks
each frame's user boxes are replaced (in memory) by boxes derived from its user
pose instances / user masks through sleap-io, padded by padding pixels.
Derived boxes keep the source's track and link back to it (box.instance).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
Labels to modify. |
required |
source
|
str
|
One of |
'auto'
|
padding
|
float
|
Pixels added on every side of derived boxes. |
0.0
|
Returns:
| Type | Description |
|---|---|
str
|
The resolved source. |
Source code in sleap_nn/data/bboxes.py
anchor_shapes(size, scales, aspect_ratios)
¶
(w, h) of one level's anchors: every scale x aspect ratio (h / w).
Source code in sleap_nn/data/bboxes.py
auto_anchor_sizes(box_sizes, num_levels, strides)
¶
Per-level SSD anchor sizes spanning the training boxes' size range.
Geometrically spaced between the 5th and 95th percentile of sqrt(w * h) (a
single level takes the median). Without boxes, falls back to RetinaNet's
4 * stride.
Source code in sleap_nn/data/bboxes.py
bbox_category_name(box)
¶
The class name of a box; boxes without a category are "object".
Source code in sleap_nn/data/bboxes.py
bbox_head_categories(model_type, head_configs)
¶
Ordered class names of a bbox_* model (["object"] when unset).
Source code in sleap_nn/data/bboxes.py
bbox_head_leaf(model_type, head_configs)
¶
The head config leaf of a bbox_* model that holds its categories.
Source code in sleap_nn/data/bboxes.py
bbox_size_stats(labels_list, max_hw=None, scale=1.0)
¶
sqrt(w * h) of every user box in labels_list, in model-input pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels_list
|
Sequence[Labels]
|
Labels to measure. |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The size matcher's |
None
|
scale
|
float
|
|
1.0
|
Source code in sleap_nn/data/bboxes.py
bboxes_to_corners(xyxy)
¶
(n, 4) xyxy boxes -> (n, 4, 2) corners (TL, TR, BR, BL).
Source code in sleap_nn/data/bboxes.py
clip_bboxes(xyxy, img_hw, min_size=2.0, min_visible_fraction=0.25)
¶
Clip boxes to the frame and flag the ones still worth supervising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyxy
|
Tensor
|
|
required |
img_hw
|
Tuple[int, int]
|
|
required |
min_size
|
float
|
Boxes narrower or shorter than this after clipping are dropped. |
2.0
|
min_visible_fraction
|
float
|
Boxes keeping less than this fraction of their area inside the frame (e.g. after a translation) are dropped. |
0.25
|
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor]
|
|
Source code in sleap_nn/data/bboxes.py
corners_to_bboxes(corners)
¶
(..., 4, 2) corners -> (..., 4) axis-aligned xyxy extent.
After a rotation this is the rotated box's enclosing axis-aligned box (the standard treatment of boxes under rotation augmentation).
Source code in sleap_nn/data/bboxes.py
decode_boxes(deltas, anchors, variances)
¶
Inverse of :func:encode_boxes: (..., A, 4) deltas -> xyxy boxes.
Source code in sleap_nn/data/bboxes.py
draw_gaussian(heatmap, cx, cy, sigma)
¶
Max-merge an unnormalized Gaussian (peak 1) centered at (cx, cy), in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
heatmap
|
Tensor
|
|
required |
cx
|
float
|
Center x in heatmap cells (an integer cell gives an exact peak of 1). |
required |
cy
|
float
|
Center y in heatmap cells. |
required |
sigma
|
float
|
Standard deviation in cells. |
required |
Source code in sleap_nn/data/bboxes.py
encode_boxes(boxes, anchors, variances)
¶
SSD box encoding of matched (A, 4) xyxy boxes relative to their anchors.
((cx - acx) / aw / v0, (cy - acy) / ah / v1, log(w / aw) / v2, log(h / ah) / v3).
Source code in sleap_nn/data/bboxes.py
frame_bbox_arrays(lf, categories)
¶
A frame's user boxes as (n, 4) float32 xyxy and (n,) int64 class ids.
Boxes whose category is not in categories are skipped (with a single-class
detector every box is class 0).
Source code in sleap_nn/data/bboxes.py
frame_user_bboxes(lf)
¶
A frame's usable user boxes: not predicted and not degenerate.
Source code in sleap_nn/data/bboxes.py
gaussian_radius(height, width, min_overlap=0.7)
¶
CenterNet's size-adaptive Gaussian radius for a height x width box.
The smallest of the three radii at which shifting the box's corners keeps IoU
=
min_overlapwith the original (CornerNet, Law & Deng 2018), exactly as in the CenterNet reference implementation.
Source code in sleap_nn/data/bboxes.py
get_bbox_target_encoder(model_type, head_configs)
¶
The target encoder of a bbox_* model from its head config leaves.
Source code in sleap_nn/data/bboxes.py
instance_crop_bbox(lf, inst, source, padding=0.0)
¶
The box a box-scaled crop of one pose instance is cut from.
Used by the crop_mode="bbox" centered-instance datasets, it derives the box
the way :func:add_bboxes_to_labels derives a detector's ground truth, so a
detector and a centered-instance model trained with the same bbox_source /
bbox_padding agree on what a box is:
bboxes: the frame's user box linked toinst(box.instance), as is;masks: the user mask linked toinst(mask.instance), padded;instances-- or no linked box/mask -- the tight box of the instance's visible keypoints, padded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lf
|
LabeledFrame
|
The instance's frame. |
required |
inst
|
Instance
|
The pose instance. |
required |
source
|
str
|
A resolved bbox source (:func: |
required |
padding
|
float
|
Pixels added on every side of derived boxes. |
0.0
|
Returns:
| Type | Description |
|---|---|
Optional[ndarray]
|
|
Source code in sleap_nn/data/bboxes.py
labels_bbox_categories(labels_list)
¶
Ordered category names of the user boxes in labels_list (first seen first).
Returns ["object"] when no box carries a category, so a class-agnostic
dataset gets a single-class detector.
Source code in sleap_nn/data/bboxes.py
make_anchors(img_hw, strides, sizes, scales, aspect_ratios)
¶
All anchors of an img_hw input as (A, 4) xyxy, in head output order.
Order: level (finest first), then row, column, anchor shape -- the order the
SSD head flattens its per-level (B, A_l * K, h, w) maps in
(:class:sleap_nn.architectures.heads.SSDHead). Anchor centers sit at
(index + 0.5) * stride.
Source code in sleap_nn/data/bboxes.py
match_anchors(boxes, anchors, pos_iou_threshold=0.5, neg_iou_threshold=0.4)
¶
Assign each anchor to a box (SSD/RetinaNet matching).
An anchor is positive for the box it overlaps most if that IoU is >=
pos_iou_threshold, background if its best IoU is < neg_iou_threshold, and
ignored in between. Each box's highest-IoU anchor is forced positive for it, so
no box goes unmatched however poorly the anchors fit; when two boxes share a
best anchor, the one that overlaps it more keeps it and the other takes its
best anchor not already claimed.
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor]
|
|
Source code in sleap_nn/data/bboxes.py
resolve_bbox_source(labels, source='auto')
¶
Resolve data_config.bbox_source for one labels file.
auto picks bboxes when the file carries any user box, else instances
when it carries any user pose instance, else masks.