Skip to content

Bounding boxes

Spatial annotations: Centroids · Boxes · ROIs · Segmentation. These types nest per-frame on LabeledFrame — see Working with annotations in frames.

A BoundingBox represents a rectangular region defined by its corner coordinates (x1, y1, x2, y2) and an optional rotation angle. Bounding boxes are the primary annotation type for object detection workflows. BoundingBox is abstract — use UserBoundingBox or PredictedBoundingBox.

Direct construction

>>> import sleap_io as sio
>>> bbox = sio.UserBoundingBox(
...     x1=75, y1=160, x2=125, y2=240,
... )
>>> print(bbox.area)
4000
>>> print(bbox.xyxy)
(75, 160, 125, 240)
>>> print(bbox.x_center)  # computed property
100.0
>>> print(bbox.width)      # computed property
50

The x_center, y_center, centroid_xy, width, and height fields are available as read-only computed properties.

From corner coordinates

The from_xyxy factory method creates a bounding box from (x1, y1, x2, y2) corner coordinates:

>>> import sleap_io as sio
>>> bbox2 = sio.UserBoundingBox.from_xyxy(75, 160, 125, 240)
>>> print(bbox2.x_center)
100.0
>>> print(bbox2.width)
50

There is also from_xywh for (x, y, width, height) format where (x, y) is the top-left corner:

>>> import sleap_io as sio
>>> bbox3 = sio.UserBoundingBox.from_xywh(75, 160, 50, 80)
>>> print(bbox3.x_center)
100.0
>>> print(bbox3.y_center)
200.0

User vs. predicted bounding boxes

UserBoundingBox and PredictedBoundingBox distinguish human annotations from model predictions. PredictedBoundingBox adds a score field for confidence:

>>> import sleap_io as sio
>>> user_bbox = sio.UserBoundingBox(
...     x1=75, y1=160, x2=125, y2=240,
... )
>>> print(user_bbox.is_predicted)
False
>>> pred_bbox = sio.PredictedBoundingBox(
...     x1=75, y1=160, x2=125, y2=240,
...     score=0.95,
... )
>>> print(pred_bbox.score)
0.95
>>> print(pred_bbox.is_predicted)
True

Rotated bounding boxes

Set angle (in radians) to create an oriented bounding box. Rotated boxes support corners and bounds but not xyxy or xywh, since those are only meaningful for axis-aligned rectangles:

>>> import sleap_io as sio
>>> rotated = sio.UserBoundingBox(
...     x1=75, y1=160, x2=125, y2=240,
...     angle=0.785,
... )
>>> print(rotated.is_rotated)
True
>>> print(rotated.corners.shape)
(4, 2)
>>> print(rotated.bounds)  # axis-aligned extent of the rotated box
(54.04228602660537, 154.03383970567785, 145.95771397339462, 245.96616029432215)

Converting to other modalities

A BoundingBox participates in the unified conversion matrix: it can be reduced to a Centroid at its center, inflated with pad(), or projected to an ROI / SegmentationMask. Predicted boxes produce predicted outputs carrying their score:

>>> import sleap_io as sio
>>> bbox = sio.UserBoundingBox(x1=75, y1=160, x2=125, y2=240)
>>> print(bbox.to_centroid().xy)   # center of the box
(100.0, 200.0)
>>> print(bbox.pad(10).xyxy)       # inflate 10 px on every side
(65, 150, 135, 250)
>>> print(bbox.to_roi().area)
4000.0

pad(padding) returns a new box of the same type inflated by padding (scalar or (px, py); negatives shrink), preserving angle, score, and metadata. to_centroid() and the other verbs accept error_on_empty=False; a degenerate box (NaN corners) yields a degenerate target unless you pass error_on_empty=True. The companion is_empty property reports whether any corner is NaN:

>>> import sleap_io as sio
>>> bbox = sio.UserBoundingBox(x1=75, y1=160, x2=125, y2=240)
>>> print(bbox.is_empty)
False

Metadata fields

Every bounding box can carry optional metadata:

Field Type Description
track Track \| None Tracking identity across frames
tracking_score float \| None Confidence of track identity assignment
identity Identity \| None Global cross-video re-ID identity (mirrors Instance.identity); persists via /identity_links (owner_type=4)
identity_score float \| None Confidence of the identity assignment
instance Instance \| None Linked pose instance
category str Class label (e.g., "mouse")
name str Human-readable name
source str Annotation source identifier

Rendering

Use sio.draw_bboxes to composite bounding boxes onto an image, or pass bboxes to sio.render_image / sio.render_video. See Rendering → Segmentation Overlays.


See also


API reference

sleap_io.BoundingBox

A bounding box annotation.

Supports axis-aligned and oriented (rotated) bounding boxes with optional metadata for associating with tracks and instances.

Attributes:

Name Type Description
x1

Left edge x-coordinate (before rotation).

y1

Top edge y-coordinate (before rotation).

x2

Right edge x-coordinate (before rotation).

y2

