instance_cropping
sleap_nn.data.instance_cropping
¶
Handle cropping of instances.
Classes:
| Name | Description |
|---|---|
BBoxCropSpec |
How a box-scaled centered-instance crop is cut ( |
Functions:
| Name | Description |
|---|---|
bbox_crop_window_sides |
Unfloored box-scaled crop window sides of every training instance. |
bbox_crop_windows |
Crop windows that resize each box to a |
clip_rects |
Clip |
compute_augmentation_padding |
Compute padding needed to accommodate augmentation transforms. |
count_clipped_instances |
Count labeled instances that a given crop size would clip. |
crop_windows |
Resample |
find_instance_crop_size |
Compute a crop size that contains every labeled instance. |
find_mask_crop_size |
Compute a crop size that contains every mask (the mask analog of |
find_max_instance_bbox_size |
Find the maximum bounding box dimension across all instances in labels. |
generate_crops |
Generate cropped image for the given centroid. |
iter_mask_extents |
Yield |
iter_required_crop_sizes |
Yield the crop size each labeled instance needs to avoid being clipped. |
letterbox_crops |
Zero the pixels of |
make_centered_bboxes |
Create centered bounding boxes around centroid. |
mask_foreground_rects |
A mask's foreground on the image-pixel grid, as disjoint rectangles. |
mask_rects_center |
The |
mask_rects_moments |
|
points_from_crop |
Map crop keypoints |
points_to_crop |
Map frame keypoints |
pre_crop_size |
Side of the training pre-crop that leaves room for rotation augmentation. |
rasterize_rects |
The |
scale_windows |
Grow (or shrink) |
window_corners |
|
BBoxCropSpec
dataclass
¶
How a box-scaled centered-instance crop is cut (crop_mode="bbox").
One object describes the crop for training (the datasets) and inference (the
top-down layer), built from the centered-instance model's config by
:meth:from_config.
Attributes:
| Name | Type | Description |
|---|---|---|
aspect |
str
|
|
padding |
float
|
|
min_size |
Optional[float]
|
|
bbox_source |
str
|
|
bbox_padding |
float
|
|
Methods:
| Name | Description |
|---|---|
__post_init__ |
Validate the aspect mode. |
from_config |
The spec of a training config, or |
windows |
:func: |
Source code in sleap_nn/data/instance_cropping.py
__post_init__()
¶
Validate the aspect mode.
from_config(config)
classmethod
¶
The spec of a training config, or None for crop_mode="fixed".
Source code in sleap_nn/data/instance_cropping.py
windows(boxes, crop_size)
¶
:func:bbox_crop_windows with this spec's aspect, padding and floor.
Source code in sleap_nn/data/instance_cropping.py
bbox_crop_window_sides(labels, spec, max_hw, user_instances_only=True)
¶
Unfloored box-scaled crop window sides of every training instance.
The window side is the padded box's longest side (square/letterbox) or
its larger padded extent (stretch), in size-matched pixels, before
min_size applies -- what :meth:ModelTrainer sizes crop_size and
crop_bbox_min_size from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
Training labels. |
required |
spec
|
BBoxCropSpec
|
The crop spec (its |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The size matcher's |
required |
user_instances_only
|
bool
|
Measure user instances only, as the dataset trains. |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in sleap_nn/data/instance_cropping.py
bbox_crop_windows(boxes, crop_size, aspect='square', padding=0.1, min_size=None)
¶
Crop windows that resize each box to a crop_size x crop_size crop.
Each box is padded on every side by padding times its longest side. For
square and letterbox the window is the square on the padded box's longest
side (one scale for both axes); for stretch it is the padded box itself (one
scale per axis). Window sides are floored at min_size (and 1 px) so a tiny
or degenerate box is not magnified without bound. Windows are centered on the
box center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boxes
|
Tensor
|
|
required |
crop_size
|
int
|
Output crop side in pixels. |
required |
aspect
|
str
|
One of :data: |
'square'
|
padding
|
float
|
Margin per side as a fraction of the box's longest side. |
0.1
|
min_size
|
Optional[float]
|
Smallest window side in frame pixels, or |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor, Tensor]
|
|
Source code in sleap_nn/data/instance_cropping.py
clip_rects(rects, frame_hw)
¶
Clip [y0, y1, x0, x1) rectangles to a (height, width) frame.
Source code in sleap_nn/data/instance_cropping.py
compute_augmentation_padding(bbox_size, rotation_max=0.0, scale_max=1.0)
¶
Compute padding needed to accommodate augmentation transforms.
When rotation and scaling augmentations are applied, the bounding box of an instance can expand beyond its original size. This function calculates the padding needed to ensure the full instance remains visible after augmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox_size
|
float
|
The size of the instance bounding box (max of width/height). |
required |
rotation_max
|
float
|
Maximum absolute rotation angle in degrees. For symmetric rotation ranges like [-180, 180], pass 180. |
0.0
|
scale_max
|
float
|
Maximum scaling factor. For scale range [0.9, 1.1], pass 1.1. |
1.0
|
Returns:
| Type | Description |
|---|---|
int
|
Padding in pixels to add around the bounding box (total, not per side). |
Source code in sleap_nn/data/instance_cropping.py
count_clipped_instances(labels, crop_size, max_hw=None, anchor_ind=None, centroid_method=None, centroid_fallback=None, user_instances_only=False, superseded_only=False)
¶
Count labeled instances that a given crop size would clip.
Used to warn about an explicitly configured crop_size, which we must not
silently override -- some users knowingly accept clipping an extremity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
crop_size
|
int
|
The configured crop size, in size-matched pixels. |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
anchor_ind
|
Optional[int]
|
Index of the anchor node, or |
None
|
centroid_method
|
Optional[str]
|
The resolved centroid method, or |
None
|
centroid_fallback
|
Optional[str]
|
The reduce method for a non-visible anchor node. |
None
|
user_instances_only
|
bool
|
When |
False
|
superseded_only
|
bool
|
See :func: |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[int, int, float]
|
|
Source code in sleap_nn/data/instance_cropping.py
crop_windows(images, windows, sample_inds, crop_size)
¶
Resample crop_size x crop_size crops of windows (inference path).
Reproduces the training crops of crop_and_resize_skia for the same window:
one bilinear sample per output pixel at its center, clamped to the frame's edge
pixels, then weighted -- like Skia's antialiased draw -- by how much of the
output pixel's footprint lies inside the frame, so a window that overhangs the
frame fades to zero there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
windows
|
Tensor
|
|
required |
sample_inds
|
Tensor
|
|
required |
crop_size
|
int
|
Output crop side. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in sleap_nn/data/instance_cropping.py
find_instance_crop_size(labels, padding=0, maximum_stride=2, min_crop_size=None, max_hw=None, anchor_ind=None, centroid_method=None, centroid_fallback=None, user_instances_only=False, superseded_only=False)
¶
Compute a crop size that contains every labeled instance.
The size is measured the way the crop is actually taken: centered on each
instance's centroid (iter_required_crop_sizes) and, when max_hw is
given, in the size-matched pixel space that cropping happens in. Both
matter -- a bounding-box measurement in native pixels under-sizes the crop
whenever the centroid is off-center or the video is rescaled to max_hw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
padding
|
int
|
Integer number of pixels to add to the bounds as margin padding. |
0
|
maximum_stride
|
int
|
Ensure that the returned crop size is divisible by this value. Useful for ensuring that the crop size will not be truncated in a given architecture. |
2
|
min_crop_size
|
Optional[int]
|
A floor for the returned crop size, before padding. |
None
|
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
anchor_ind
|
Optional[int]
|
Index of the anchor node the crop is centered on, or
|
None
|
centroid_method
|
Optional[str]
|
The resolved centroid method, or |
None
|
centroid_fallback
|
Optional[str]
|
The reduce method used when the anchor node is not visible on an instance. |
None
|
user_instances_only
|
bool
|
When |
False
|
superseded_only
|
bool
|
See :func: |
False
|
Returns:
| Type | Description |
|---|---|
int
|
An integer crop size denoting the length of the side of the boxes that
will contain the instances when cropped. The returned crop size will be
larger or equal to the input This accounts for stride and padding when ensuring divisibility. |
Source code in sleap_nn/data/instance_cropping.py
find_mask_crop_size(labels, padding=0, maximum_stride=2, min_crop_size=None, max_hw=None, crop_centering='auto', user_instances_only=False, min_mask_area=1.0)
¶
Compute a crop size that contains every mask (the mask analog of find_instance_crop_size).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
padding
|
int
|
Pixels of margin to add. |
0
|
maximum_stride
|
int
|
The returned size is divisible by this. |
2
|
min_crop_size
|
Optional[int]
|
A floor for the size, before padding. |
None
|
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
crop_centering
|
str
|
Where the crop is centered on each mask (see
:func: |
'auto'
|
user_instances_only
|
bool
|
When |
False
|
min_mask_area
|
float
|
Ignore masks smaller than this (image pixels). |
1.0
|
Returns:
| Type | Description |
|---|---|
int
|
The crop side length, a multiple of |
Source code in sleap_nn/data/instance_cropping.py
find_max_instance_bbox_size(labels, max_hw=None, user_instances_only=False, superseded_only=False)
¶
Find the maximum bounding box dimension across all instances in labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
user_instances_only
|
bool
|
When |
False
|
superseded_only
|
bool
|
See :func: |
False
|
Returns:
| Type | Description |
|---|---|
float
|
The maximum bounding box dimension (max of width or height) across all instances. |
Source code in sleap_nn/data/instance_cropping.py
generate_crops(image, instance, centroid, crop_size)
¶
Generate cropped image for the given centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
Input source image. (n_samples, C, H, W) |
required |
instance
|
Tensor
|
Keypoints for the instance to be cropped. (n_nodes, 2) |
required |
centroid
|
Tensor
|
Centroid of the instance to be cropped. (2) |
required |
crop_size
|
Tuple[int]
|
(height, width) of the crop to be generated. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Tensor]
|
A dictionary with cropped images, bounding box for the cropped instance, keypoints and centroids adjusted to the crop. |
Source code in sleap_nn/data/instance_cropping.py
iter_mask_extents(labels, max_hw=None, crop_centering='auto', user_instances_only=False, min_mask_area=1.0)
¶
Yield (required_crop_size, bbox_size) for every mask, in size-matched pixels.
The mask analog of :func:iter_required_crop_sizes, for the embedding model's
mask mode, whose crop is centered on the mask's center of mass (crop_centering
auto / mask_com) or on its bounding-box midpoint (bbox), as
EmbeddingDataset._crop_mask centers it. required_crop_size is the side a
crop around that center needs to hold the whole mask (twice the largest distance
from the center to a mask pixel's far edge); bbox_size is the larger side of
the mask's bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
crop_centering
|
str
|
|
'auto'
|
user_instances_only
|
bool
|
When |
False
|
min_mask_area
|
float
|
Skip masks with fewer foreground pixels (image pixels) than this, as the embedding dataset does. |
1.0
|
Source code in sleap_nn/data/instance_cropping.py
iter_required_crop_sizes(labels, max_hw=None, anchor_ind=None, centroid_method=None, centroid_fallback=None, user_instances_only=False, superseded_only=False)
¶
Yield the crop size each labeled instance needs to avoid being clipped.
Crops are centered on the instance's centroid, not on its bounding-box
midpoint (see generate_crops / make_centered_bboxes), so the size an
instance requires is twice its greatest node offset from that centroid --
not its bounding-box extent. The two agree only when the centroid happens
to sit at the middle of the bounding box. For an anchor node near one end of
the animal (a mouse anchored on the thorax, with a long tail) the required
size approaches twice the extent, which is why a crop sized to the bounding
box still clips the far nodes.
The centroid is derived through generate_centroids, the same op that
positions the crop at training time, so this can't disagree with the actual
crop center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
max_hw
|
Optional[Tuple[Optional[int], Optional[int]]]
|
The configured |
None
|
anchor_ind
|
Optional[int]
|
Index of the anchor node, or |
None
|
centroid_method
|
Optional[str]
|
The resolved centroid method, or |
None
|
centroid_fallback
|
Optional[str]
|
The reduce method used when the anchor node is not visible on an instance. |
None
|
user_instances_only
|
bool
|
When |
False
|
superseded_only
|
bool
|
See :func: |
False
|
Yields:
| Type | Description |
|---|---|
float
|
The required crop side length, in size-matched pixels, per instance. Instances whose centroid is undefined are skipped. |
Source code in sleap_nn/data/instance_cropping.py
letterbox_crops(crops, keep_half)
¶
Zero the pixels of (N, C, h, w) crops outside the centered padded box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crops
|
Tensor
|
Crops centered on their boxes. |
required |
keep_half
|
Tensor
|
|
required |
Source code in sleap_nn/data/instance_cropping.py
make_centered_bboxes(centroids, box_height, box_width)
¶
Create centered bounding boxes around centroid.
To be used with kornia.geometry.transform.crop_and_resizein the following
(clockwise) order: top-left, top-right, bottom-right and bottom-left.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centroids
|
Tensor
|
A tensor of centroids with shape (n_centroids, 2), where n_centroids is the number of centroids, and the last dimension represents x and y coordinates. |
required |
box_height
|
int
|
The desired height of the bounding boxes. |
required |
box_width
|
int
|
The desired width of the bounding boxes. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: A tensor containing bounding box coordinates for each centroid. The output tensor has shape (n_centroids, 4, 2), where n_centroids is the number of centroids, and the second dimension represents the four corner points of the bounding boxes, each with x and y coordinates. The order of the corners follows a clockwise arrangement: top-left, top-right, bottom-right, and bottom-left. |
Source code in sleap_nn/data/instance_cropping.py
mask_foreground_rects(mask)
¶
A mask's foreground on the image-pixel grid, as disjoint rectangles.
The union of the returned rectangles is exactly the foreground of
:func:sleap_nn.inference.segmentation_convert.decode_mask_to_image_res: the
stored grid, resampled nearest-neighbor to its image extent when scale is
not 1, placed at the rounded offset, with pixels an offset puts above or left
of the image dropped. It is read off the run-length encoding, so the cost grows
with the number of runs, not with the frame; no full-grid decode is made.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
SegmentationMask
|
A |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
An |
Source code in sleap_nn/data/instance_cropping.py
mask_rects_center(rects, crop_centering='auto', frame_hw=None)
¶
The (cx, cy) a mask crop centers on, from the mask's rectangles.
auto / mask_com: the center of mass; bbox: the bounding-box
midpoint. Both are the values _compute_mask_centroids /
_mask_bbox_midpoint compute on the decoded mask, to the last bit: the
coordinate sums are exact integers, and the mean is their one rounded quotient,
as np.mean of the pixel coordinates is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rects
|
ndarray
|
:func: |
required |
crop_centering
|
str
|
|
'auto'
|
frame_hw
|
Optional[Tuple[int, int]]
|
The frame |
None
|
Source code in sleap_nn/data/instance_cropping.py
mask_rects_moments(rects)
¶
(n, sum_x, sum_y): a mask's pixel count and coordinate sums, exactly.
Python integers, from the :func:mask_foreground_rects rectangles: no pixel is
enumerated.
Source code in sleap_nn/data/instance_cropping.py
points_from_crop(points, windows, scales)
¶
Map crop keypoints (N, ..., 2) back to the frame.
The inverse of :func:points_to_crop.
Source code in sleap_nn/data/instance_cropping.py
points_to_crop(points, windows, scales)
¶
Map frame keypoints (N, ..., 2) into the crops of windows.
Source code in sleap_nn/data/instance_cropping.py
pre_crop_size(crop_size)
¶
Side of the training pre-crop that leaves room for rotation augmentation.
At least crop_size * sqrt(2), and of the same parity as crop_size so the
final re-crop around the pre-crop center lands on whole pixels (no half-pixel
resampling between the pre-crop and the final crop).
Source code in sleap_nn/data/instance_cropping.py
rasterize_rects(rects, y0, y1, x0, x1)
¶
The [y0:y1, x0:x1] window of the mask rects cover, as a bool array.
Source code in sleap_nn/data/instance_cropping.py
scale_windows(windows, factor)
¶
Grow (or shrink) (N, 4) edge-coordinate windows about their centers.
Source code in sleap_nn/data/instance_cropping.py
window_corners(windows)
¶
(N, 4) edge-coordinate windows -> (N, 4, 2) TL, TR, BR, BL corners.