Bottom edge y-coordinate (before rotation).

angle

Rotation angle in radians (0 = axis-aligned).

track

Optional tracking identity.

tracking_score

Confidence of the track identity assignment. None if unassigned or manually assigned.

identity

Optional global, ground-truth Identity for this box -- the persistent cross-video animal identity / re-identification key. None if no global identity is assigned. Mirrors Instance.identity.

identity_score

Score associated with the identity assignment (e.g. the re-ID match similarity). None if unassigned or assigned manually. Kept separate from tracking_score (short-term tracklet vs long-term identity).

instance

Optional linked pose instance.

category

Optional Category (class label, e.g. "mouse", "fly") for this box. Promoted from the legacy free-form string; None if unset. Mirrors Instance.category.

name

Human-readable name.

source

Annotation source identifier.

identity_embedding

Optional Embedding describing this detection's appearance for re-identification. None by default.

category_score

Score associated with the category assignment (e.g. the classifier confidence). None if unassigned or assigned manually.

category_embedding

Optional Embedding describing this detection's appearance for classification. None by default.

Notes

Bounding boxes use identity-based equality (two BoundingBox objects are only equal if they are the same object in memory).

This class is abstract. Use UserBoundingBox or PredictedBoundingBox instead.

Methods:

Name Description
__attrs_post_init__

Validate that this class is not instantiated directly.

__init__

Method generated by attrs for class BoundingBox.

__repr__

Method generated by attrs for class BoundingBox.

__setattr__

Method generated by attrs for class BoundingBox.

from_xywh

Create a bounding box from top-left corner and dimensions.

from_xyxy

Create a bounding box from corner coordinates.

pad

Return a new box inflated outward by padding.

to_centroid

Convert this bounding box to a centroid at its center.

to_mask

Rasterize this bounding box into a binary segmentation mask.

to_roi

Convert to an ROI with Shapely polygon geometry.

Source code in sleap_io/model/bbox.py
@attrs.define(eq=False)
class BoundingBox:
    """A bounding box annotation.

    Supports axis-aligned and oriented (rotated) bounding boxes with optional
    metadata for associating with tracks and instances.

    Attributes:
        x1: Left edge x-coordinate (before rotation).
        y1: Top edge y-coordinate (before rotation).
        x2: Right edge x-coordinate (before rotation).
        y2: Bottom edge y-coordinate (before rotation).
        angle: Rotation angle in radians (0 = axis-aligned).
        track: Optional tracking identity.
        tracking_score: Confidence of the track identity assignment. ``None``
            if unassigned or manually assigned.
        identity: Optional global, ground-truth `Identity` for this box -- the
            persistent cross-video animal identity / re-identification key. ``None``
            if no global identity is assigned. Mirrors `Instance.identity`.
        identity_score: Score associated with the `identity` assignment (e.g. the
            re-ID match similarity). ``None`` if unassigned or assigned manually.
            Kept separate from `tracking_score` (short-term tracklet vs long-term
            identity).
        instance: Optional linked pose instance.
        category: Optional `Category` (class label, e.g. ``"mouse"``, ``"fly"``)
            for this box. Promoted from the legacy free-form string; ``None`` if
            unset. Mirrors `Instance.category`.
        name: Human-readable name.
        source: Annotation source identifier.
        identity_embedding: Optional `Embedding` describing this detection's
            appearance for re-identification. ``None`` by default.
        category_score: Score associated with the `category` assignment (e.g. the
            classifier confidence). ``None`` if unassigned or assigned manually.
        category_embedding: Optional `Embedding` describing this detection's
            appearance for classification. ``None`` by default.

    Notes:
        Bounding boxes use identity-based equality (two BoundingBox objects are
        only equal if they are the same object in memory).

        This class is abstract. Use ``UserBoundingBox`` or
        ``PredictedBoundingBox`` instead.
    """

    x1: float = attrs.field()
    y1: float = attrs.field()
    x2: float = attrs.field()
    y2: float = attrs.field()
    angle: float = attrs.field(default=0.0)
    track: "Track | None" = attrs.field(default=None)
    tracking_score: float | None = attrs.field(default=None)
    identity: "Identity | None" = attrs.field(default=None)
    identity_score: float | None = attrs.field(default=None)
    instance: "Instance | None" = attrs.field(default=None)
    category: "Category | None" = attrs.field(default=None, converter=to_category)
    name: str = attrs.field(default="")
    source: str = attrs.field(default="")
    identity_embedding: "Embedding | None" = attrs.field(default=None, repr=False)
    category_score: float | None = attrs.field(default=None)
    category_embedding: "Embedding | None" = attrs.field(default=None, repr=False)

    # Private: deferred instance index for lazy loading.
    _instance_idx: int = attrs.field(default=-1, repr=False, eq=False, init=False)

    def __attrs_post_init__(self):
        """Validate that this class is not instantiated directly."""
        if type(self) is BoundingBox:
            raise TypeError(
                "BoundingBox is abstract. Use UserBoundingBox or PredictedBoundingBox."
            )

    @classmethod
    def from_xyxy(
        cls,
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        **kwargs,
    ) -> "BoundingBox":
        """Create a bounding box from corner coordinates.

        Args:
            x1: Left edge x-coordinate.
            y1: Top edge y-coordinate.
            x2: Right edge x-coordinate.
            y2: Bottom edge y-coordinate.
            **kwargs: Additional keyword arguments passed to the constructor.

        Returns:
            A new bounding box instance.

        Raises:
            ValueError: If ``x2 < x1`` or ``y2 < y1``.
        """
        if x2 < x1 or y2 < y1:
            raise ValueError(
                f"Expected x2 >= x1 and y2 >= y1, got "
                f"x1={x1}, y1={y1}, x2={x2}, y2={y2}."
            )
        return cls(x1=x1, y1=y1, x2=x2, y2=y2, **kwargs)

    @classmethod
    def from_xywh(
        cls,
        x: float,
        y: float,
        w: float,
        h: float,
        **kwargs,
    ) -> "BoundingBox":
        """Create a bounding box from top-left corner and dimensions.

        Args:
            x: Left edge x-coordinate.
            y: Top edge y-coordinate.
            w: Width of the bounding box.
            h: Height of the bounding box.
            **kwargs: Additional keyword arguments passed to the constructor.

        Returns:
            A new bounding box instance.
        """
        return cls(x1=x, y1=y, x2=x + w, y2=y + h, **kwargs)

    @property
    def is_predicted(self) -> bool:
        """Whether this bounding box is a prediction."""
        return isinstance(self, PredictedBoundingBox)

    @property
    def is_rotated(self) -> bool:
        """Whether this bounding box is rotated (non-axis-aligned)."""
        return abs(self.angle) > 1e-10

    @property
    def is_empty(self) -> bool:
        """Whether this box is degenerate (any corner coordinate is NaN)."""
        return bool(
            np.isnan(self.x1)
            or np.isnan(self.y1)
            or np.isnan(self.x2)
            or np.isnan(self.y2)
        )

    @property
    def x_center(self) -> float:
        """Center x-coordinate."""
        return (self.x1 + self.x2) / 2

    @property
    def y_center(self) -> float:
        """Center y-coordinate."""
        return (self.y1 + self.y2) / 2

    @property
    def centroid_xy(self) -> tuple[float, float]:
        """Center point as ``(x, y)``."""
        return (self.x_center, self.y_center)

    @property
    def width(self) -> float:
        """Box width in pixels."""
        return self.x2 - self.x1

    @property
    def height(self) -> float:
        """Box height in pixels."""
        return self.y2 - self.y1

    @property
    def xyxy(self) -> tuple[float, float, float, float]:
        """Corner coordinates as (x1, y1, x2, y2).

        Returns:
            Tuple of (left, top, right, bottom) coordinates.

        Raises:
            ValueError: If the bounding box is rotated.
        """
        if self.is_rotated:
            raise ValueError(
                "xyxy is only defined for axis-aligned bounding boxes. "
                "Use `bounds` or `corners` for rotated boxes."
            )
        return (self.x1, self.y1, self.x2, self.y2)

    @property
    def xywh(self) -> tuple[float, float, float, float]:
        """Top-left corner and dimensions as (x, y, width, height).

        Returns:
            Tuple of (left, top, width, height).

        Raises:
            ValueError: If the bounding box is rotated.
        """
        if self.is_rotated:
            raise ValueError(
                "xywh is only defined for axis-aligned bounding boxes. "
                "Use `bounds` or `corners` for rotated boxes."
            )
        return (self.x1, self.y1, self.width, self.height)

    @property
    def corners(self) -> np.ndarray:
        """Corner points as a (4, 2) array.

        Returns corners in order: top-left, top-right, bottom-right, bottom-left
        (before rotation). Works for both axis-aligned and rotated boxes.

        Returns:
            A (4, 2) numpy array of corner coordinates.
        """
        half_w = self.width / 2
        half_h = self.height / 2
        # Corners relative to center (TL, TR, BR, BL)
        corners = np.array(
            [
                [-half_w, -half_h],
                [half_w, -half_h],
                [half_w, half_h],
                [-half_w, half_h],
            ]
        )
        if self.is_rotated:
            cos_a = math.cos(self.angle)
            sin_a = math.sin(self.angle)
            rotation = np.array([[cos_a, -sin_a], [sin_a, cos_a]])
            corners = corners @ rotation.T
        corners[:, 0] += self.x_center
        corners[:, 1] += self.y_center
        return corners

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """Axis-aligned bounding extent as (minx, miny, maxx, maxy).

        Works for both axis-aligned and rotated bounding boxes.

        Returns:
            Tuple of (minx, miny, maxx, maxy).
        """
        if not self.is_rotated:
            return (self.x1, self.y1, self.x2, self.y2)
        c = self.corners
        return (
            float(c[:, 0].min()),
            float(c[:, 1].min()),
            float(c[:, 0].max()),
            float(c[:, 1].max()),
        )

    @property
    def area(self) -> float:
        """Area of the bounding box."""
        return self.width * self.height

    def to_roi(self) -> "ROI":
        """Convert to an ROI with Shapely polygon geometry.

        Returns:
            An ROI with a rectangular polygon matching this bounding box.
        """
        from shapely.geometry import Polygon

        from sleap_io.model.roi import UserROI

        corners = self.corners
        # Close the ring
        coords = list(map(tuple, corners)) + [tuple(corners[0])]
        geom = Polygon(coords)
        return UserROI(
            geometry=geom,
            name=self.name,
            category=self.category,
            category_score=self.category_score,
            category_embedding=self.category_embedding,
            source=self.source,
            track=self.track,
            tracking_score=self.tracking_score,
            identity=self.identity,
            identity_score=self.identity_score,
            identity_embedding=self.identity_embedding,
            instance=self.instance,
        )

    def to_mask(self, height: int, width: int) -> "SegmentationMask":
        """Rasterize this bounding box into a binary segmentation mask.

        Args:
            height: Height of the output mask in pixels.
            width: Width of the output mask in pixels.

        Returns:
            A SegmentationMask with the rasterized bounding box.
        """
        roi = self.to_roi()
        return roi.to_mask(height, width)

    def to_centroid(self, error_on_empty: bool = False) -> "Centroid":
        """Convert this bounding box to a centroid at its center.

        A ``PredictedBoundingBox`` produces a ``PredictedCentroid`` carrying its
        ``score``; any other box produces a ``UserCentroid``. Metadata (track,
        tracking_score, identity, identity_score, category, name, source,
        instance) is inherited.

        Args:
            error_on_empty: If ``True``, raise ``ValueError`` when this box is
                degenerate (NaN corners) instead of returning a degenerate
                (NaN) centroid.

        Returns:
            A ``Centroid`` located at this box's center (or NaN coordinates if
            the box is degenerate).

        Raises:
            ValueError: If the box is degenerate and ``error_on_empty`` is
                ``True``.
        """
        from sleap_io.model.centroid import PredictedCentroid, UserCentroid

        if self.is_empty:
            if error_on_empty:
                raise ValueError(
                    "Cannot compute centroid of a degenerate (NaN) bounding box."
                )
            nan = float("nan")
            x, y = nan, nan
        else:
            x, y = self.centroid_xy

        kwargs = dict(
            x=x,
            y=y,
            track=self.track,
            tracking_score=self.tracking_score,
            identity=self.identity,
            identity_score=self.identity_score,
            identity_embedding=self.identity_embedding,
            instance=self.instance,
            category=self.category,
            category_score=self.category_score,
            category_embedding=self.category_embedding,
            name=self.name,
            source=self.source,
        )
        if self.is_predicted:
            return PredictedCentroid(score=self.score, **kwargs)
        return UserCentroid(**kwargs)

    def pad(self, padding: float | tuple[float, float]) -> "BoundingBox":
        """Return a new box inflated outward by ``padding``.

        The returned box is the same type as this one (``UserBoundingBox`` or
        ``PredictedBoundingBox``) and preserves ``angle``, ``score``, and all
        metadata. For rotated boxes the pre-rotation extent is inflated about
        the center, keeping the angle fixed.

        Args:
            padding: Amount to inflate the box outward. A scalar applies to both
                axes; a ``(px, py)`` tuple applies per-axis. Negative values
                shrink the box; values are not clamped.

        Returns:
            A new ``BoundingBox`` of the same type with padded corners.
        """
        from sleap_io.model.roi import _apply_padding

        x1, y1, x2, y2 = _apply_padding(self.x1, self.y1, self.x2, self.y2, padding)

        kwargs = dict(
            x1=x1,
            y1=y1,
            x2=x2,
            y2=y2,
            angle=self.angle,
            track=self.track,
            tracking_score=self.tracking_score,
            identity=self.identity,
            identity_score=self.identity_score,
            identity_embedding=self.identity_embedding,
            instance=self.instance,
            category=self.category,
            category_score=self.category_score,
            category_embedding=self.category_embedding,
            name=self.name,
            source=self.source,
        )
        if self.is_predicted:
            return PredictedBoundingBox(score=self.score, **kwargs)
        return UserBoundingBox(**kwargs)

__annotations__ = {'x1': 'float', 'y1': 'float', 'x2': 'float', 'y2': 'float', 'angle': 'float', 'track': "'Track | None'", 'tracking_score': 'float | None', 'identity': "'Identity | None'", 'identity_score': 'float | None', 'instance': "'Instance | None'", 'category': "'Category | None'", 'name': 'str', 'source': 'str', 'identity_embedding': "'Embedding | None'", 'category_score': 'float | None', 'category_embedding': "'Embedding | None'", '_instance_idx': 'int'} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A bounding box annotation.\n\nSupports axis-aligned and oriented (rotated) bounding boxes with optional\nmetadata for associating with tracks and instances.\n\nAttributes:\n x1: Left edge x-coordinate (before rotation).\n y1: Top edge y-coordinate (before rotation).\n x2: Right edge x-coordinate (before rotation).\n y2: Bottom edge y-coordinate (before rotation).\n angle: Rotation angle in radians (0 = axis-aligned).\n track: Optional tracking identity.\n tracking_score: Confidence of the track identity assignment. ``None``\n if unassigned or manually assigned.\n identity: Optional global, ground-truth `Identity` for this box -- the\n persistent cross-video animal identity / re-identification key. ``None``\n if no global identity is assigned. Mirrors `Instance.identity`.\n identity_score: Score associated with the `identity` assignment (e.g. the\n re-ID match similarity). ``None`` if unassigned or assigned manually.\n Kept separate from `tracking_score` (short-term tracklet vs long-term\n identity).\n instance: Optional linked pose instance.\n category: Optional `Category` (class label, e.g. ``"mouse"``, ``"fly"``)\n for this box. Promoted from the legacy free-form string; ``None`` if\n unset. Mirrors `Instance.category`.\n name: Human-readable name.\n source: Annotation source identifier.\n identity_embedding: Optional `Embedding` describing this detection\'s\n appearance for re-identification. ``None`` by default.\n category_score: Score associated with the `category` assignment (e.g. the\n classifier confidence). ``None`` if unassigned or assigned manually.\n category_embedding: Optional `Embedding` describing this detection\'s\n appearance for classification. ``None`` by default.\n\nNotes:\n Bounding boxes use identity-based equality (two BoundingBox objects are\n only equal if they are the same object in memory).\n\n This class is abstract. Use ``UserBoundingBox`` or\n ``PredictedBoundingBox`` instead.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 33 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('x1', 'y1', 'x2', 'y2', 'angle', 'track', 'tracking_score', 'identity', 'identity_score', 'instance', 'category', 'name', 'source', 'identity_embedding', 'category_score', 'category_embedding') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.bbox' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('x1', 'y1', 'x2', 'y2', 'angle', 'track', 'tracking_score', 'identity', 'identity_score', 'instance', 'category', 'name', 'source', 'identity_embedding', 'category_score', 'category_embedding', '_instance_idx', '__weakref__') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property

list of weak references to the object

area property

Area of the bounding box.

bounds property

Axis-aligned bounding extent as (minx, miny, maxx, maxy).

Works for both axis-aligned and rotated bounding boxes.

Returns:

Type Description

Tuple of (minx, miny, maxx, maxy).

centroid_xy property

Center point as (x, y).

corners property

Corner points as a (4, 2) array.

Returns corners in order: top-left, top-right, bottom-right, bottom-left (before rotation). Works for both axis-aligned and rotated boxes.

Returns:

Type Description

A (4, 2) numpy array of corner coordinates.

height property

Box height in pixels.

is_empty property

Whether this box is degenerate (any corner coordinate is NaN).

is_predicted property

Whether this bounding box is a prediction.

is_rotated property

Whether this bounding box is rotated (non-axis-aligned).

width property

Box width in pixels.

x_center property

Center x-coordinate.

xywh property

Top-left corner and dimensions as (x, y, width, height).

Returns:

Type Description

Tuple of (left, top, width, height).

Raises:

Type Description
ValueError

If the bounding box is rotated.

xyxy property

Corner coordinates as (x1, y1, x2, y2).

Returns:

Type Description

Tuple of (left, top, right, bottom) coordinates.

Raises:

Type Description
ValueError

If the bounding box is rotated.

y_center property

Center y-coordinate.

__attrs_post_init__()

Validate that this class is not instantiated directly.

Source code in sleap_io/model/bbox.py
def __attrs_post_init__(self):
    """Validate that this class is not instantiated directly."""
    if type(self) is BoundingBox:
        raise TypeError(
            "BoundingBox is abstract. Use UserBoundingBox or PredictedBoundingBox."
        )

__init__(x1, y1, x2, y2, angle=0.0, track=None, tracking_score=None, identity=None, identity_score=None, instance=None, category=None, name='', source='', identity_embedding=None, category_score=None, category_embedding=None)

Method generated by attrs for class BoundingBox.

Source code in sleap_io/model/bbox.py
from typing import TYPE_CHECKING

import attrs
import numpy as np

from sleap_io.model.category import to_category

if TYPE_CHECKING:
    from sleap_io.model.category import Category
    from sleap_io.model.centroid import Centroid
    from sleap_io.model.embedding import Embedding
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Instance, Track
    from sleap_io.model.mask import SegmentationMask
    from sleap_io.model.roi import ROI


@attrs.define(eq=False)
class BoundingBox:
    """A bounding box annotation.

__repr__()

Method generated by attrs for class BoundingBox.

Source code in sleap_io/model/bbox.py
"""Data structures for bounding box annotations.

Bounding boxes are first-class annotations for object detection and tracking
workflows. They support axis-aligned and oriented (rotated) bounding boxes with
user/predicted distinction.

The class hierarchy:
    - `BoundingBox` — abstract base with geometry, video/frame/track/instance metadata
    - `UserBoundingBox` — human-annotated bounding box
    - `PredictedBoundingBox` — model-predicted bounding box with confidence score
"""

from __future__ import annotations

import math

__setattr__(name, val)

Method generated by attrs for class BoundingBox.

from_xywh(x, y, w, h, **kwargs) classmethod

Create a bounding box from top-left corner and dimensions.

Parameters:

Name Type Description Default
x float

Left edge x-coordinate.

required
y float

Top edge y-coordinate.

required
w float

Width of the bounding box.

required
h float

Height of the bounding box.

required
**kwargs

Additional keyword arguments passed to the constructor.

required

Returns:

Type Description
BoundingBox

A new bounding box instance.

Source code in sleap_io/model/bbox.py
@classmethod
def from_xywh(
    cls,
    x: float,
    y: float,
    w: float,
    h: float,
    **kwargs,
) -> "BoundingBox":
    """Create a bounding box from top-left corner and dimensions.

    Args:
        x: Left edge x-coordinate.
        y: Top edge y-coordinate.
        w: Width of the bounding box.
        h: Height of the bounding box.
        **kwargs: Additional keyword arguments passed to the constructor.

    Returns:
        A new bounding box instance.
    """
    return cls(x1=x, y1=y, x2=x + w, y2=y + h, **kwargs)

from_xyxy(x1, y1, x2, y2, **kwargs) classmethod

Create a bounding box from corner coordinates.

Parameters:

Name Type Description Default
x1 float

Left edge x-coordinate.

required
y1 float

Top edge y-coordinate.

required
x2 float

Right edge x-coordinate.

required
y2 float

Bottom edge y-coordinate.

required
**kwargs

Additional keyword arguments passed to the constructor.

required

Returns:

Type Description
BoundingBox

A new bounding box instance.

Raises:

Type Description
ValueError

If x2 < x1 or y2 < y1.

Source code in sleap_io/model/bbox.py
@classmethod
def from_xyxy(
    cls,
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    **kwargs,
) -> "BoundingBox":
    """Create a bounding box from corner coordinates.

    Args:
        x1: Left edge x-coordinate.
        y1: Top edge y-coordinate.
        x2: Right edge x-coordinate.
        y2: Bottom edge y-coordinate.
        **kwargs: Additional keyword arguments passed to the constructor.

    Returns:
        A new bounding box instance.

    Raises:
        ValueError: If ``x2 < x1`` or ``y2 < y1``.
    """
    if x2 < x1 or y2 < y1:
        raise ValueError(
            f"Expected x2 >= x1 and y2 >= y1, got "
            f"x1={x1}, y1={y1}, x2={x2}, y2={y2}."
        )
    return cls(x1=x1, y1=y1, x2=x2, y2=y2, **kwargs)

pad(padding)

Return a new box inflated outward by padding.

The returned box is the same type as this one (UserBoundingBox or PredictedBoundingBox) and preserves angle, score, and all metadata. For rotated boxes the pre-rotation extent is inflated about the center, keeping the angle fixed.

Parameters:

Name Type Description Default
padding float | tuple[float, float]

Amount to inflate the box outward. A scalar applies to both axes; a (px, py) tuple applies per-axis. Negative values shrink the box; values are not clamped.

required

Returns:

Type Description
BoundingBox

A new BoundingBox of the same type with padded corners.

Source code in sleap_io/model/bbox.py
def pad(self, padding: float | tuple[float, float]) -> "BoundingBox":
    """Return a new box inflated outward by ``padding``.

    The returned box is the same type as this one (``UserBoundingBox`` or
    ``PredictedBoundingBox``) and preserves ``angle``, ``score``, and all
    metadata. For rotated boxes the pre-rotation extent is inflated about
    the center, keeping the angle fixed.

    Args:
        padding: Amount to inflate the box outward. A scalar applies to both
            axes; a ``(px, py)`` tuple applies per-axis. Negative values
            shrink the box; values are not clamped.

    Returns:
        A new ``BoundingBox`` of the same type with padded corners.
    """
    from sleap_io.model.roi import _apply_padding

    x1, y1, x2, y2 = _apply_padding(self.x1, self.y1, self.x2, self.y2, padding)

    kwargs = dict(
        x1=x1,
        y1=y1,
        x2=x2,
        y2=y2,
        angle=self.angle,
        track=self.track,
        tracking_score=self.tracking_score,
        identity=self.identity,
        identity_score=self.identity_score,
        identity_embedding=self.identity_embedding,
        instance=self.instance,
        category=self.category,
        category_score=self.category_score,
        category_embedding=self.category_embedding,
        name=self.name,
        source=self.source,
    )
    if self.is_predicted:
        return PredictedBoundingBox(score=self.score, **kwargs)
    return UserBoundingBox(**kwargs)

to_centroid(error_on_empty=False)

Convert this bounding box to a centroid at its center.

A PredictedBoundingBox produces a PredictedCentroid carrying its score; any other box produces a UserCentroid. Metadata (track, tracking_score, identity, identity_score, category, name, source, instance) is inherited.

Parameters:

Name Type Description Default
error_on_empty bool

If True, raise ValueError when this box is degenerate (NaN corners) instead of returning a degenerate (NaN) centroid.

False

Returns:

Type Description
Centroid

A Centroid located at this box's center (or NaN coordinates if the box is degenerate).

Raises:

Type Description
ValueError

If the box is degenerate and error_on_empty is True.

Source code in sleap_io/model/bbox.py
def to_centroid(self, error_on_empty: bool = False) -> "Centroid":
    """Convert this bounding box to a centroid at its center.

    A ``PredictedBoundingBox`` produces a ``PredictedCentroid`` carrying its
    ``score``; any other box produces a ``UserCentroid``. Metadata (track,
    tracking_score, identity, identity_score, category, name, source,
    instance) is inherited.

    Args:
        error_on_empty: If ``True``, raise ``ValueError`` when this box is
            degenerate (NaN corners) instead of returning a degenerate
            (NaN) centroid.

    Returns:
        A ``Centroid`` located at this box's center (or NaN coordinates if
        the box is degenerate).

    Raises:
        ValueError: If the box is degenerate and ``error_on_empty`` is
            ``True``.
    """
    from sleap_io.model.centroid import PredictedCentroid, UserCentroid

    if self.is_empty:
        if error_on_empty:
            raise ValueError(
                "Cannot compute centroid of a degenerate (NaN) bounding box."
            )
        nan = float("nan")
        x, y = nan, nan
    else:
        x, y = self.centroid_xy

    kwargs = dict(
        x=x,
        y=y,
        track=self.track,
        tracking_score=self.tracking_score,
        identity=self.identity,
        identity_score=self.identity_score,
        identity_embedding=self.identity_embedding,
        instance=self.instance,
        category=self.category,
        category_score=self.category_score,
        category_embedding=self.category_embedding,
        name=self.name,
        source=self.source,
    )
    if self.is_predicted:
        return PredictedCentroid(score=self.score, **kwargs)
    return UserCentroid(**kwargs)

to_mask(height, width)

Rasterize this bounding box into a binary segmentation mask.

Parameters:

Name Type Description Default
height int

Height of the output mask in pixels.

required
width int

Width of the output mask in pixels.

required

Returns:

Type Description
SegmentationMask

A SegmentationMask with the rasterized bounding box.

Source code in sleap_io/model/bbox.py
def to_mask(self, height: int, width: int) -> "SegmentationMask":
    """Rasterize this bounding box into a binary segmentation mask.

    Args:
        height: Height of the output mask in pixels.
        width: Width of the output mask in pixels.

    Returns:
        A SegmentationMask with the rasterized bounding box.
    """
    roi = self.to_roi()
    return roi.to_mask(height, width)

to_roi()

Convert to an ROI with Shapely polygon geometry.

Returns:

Type Description
ROI

An ROI with a rectangular polygon matching this bounding box.

Source code in sleap_io/model/bbox.py
def to_roi(self) -> "ROI":
    """Convert to an ROI with Shapely polygon geometry.

    Returns:
        An ROI with a rectangular polygon matching this bounding box.
    """
    from shapely.geometry import Polygon

    from sleap_io.model.roi import UserROI

    corners = self.corners
    # Close the ring
    coords = list(map(tuple, corners)) + [tuple(corners[0])]
    geom = Polygon(coords)
    return UserROI(
        geometry=geom,
        name=self.name,
        category=self.category,
        category_score=self.category_score,
        category_embedding=self.category_embedding,
        source=self.source,
        track=self.track,
        tracking_score=self.tracking_score,
        identity=self.identity,
        identity_score=self.identity_score,
        identity_embedding=self.identity_embedding,
        instance=self.instance,
    )

sleap_io.UserBoundingBox

Bases: sleap_io.model.bbox.BoundingBox

A human-annotated bounding box.

Inherits all fields from BoundingBox. Has no additional fields.

See BoundingBox for attribute documentation.

Methods:

Name Description
__init__

Method generated by attrs for class UserBoundingBox.

__repr__

Method generated by attrs for class UserBoundingBox.

__setattr__

Method generated by attrs for class UserBoundingBox.

Attributes:

Name Type Description
__annotations__

dict() -> new empty dictionary

__attrs_own_setattr__

Returns True when the argument is true, False otherwise.

__attrs_props__

Effective class properties as derived from parameters to attr.s() or

__doc__

str(object='') -> str

__firstlineno__

int([x]) -> integer

__match_args__

Built-in immutable sequence.

__module__

str(object='') -> str

__slots__

Built-in immutable sequence.

__static_attributes__

Built-in immutable sequence.

Source code in sleap_io/model/bbox.py
@attrs.define(eq=False)
class UserBoundingBox(BoundingBox):
    """A human-annotated bounding box.

    Inherits all fields from `BoundingBox`. Has no additional fields.

    See `BoundingBox` for attribute documentation.
    """

    pass

__annotations__ = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A human-annotated bounding box.\n\nInherits all fields from `BoundingBox`. Has no additional fields.\n\nSee `BoundingBox` for attribute documentation.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 428 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('x1', 'y1', 'x2', 'y2', 'angle', 'track', 'tracking_score', 'identity', 'identity_score', 'instance', 'category', 'name', 'source', 'identity_embedding', 'category_score', 'category_embedding') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.bbox' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__init__(x1, y1, x2, y2, angle=0.0, track=None, tracking_score=None, identity=None, identity_score=None, instance=None, category=None, name='', source='', identity_embedding=None, category_score=None, category_embedding=None)

Method generated by attrs for class UserBoundingBox.

Source code in sleap_io/model/bbox.py
from typing import TYPE_CHECKING

import attrs
import numpy as np

from sleap_io.model.category import to_category

if TYPE_CHECKING:
    from sleap_io.model.category import Category
    from sleap_io.model.centroid import Centroid
    from sleap_io.model.embedding import Embedding
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Instance, Track
    from sleap_io.model.mask import SegmentationMask
    from sleap_io.model.roi import ROI


@attrs.define(eq=False)
class BoundingBox:
    """A bounding box annotation.

__repr__()

Method generated by attrs for class UserBoundingBox.

Source code in sleap_io/model/bbox.py
"""Data structures for bounding box annotations.

Bounding boxes are first-class annotations for object detection and tracking
workflows. They support axis-aligned and oriented (rotated) bounding boxes with
user/predicted distinction.

The class hierarchy:
    - `BoundingBox` — abstract base with geometry, video/frame/track/instance metadata
    - `UserBoundingBox` — human-annotated bounding box
    - `PredictedBoundingBox` — model-predicted bounding box with confidence score
"""

from __future__ import annotations

import math

__setattr__(name, val)

Method generated by attrs for class UserBoundingBox.

sleap_io.PredictedBoundingBox

Bases: sleap_io.model.bbox.BoundingBox

A model-predicted bounding box with a confidence score.

Attributes:

Name Type Description
score

Confidence score (0-1).

See BoundingBox for other attribute documentation.

Methods:

Name Description
__init__

Method generated by attrs for class PredictedBoundingBox.

__repr__

Method generated by attrs for class PredictedBoundingBox.

__setattr__

Method generated by attrs for class PredictedBoundingBox.

Source code in sleap_io/model/bbox.py
@attrs.define(eq=False)
class PredictedBoundingBox(BoundingBox):
    """A model-predicted bounding box with a confidence score.

    Attributes:
        score: Confidence score (0-1).

    See `BoundingBox` for other attribute documentation.
    """

    score: float = attrs.field(default=0.0)

__annotations__ = {'score': 'float'} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A model-predicted bounding box with a confidence score.\n\nAttributes:\n score: Confidence score (0-1).\n\nSee `BoundingBox` for other attribute documentation.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 440 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('x1', 'y1', 'x2', 'y2', 'angle', 'track', 'tracking_score', 'identity', 'identity_score', 'instance', 'category', 'name', 'source', 'identity_embedding', 'category_score', 'category_embedding', 'score') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.bbox' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('score',) class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__init__(x1, y1, x2, y2, angle=0.0, track=None, tracking_score=None, identity=None, identity_score=None, instance=None, category=None, name='', source='', identity_embedding=None, category_score=None, category_embedding=None, score=0.0)

Method generated by attrs for class PredictedBoundingBox.

Source code in sleap_io/model/bbox.py
from typing import TYPE_CHECKING

import attrs
import numpy as np

from sleap_io.model.category import to_category

if TYPE_CHECKING:
    from sleap_io.model.category import Category
    from sleap_io.model.centroid import Centroid
    from sleap_io.model.embedding import Embedding
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Instance, Track
    from sleap_io.model.mask import SegmentationMask
    from sleap_io.model.roi import ROI


@attrs.define(eq=False)
class BoundingBox:
    """A bounding box annotation.

__repr__()

Method generated by attrs for class PredictedBoundingBox.

Source code in sleap_io/model/bbox.py
"""Data structures for bounding box annotations.

Bounding boxes are first-class annotations for object detection and tracking
workflows. They support axis-aligned and oriented (rotated) bounding boxes with
user/predicted distinction.

The class hierarchy:
    - `BoundingBox` — abstract base with geometry, video/frame/track/instance metadata
    - `UserBoundingBox` — human-annotated bounding box
    - `PredictedBoundingBox` — model-predicted bounding box with confidence score
"""

from __future__ import annotations

import math

__setattr__(name, val)

Method generated by attrs for class PredictedBoundingBox.