Skip to content

Annotators

import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

vertex_annotator = sv.VertexAnnotator(
    color=sv.Color.GREEN,
    radius=10,
)
annotated_frame = vertex_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)

vertex-annotator-example

import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

edge_annotator = sv.EdgeAnnotator(
    color=sv.Color.GREEN,
    thickness=5,
)
annotated_frame = edge_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)

edge-annotator-example

import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

vertex_label_annotator = sv.VertexLabelAnnotator(
    color=sv.Color.GREEN,
    text_color=sv.Color.BLACK,
    border_radius=5,
)
annotated_frame = vertex_label_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)

vertex-label-annotator-example

import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

area_annotator = sv.VertexEllipseAreaAnnotator(
    color=sv.Color.GREEN,
    sigma=2.0,
)
annotated_frame = area_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)

sv.VertexEllipseAnnotator is a compatibility alias for sv.VertexEllipseAreaAnnotator.

import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

outline_annotator = sv.VertexEllipseOutlineAnnotator(
    color=sv.Color.GREEN,
    sigma=2.0,
    thickness=2,
)
annotated_frame = outline_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)
import supervision as sv

image = ...
key_points = sv.KeyPoints(...)

halo_annotator = sv.VertexEllipseHaloAnnotator(
    color=sv.Color.GREEN,
    sigma=2.0,
)
annotated_frame = halo_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)
import supervision as sv
from supervision.key_points.angles import JointAngle

image = ...
key_points = sv.KeyPoints(...)

# Zero-based positions in key_points.xy;
# joint is the middle point. COCO: hip, knee, ankle.
left_knee = JointAngle(name="left_knee", start=11, joint=13, end=15)
joint_angle_annotator = sv.JointAngleAnnotator(
    angles=[left_knee],
    color=sv.Color.GREEN,
)
annotated_frame = joint_angle_annotator.annotate(
    scene=image.copy(),
    key_points=key_points,
)

supervision.key_points.annotators.VertexAnnotator

Bases: BaseKeyPointAnnotator

A class that specializes in drawing skeleton vertices on images.

It uses specified key points to determine the locations where the vertices should be drawn.

Source code in src/supervision/key_points/annotators.py
class VertexAnnotator(BaseKeyPointAnnotator):
    """A class that specializes in drawing skeleton vertices on images.

    It uses specified key points to determine the locations where the vertices should be
    drawn.
    """

    def __init__(
        self,
        color: Color | ColorPalette = Color.ROBOFLOW,
        radius: int = 4,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ) -> None:
        """
        Args:
            color: The :class:`~supervision.draw.color.Color` or
                :class:`~supervision.draw.color.ColorPalette` to use for
                annotating key points.
            radius: Radius of the drawn key point circles.
            color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
                strategy for mapping palette colors to key points. Options are
                ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
                and ``KEYPOINT`` (per keypoint index within each skeleton).

        Raises:
            ValueError: If ``color_lookup`` is ``TRACK``;
                :class:`~supervision.key_points.core.KeyPoints` carry no
                ``tracker_id``.
        """
        self.color = color
        self.radius = radius
        self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Annotates the given scene with skeleton vertices based on the provided key
        points. It draws circles at each key point location. Anchors marked as not
        visible via ``key_points.visible``, and anchors whose coordinates are not
        finite, are skipped.

        Args:
            scene: The image where skeleton vertices will be drawn. `ImageType` is a
                flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
            key_points: A collection of key points. Only the first two coordinate
                channels, x and y, determine pixel positions.

        Returns:
            The annotated image, matching the type of `scene` (`numpy.ndarray`
                or `PIL.Image.Image`)

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ... )
            >>> annotator = sv.VertexAnnotator(
            ...     color=sv.Color.ROBOFLOW, radius=10
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```

            Per-keypoint palette example:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ... )
            >>> annotator = sv.VertexAnnotator(
            ...     color=sv.ColorPalette.DEFAULT,
            ...     radius=10,
            ...     color_lookup=sv.ColorLookup.KEYPOINT,
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0:
            return scene

        for detection_index, xy in enumerate(key_points.xy):
            for point_index, (x, y) in enumerate(xy[:, :2]):
                if np.allclose((x, y), 0) or not _has_finite_coordinates((x, y)):
                    continue
                if (
                    key_points.visible is not None
                    and not key_points.visible[detection_index, point_index]
                ):
                    continue
                color = _resolve_keypoint_color(
                    color=self.color,
                    color_lookup=self.color_lookup,
                    key_points=key_points,
                    instance_idx=detection_index,
                    keypoint_idx=point_index,
                )
                cv2.circle(
                    img=scene,
                    center=(int(x), int(y)),
                    radius=self.radius,
                    color=_color_for_canvas(color.as_bgr(), scene),
                    thickness=-1,
                )

        return scene

Methods:

__init__(color: Color | ColorPalette = Color.ROBOFLOW, radius: int = 4, color_lookup: ColorLookup = ColorLookup.CLASS) -> None

Parameters:

Name Type Description Default
color
Color | ColorPalette

The :class:~supervision.draw.color.Color or :class:~supervision.draw.color.ColorPalette to use for annotating key points.

ROBOFLOW
radius
int

Radius of the drawn key point circles.

4
color_lookup
ColorLookup

:class:~supervision.annotators.utils.ColorLookup strategy for mapping palette colors to key points. Options are INDEX (per-skeleton index), CLASS (per class_id), and KEYPOINT (per keypoint index within each skeleton).

CLASS

Raises:

Type Description
ValueError

If color_lookup is TRACK; :class:~supervision.key_points.core.KeyPoints carry no tracker_id.

Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    color: Color | ColorPalette = Color.ROBOFLOW,
    radius: int = 4,
    color_lookup: ColorLookup = ColorLookup.CLASS,
) -> None:
    """
    Args:
        color: The :class:`~supervision.draw.color.Color` or
            :class:`~supervision.draw.color.ColorPalette` to use for
            annotating key points.
        radius: Radius of the drawn key point circles.
        color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
            strategy for mapping palette colors to key points. Options are
            ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
            and ``KEYPOINT`` (per keypoint index within each skeleton).

    Raises:
        ValueError: If ``color_lookup`` is ``TRACK``;
            :class:`~supervision.key_points.core.KeyPoints` carry no
            ``tracker_id``.
    """
    self.color = color
    self.radius = radius
    self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Annotates the given scene with skeleton vertices based on the provided key points. It draws circles at each key point location. Anchors marked as not visible via key_points.visible, and anchors whose coordinates are not finite, are skipped.

Parameters:

Name Type Description Default
scene
ImageType

The image where skeleton vertices will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

A collection of key points. Only the first two coordinate channels, x and y, determine pixel positions.

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene (numpy.ndarray or PIL.Image.Image)

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
... )
>>> annotator = sv.VertexAnnotator(
...     color=sv.Color.ROBOFLOW, radius=10
... )
>>> result = annotator.annotate(image.copy(), key_points)

Per-keypoint palette example:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
... )
>>> annotator = sv.VertexAnnotator(
...     color=sv.ColorPalette.DEFAULT,
...     radius=10,
...     color_lookup=sv.ColorLookup.KEYPOINT,
... )
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Annotates the given scene with skeleton vertices based on the provided key
    points. It draws circles at each key point location. Anchors marked as not
    visible via ``key_points.visible``, and anchors whose coordinates are not
    finite, are skipped.

    Args:
        scene: The image where skeleton vertices will be drawn. `ImageType` is a
            flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
        key_points: A collection of key points. Only the first two coordinate
            channels, x and y, determine pixel positions.

    Returns:
        The annotated image, matching the type of `scene` (`numpy.ndarray`
            or `PIL.Image.Image`)

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ... )
        >>> annotator = sv.VertexAnnotator(
        ...     color=sv.Color.ROBOFLOW, radius=10
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```

        Per-keypoint palette example:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ... )
        >>> annotator = sv.VertexAnnotator(
        ...     color=sv.ColorPalette.DEFAULT,
        ...     radius=10,
        ...     color_lookup=sv.ColorLookup.KEYPOINT,
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0:
        return scene

    for detection_index, xy in enumerate(key_points.xy):
        for point_index, (x, y) in enumerate(xy[:, :2]):
            if np.allclose((x, y), 0) or not _has_finite_coordinates((x, y)):
                continue
            if (
                key_points.visible is not None
                and not key_points.visible[detection_index, point_index]
            ):
                continue
            color = _resolve_keypoint_color(
                color=self.color,
                color_lookup=self.color_lookup,
                key_points=key_points,
                instance_idx=detection_index,
                keypoint_idx=point_index,
            )
            cv2.circle(
                img=scene,
                center=(int(x), int(y)),
                radius=self.radius,
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=-1,
            )

    return scene

supervision.key_points.annotators.EdgeAnnotator

Bases: BaseKeyPointAnnotator

A class that specializes in drawing skeleton edges on images using specified key points.

It connects key points with lines to form the skeleton structure.

Source code in src/supervision/key_points/annotators.py
class EdgeAnnotator(BaseKeyPointAnnotator):
    """A class that specializes in drawing skeleton edges on images using specified key
    points.

    It connects key points with lines to form the skeleton structure.
    """

    def __init__(
        self,
        color: Color | ColorPalette = Color.ROBOFLOW,
        thickness: int = 2,
        edges: (
            Sequence[tuple[int, int]] | dict[int, Sequence[tuple[int, int]]] | None
        ) = None,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ) -> None:
        """
        Args:
            color: The :class:`~supervision.draw.color.Color` or
                :class:`~supervision.draw.color.ColorPalette` to use for
                annotating edges.
            thickness: Thickness of the edge lines.
            edges: The edges to draw. If set to ``None``, will attempt to
                auto-detect the skeleton by vertex count. A
                ``Sequence[tuple[int, int]]`` applies a single skeleton to
                every instance. A ``dict[int, Sequence[tuple[int, int]]]``
                maps ``class_id`` to skeleton edges, enabling correct
                rendering for datasets with multiple skeleton types.
            color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
                strategy for mapping palette colors to edges. Options are
                ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
                and ``KEYPOINT`` (per keypoint index; an edge inherits the
                color of its first endpoint).

        Raises:
            ValueError: If ``color_lookup`` is ``TRACK``;
                :class:`~supervision.key_points.core.KeyPoints` carry no
                ``tracker_id``.
        """
        self.color = color
        self.thickness = thickness
        self.edges = edges
        self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Annotates the given scene by drawing lines between specified key points to
        form edges. Edges where either endpoint is marked as not visible via
        ``key_points.visible``, or where either endpoint has a non-finite x/y
        coordinate, are skipped. An extra coordinate does not affect drawing.

        Args:
            scene: The image where skeleton edges will be drawn. `ImageType` is a
                flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
            key_points: A collection of key points where each key point consists of x
                and y coordinates.

        Returns:
            The annotated image, matching the type of `scene` (`numpy.ndarray`
                or `PIL.Image.Image`)

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            Single-skeleton example:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ... )
            >>> annotator = sv.EdgeAnnotator(
            ...     color=sv.Color.ROBOFLOW,
            ...     thickness=3,
            ...     edges=[(1, 2), (1, 3)],
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```

            Multi-skeleton example with per-class edges:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]],
            ...          [[700, 300], [650, 500], [0, 0]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0, 1]),
            ...     visible=np.array(
            ...         [[True, True, True],
            ...          [True, True, False]],
            ...     ),
            ... )
            >>> annotator = sv.EdgeAnnotator(
            ...     color=sv.Color.ROBOFLOW,
            ...     thickness=3,
            ...     edges={0: [(1, 2), (1, 3)], 1: [(1, 2)]},
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```

            Per-keypoint palette example:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ... )
            >>> annotator = sv.EdgeAnnotator(
            ...     color=sv.ColorPalette.DEFAULT,
            ...     thickness=3,
            ...     edges=[(1, 2), (1, 3)],
            ...     color_lookup=sv.ColorLookup.KEYPOINT,
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0:
            return scene

        for detection_index, xy in enumerate(key_points.xy):
            if isinstance(self.edges, dict):
                class_id = (
                    int(key_points.class_id[detection_index])
                    if key_points.class_id is not None
                    else None
                )
                if class_id is None:
                    raise ValueError(
                        "edges is a dict but class_id is None; "
                        "KeyPoints must have class_id set."
                    )
                if class_id not in self.edges:
                    raise ValueError(f"No edges defined for class_id={class_id}.")
                edges = self.edges[class_id]
            elif self.edges:
                edges = self.edges
            else:
                _looked_up = SKELETONS_BY_VERTEX_COUNT.get(len(xy))
                if not _looked_up:
                    logger.warning("No skeleton found with %d vertices", len(xy))
                    continue
                edges = _looked_up

            for edge in edges:
                idx_a, idx_b = _validate_edge_indices(edge=edge, vertex_count=len(xy))
                xy_a = xy[idx_a, :2]
                xy_b = xy[idx_b, :2]
                if np.allclose(xy_a, 0) or np.allclose(xy_b, 0):
                    continue
                if not _has_finite_coordinates(xy_a) or not _has_finite_coordinates(
                    xy_b
                ):
                    continue
                if key_points.visible is not None:
                    if (
                        not key_points.visible[detection_index, idx_a]
                        or not key_points.visible[detection_index, idx_b]
                    ):
                        continue

                color = _resolve_keypoint_color(
                    color=self.color,
                    color_lookup=self.color_lookup,
                    key_points=key_points,
                    instance_idx=detection_index,
                    keypoint_idx=idx_a,
                )
                cv2.line(
                    img=scene,
                    pt1=(int(xy_a[0]), int(xy_a[1])),
                    pt2=(int(xy_b[0]), int(xy_b[1])),
                    color=_color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )

        return scene

Methods:

__init__(color: Color | ColorPalette = Color.ROBOFLOW, thickness: int = 2, edges: Sequence[tuple[int, int]] | dict[int, Sequence[tuple[int, int]]] | None = None, color_lookup: ColorLookup = ColorLookup.CLASS) -> None

Parameters:

Name Type Description Default
color
Color | ColorPalette

The :class:~supervision.draw.color.Color or :class:~supervision.draw.color.ColorPalette to use for annotating edges.

ROBOFLOW
thickness
int

Thickness of the edge lines.

2
edges
Sequence[tuple[int, int]] | dict[int, Sequence[tuple[int, int]]] | None

The edges to draw. If set to None, will attempt to auto-detect the skeleton by vertex count. A Sequence[tuple[int, int]] applies a single skeleton to every instance. A dict[int, Sequence[tuple[int, int]]] maps class_id to skeleton edges, enabling correct rendering for datasets with multiple skeleton types.

None
color_lookup
ColorLookup

:class:~supervision.annotators.utils.ColorLookup strategy for mapping palette colors to edges. Options are INDEX (per-skeleton index), CLASS (per class_id), and KEYPOINT (per keypoint index; an edge inherits the color of its first endpoint).

CLASS

Raises:

Type Description
ValueError

If color_lookup is TRACK; :class:~supervision.key_points.core.KeyPoints carry no tracker_id.

Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    color: Color | ColorPalette = Color.ROBOFLOW,
    thickness: int = 2,
    edges: (
        Sequence[tuple[int, int]] | dict[int, Sequence[tuple[int, int]]] | None
    ) = None,
    color_lookup: ColorLookup = ColorLookup.CLASS,
) -> None:
    """
    Args:
        color: The :class:`~supervision.draw.color.Color` or
            :class:`~supervision.draw.color.ColorPalette` to use for
            annotating edges.
        thickness: Thickness of the edge lines.
        edges: The edges to draw. If set to ``None``, will attempt to
            auto-detect the skeleton by vertex count. A
            ``Sequence[tuple[int, int]]`` applies a single skeleton to
            every instance. A ``dict[int, Sequence[tuple[int, int]]]``
            maps ``class_id`` to skeleton edges, enabling correct
            rendering for datasets with multiple skeleton types.
        color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
            strategy for mapping palette colors to edges. Options are
            ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
            and ``KEYPOINT`` (per keypoint index; an edge inherits the
            color of its first endpoint).

    Raises:
        ValueError: If ``color_lookup`` is ``TRACK``;
            :class:`~supervision.key_points.core.KeyPoints` carry no
            ``tracker_id``.
    """
    self.color = color
    self.thickness = thickness
    self.edges = edges
    self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Annotates the given scene by drawing lines between specified key points to form edges. Edges where either endpoint is marked as not visible via key_points.visible, or where either endpoint has a non-finite x/y coordinate, are skipped. An extra coordinate does not affect drawing.

Parameters:

Name Type Description Default
scene
ImageType

The image where skeleton edges will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

A collection of key points where each key point consists of x and y coordinates.

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene (numpy.ndarray or PIL.Image.Image)

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example

Single-skeleton example:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
... )
>>> annotator = sv.EdgeAnnotator(
...     color=sv.Color.ROBOFLOW,
...     thickness=3,
...     edges=[(1, 2), (1, 3)],
... )
>>> result = annotator.annotate(image.copy(), key_points)

Multi-skeleton example with per-class edges:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]],
...          [[700, 300], [650, 500], [0, 0]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0, 1]),
...     visible=np.array(
...         [[True, True, True],
...          [True, True, False]],
...     ),
... )
>>> annotator = sv.EdgeAnnotator(
...     color=sv.Color.ROBOFLOW,
...     thickness=3,
...     edges={0: [(1, 2), (1, 3)], 1: [(1, 2)]},
... )
>>> result = annotator.annotate(image.copy(), key_points)

Per-keypoint palette example:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
... )
>>> annotator = sv.EdgeAnnotator(
...     color=sv.ColorPalette.DEFAULT,
...     thickness=3,
...     edges=[(1, 2), (1, 3)],
...     color_lookup=sv.ColorLookup.KEYPOINT,
... )
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Annotates the given scene by drawing lines between specified key points to
    form edges. Edges where either endpoint is marked as not visible via
    ``key_points.visible``, or where either endpoint has a non-finite x/y
    coordinate, are skipped. An extra coordinate does not affect drawing.

    Args:
        scene: The image where skeleton edges will be drawn. `ImageType` is a
            flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
        key_points: A collection of key points where each key point consists of x
            and y coordinates.

    Returns:
        The annotated image, matching the type of `scene` (`numpy.ndarray`
            or `PIL.Image.Image`)

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        Single-skeleton example:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ... )
        >>> annotator = sv.EdgeAnnotator(
        ...     color=sv.Color.ROBOFLOW,
        ...     thickness=3,
        ...     edges=[(1, 2), (1, 3)],
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```

        Multi-skeleton example with per-class edges:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]],
        ...          [[700, 300], [650, 500], [0, 0]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0, 1]),
        ...     visible=np.array(
        ...         [[True, True, True],
        ...          [True, True, False]],
        ...     ),
        ... )
        >>> annotator = sv.EdgeAnnotator(
        ...     color=sv.Color.ROBOFLOW,
        ...     thickness=3,
        ...     edges={0: [(1, 2), (1, 3)], 1: [(1, 2)]},
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```

        Per-keypoint palette example:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ... )
        >>> annotator = sv.EdgeAnnotator(
        ...     color=sv.ColorPalette.DEFAULT,
        ...     thickness=3,
        ...     edges=[(1, 2), (1, 3)],
        ...     color_lookup=sv.ColorLookup.KEYPOINT,
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0:
        return scene

    for detection_index, xy in enumerate(key_points.xy):
        if isinstance(self.edges, dict):
            class_id = (
                int(key_points.class_id[detection_index])
                if key_points.class_id is not None
                else None
            )
            if class_id is None:
                raise ValueError(
                    "edges is a dict but class_id is None; "
                    "KeyPoints must have class_id set."
                )
            if class_id not in self.edges:
                raise ValueError(f"No edges defined for class_id={class_id}.")
            edges = self.edges[class_id]
        elif self.edges:
            edges = self.edges
        else:
            _looked_up = SKELETONS_BY_VERTEX_COUNT.get(len(xy))
            if not _looked_up:
                logger.warning("No skeleton found with %d vertices", len(xy))
                continue
            edges = _looked_up

        for edge in edges:
            idx_a, idx_b = _validate_edge_indices(edge=edge, vertex_count=len(xy))
            xy_a = xy[idx_a, :2]
            xy_b = xy[idx_b, :2]
            if np.allclose(xy_a, 0) or np.allclose(xy_b, 0):
                continue
            if not _has_finite_coordinates(xy_a) or not _has_finite_coordinates(
                xy_b
            ):
                continue
            if key_points.visible is not None:
                if (
                    not key_points.visible[detection_index, idx_a]
                    or not key_points.visible[detection_index, idx_b]
                ):
                    continue

            color = _resolve_keypoint_color(
                color=self.color,
                color_lookup=self.color_lookup,
                key_points=key_points,
                instance_idx=detection_index,
                keypoint_idx=idx_a,
            )
            cv2.line(
                img=scene,
                pt1=(int(xy_a[0]), int(xy_a[1])),
                pt2=(int(xy_b[0]), int(xy_b[1])),
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )

    return scene

supervision.key_points.annotators.VertexLabelAnnotator

A class that draws labels of skeleton vertices on images.

It uses specified key points to determine the locations where the vertices should be drawn.

Source code in src/supervision/key_points/annotators.py
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
class VertexLabelAnnotator:
    """A class that draws labels of skeleton vertices on images.

    It uses specified key points to determine the locations where the vertices should be
    drawn.
    """

    def __init__(
        self,
        color: Color | list[Color] | ColorPalette = Color.ROBOFLOW,
        text_color: Color | list[Color] | ColorPalette = Color.WHITE,
        text_scale: float = 0.5,
        text_thickness: int = 1,
        text_padding: int = 10,
        border_radius: int = 0,
        smart_position: bool = False,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ) -> None:
        """
        Args:
            color: The color to use for each keypoint label. A single
                :class:`~supervision.draw.color.Color` applies uniformly. A
                :class:`~supervision.draw.color.ColorPalette` selects colors
                via the ``color_lookup`` strategy. Passing a ``list[Color]``
                is **deprecated in** ``0.32.0`` (removed in ``0.35.0``); use a
                :class:`~supervision.draw.color.ColorPalette` with
                ``ColorLookup.KEYPOINT`` instead.
            text_color: The color to use for the label text. Accepts the
                same types as ``color``. Passing a ``list[Color]`` is
                **deprecated in** ``0.32.0`` (removed in ``0.35.0``).
            text_scale: Font scale for the text.
            text_thickness: Thickness of the text characters.
            text_padding: Padding around the text within its
                background box.
            border_radius: The radius to apply round edges. If the
                selected value is higher than the lower dimension,
                width or height, is clipped.
            smart_position: Spread out the labels to avoid overlapping.
            color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
                strategy for mapping palette colors to labels. Options are
                ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
                and ``KEYPOINT`` (per keypoint index within each skeleton).

        Raises:
            ValueError: If ``color_lookup`` is ``TRACK``;
                :class:`~supervision.key_points.core.KeyPoints` carry no
                ``tracker_id``.
        """
        self.color_lookup = _validate_keypoint_color_lookup(color_lookup)
        if isinstance(color, list):
            warn_deprecated(
                "Passing a list[Color] as 'color' to VertexLabelAnnotator "
                "deprecated in `0.32.0`, removed in `0.35.0`. "
                "Use 'ColorPalette' with 'ColorLookup.KEYPOINT'."
            )
        if isinstance(text_color, list):
            warn_deprecated(
                "Passing a list[Color] as 'text_color' to VertexLabelAnnotator "
                "deprecated in `0.32.0`, removed in `0.35.0`. "
                "Use 'ColorPalette' with 'ColorLookup.KEYPOINT'."
            )
        self.border_radius: int = border_radius
        self.color: Color | list[Color] | ColorPalette = color
        self.text_color: Color | list[Color] | ColorPalette = text_color
        self.text_scale: float = text_scale
        self.text_thickness: int = text_thickness
        self.text_padding: int = text_padding
        self.smart_position = smart_position

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        key_points: KeyPoints,
        labels: list[str] | dict[int, list[str]] | None = None,
    ) -> ImageType:
        """Draws labels at skeleton vertex positions on the image. Vertices marked not
        visible via ``key_points.visible``, and vertices whose coordinates are not
        finite, are skipped.

        Args:
            scene: The image where vertex labels will be drawn. `ImageType` is a
                flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
            key_points: A collection of key points where each key point consists of x
                and y coordinates.
            labels: Labels to display at each keypoint. If ``None``, keypoint
                indices are used. A ``list[str]`` applies the same labels to
                every instance. A ``dict[int, list[str]]`` maps ``class_id``
                to per-class label lists, enabling correct labeling for
                datasets with multiple skeleton types.

        Returns:
            The annotated image, matching the type of `scene` (`numpy.ndarray`
                or `PIL.Image.Image`)

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            Single-skeleton example:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ... )
            >>> annotator = sv.VertexLabelAnnotator(
            ...     color=sv.Color.ROBOFLOW,
            ...     text_color=sv.Color.WHITE,
            ...     border_radius=5,
            ... )
            >>> result = annotator.annotate(
            ...     scene=image.copy(),
            ...     key_points=key_points,
            ...     labels=["head", "L-foot", "R-foot"],
            ... )

            ```

            Multi-skeleton example with per-class labels:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]],
            ...          [[700, 300], [650, 500], [0, 0]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0, 1]),
            ...     visible=np.array(
            ...         [[True, True, True],
            ...          [True, True, False]],
            ...     ),
            ... )
            >>> annotator = sv.VertexLabelAnnotator(
            ...     color=sv.Color.ROBOFLOW,
            ...     text_color=sv.Color.WHITE,
            ...     border_radius=5,
            ... )
            >>> result = annotator.annotate(
            ...     scene=image.copy(),
            ...     key_points=key_points,
            ...     labels={
            ...         0: ["head", "L-foot", "R-foot"],
            ...         1: ["top", "bottom", "pad"],
            ...     },
            ... )

            ```

            Per-keypoint palette example:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ... )
            >>> annotator = sv.VertexLabelAnnotator(
            ...     color=sv.ColorPalette.DEFAULT,
            ...     text_color=sv.Color.BLACK,
            ...     color_lookup=sv.ColorLookup.KEYPOINT,
            ... )
            >>> result = annotator.annotate(
            ...     scene=image.copy(),
            ...     key_points=key_points,
            ...     labels=["head", "L-foot", "R-foot"],
            ... )

            ```
        """
        font = cv2.FONT_HERSHEY_SIMPLEX

        skeletons_count, points_count, _ = key_points.xy.shape
        if skeletons_count == 0:
            return scene
        self._validate_legacy_color_lists(points_count)

        all_anchors: list[tuple[int, int]] = []
        all_labels: list[str] = []
        all_colors: list[Color] = []
        all_text_colors: list[Color] = []

        for i in range(skeletons_count):
            xy = key_points.xy[i, :, :2]

            class_id = (
                int(key_points.class_id[i]) if key_points.class_id is not None else None
            )
            instance_labels = self._resolve_labels(labels, points_count, class_id)

            for j in range(points_count):
                if not _has_finite_coordinates(xy[j]):
                    continue
                if key_points.visible is not None:
                    if not key_points.visible[i, j]:
                        continue
                elif np.allclose(xy[j], 0):
                    continue

                anchor = (int(xy[j][0]), int(xy[j][1]))
                all_anchors.append(anchor)
                all_labels.append(instance_labels[j])
                all_colors.append(
                    self._resolve_label_color_legacy(self.color, key_points, i, j)
                )
                all_text_colors.append(
                    self._resolve_label_color_legacy(self.text_color, key_points, i, j)
                )

        if not all_anchors:
            return scene

        xyxy = np.array(
            [
                self.get_text_bounding_box(
                    text=label,
                    font=font,
                    text_scale=self.text_scale,
                    text_thickness=self.text_thickness,
                    center_coordinates=anchor,
                )
                for anchor, label in zip(all_anchors, all_labels)
            ]
        )
        xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding)

        if self.smart_position:
            xyxy_padded = spread_out_boxes(xyxy_padded)
            xyxy = pad_boxes(xyxy=xyxy_padded, px=-self.text_padding)

        for text, color, text_color, box, box_padded in zip(
            all_labels, all_colors, all_text_colors, xyxy, xyxy_padded
        ):
            draw_rounded_rectangle(
                scene=scene,
                rect=Rect.from_xyxy(box_padded),
                color=color,
                border_radius=self.border_radius,
            )
            _draw_antialiased(
                scene,
                text_color.as_bgr(),
                lambda image, draw_color: cv2.putText(
                    image,
                    text,
                    (box[0], box[3]),
                    font,
                    self.text_scale,
                    draw_color,
                    self.text_thickness,
                    lineType=cv2.LINE_AA,
                ),
            )

        return scene

    @staticmethod
    def get_text_bounding_box(
        text: str,
        font: int,
        text_scale: float,
        text_thickness: int,
        center_coordinates: tuple[int, int],
    ) -> tuple[int, int, int, int]:
        text_w, text_h = cv2.getTextSize(
            text=text,
            fontFace=font,
            fontScale=text_scale,
            thickness=text_thickness,
        )[0]
        center_x, center_y = center_coordinates
        return (
            center_x - text_w // 2,
            center_y - text_h // 2,
            center_x + text_w // 2,
            center_y + text_h // 2,
        )

    @staticmethod
    def _resolve_labels(
        labels: list[str] | dict[int, list[str]] | None,
        points_count: int,
        class_id: int | None = None,
    ) -> list[str]:
        """Return the label list for a single instance."""
        if labels is None:
            return [str(j) for j in range(points_count)]

        resolved: list[str]
        if isinstance(labels, dict):
            if class_id is None:
                raise ValueError(
                    "labels is a dict but class_id is None; "
                    "KeyPoints must have class_id set."
                )
            if class_id not in labels:
                raise ValueError(f"No labels defined for class_id={class_id}.")
            resolved = labels[class_id]
        else:
            resolved = labels

        if len(resolved) != points_count:
            raise ValueError(
                f"Number of labels ({len(resolved)}) must match "
                f"number of key points ({points_count})."
            )
        return resolved

    def _validate_legacy_color_lists(self, points_count: int) -> None:
        """Check deprecated ``list[Color]`` inputs hold one color per keypoint.

        Runs once per ``annotate()`` call, before any visibility filtering, so a
        wrong-length list fails on every frame, not only when a point is drawn.
        Covers both ``color`` and ``text_color``.

        Args:
            points_count: Number of keypoints per skeleton.

        Raises:
            ValueError: If a ``list[Color]`` length differs from ``points_count``.
        """
        for color_input in (self.color, self.text_color):
            if isinstance(color_input, list) and len(color_input) != points_count:
                raise ValueError(
                    f"Number of colors ({len(color_input)}) must match "
                    f"number of key points ({points_count})."
                )

    def _resolve_label_color_legacy(
        self,
        color_input: Color | list[Color] | ColorPalette,
        key_points: KeyPoints,
        instance_idx: int,
        keypoint_idx: int,
    ) -> Color:
        """Backward-compatibility shim for resolving a label color.

        Handles the deprecated ``list[Color]`` input type by indexing
        directly into the list. For :class:`~supervision.draw.color.Color`
        and :class:`~supervision.draw.color.ColorPalette` inputs, delegates to
        :func:`~supervision.key_points.annotators._resolve_keypoint_color`.

        .. deprecated:: 0.32.0
            When ``list[Color]`` support is removed in ``0.35.0``, delete this
            method and call ``_resolve_keypoint_color`` directly. The call
            sites in ``annotate()`` should change from::

                self._resolve_label_color_legacy(self.color, ...)

            to::

                _resolve_keypoint_color(
                    color=self.color,
                    color_lookup=self.color_lookup,
                    key_points=key_points,
                    instance_idx=i,
                    keypoint_idx=keypoint_idx,
                )
        """
        if isinstance(color_input, list):
            # Length already checked once per annotate() call.
            return color_input[keypoint_idx]
        return _resolve_keypoint_color(
            color=color_input,
            color_lookup=self.color_lookup,
            key_points=key_points,
            instance_idx=instance_idx,
            keypoint_idx=keypoint_idx,
        )

Methods:

__init__(color: Color | list[Color] | ColorPalette = Color.ROBOFLOW, text_color: Color | list[Color] | ColorPalette = Color.WHITE, text_scale: float = 0.5, text_thickness: int = 1, text_padding: int = 10, border_radius: int = 0, smart_position: bool = False, color_lookup: ColorLookup = ColorLookup.CLASS) -> None

Parameters:

Name Type Description Default
color
Color | list[Color] | ColorPalette

The color to use for each keypoint label. A single :class:~supervision.draw.color.Color applies uniformly. A :class:~supervision.draw.color.ColorPalette selects colors via the color_lookup strategy. Passing a list[Color] is deprecated in 0.32.0 (removed in 0.35.0); use a :class:~supervision.draw.color.ColorPalette with ColorLookup.KEYPOINT instead.

ROBOFLOW
text_color
Color | list[Color] | ColorPalette

The color to use for the label text. Accepts the same types as color. Passing a list[Color] is deprecated in 0.32.0 (removed in 0.35.0).

WHITE
text_scale
float

Font scale for the text.

0.5
text_thickness
int

Thickness of the text characters.

1
text_padding
int

Padding around the text within its background box.

10
border_radius
int

The radius to apply round edges. If the selected value is higher than the lower dimension, width or height, is clipped.

0
smart_position
bool

Spread out the labels to avoid overlapping.

False
color_lookup
ColorLookup

:class:~supervision.annotators.utils.ColorLookup strategy for mapping palette colors to labels. Options are INDEX (per-skeleton index), CLASS (per class_id), and KEYPOINT (per keypoint index within each skeleton).

CLASS

Raises:

Type Description
ValueError

If color_lookup is TRACK; :class:~supervision.key_points.core.KeyPoints carry no tracker_id.

Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    color: Color | list[Color] | ColorPalette = Color.ROBOFLOW,
    text_color: Color | list[Color] | ColorPalette = Color.WHITE,
    text_scale: float = 0.5,
    text_thickness: int = 1,
    text_padding: int = 10,
    border_radius: int = 0,
    smart_position: bool = False,
    color_lookup: ColorLookup = ColorLookup.CLASS,
) -> None:
    """
    Args:
        color: The color to use for each keypoint label. A single
            :class:`~supervision.draw.color.Color` applies uniformly. A
            :class:`~supervision.draw.color.ColorPalette` selects colors
            via the ``color_lookup`` strategy. Passing a ``list[Color]``
            is **deprecated in** ``0.32.0`` (removed in ``0.35.0``); use a
            :class:`~supervision.draw.color.ColorPalette` with
            ``ColorLookup.KEYPOINT`` instead.
        text_color: The color to use for the label text. Accepts the
            same types as ``color``. Passing a ``list[Color]`` is
            **deprecated in** ``0.32.0`` (removed in ``0.35.0``).
        text_scale: Font scale for the text.
        text_thickness: Thickness of the text characters.
        text_padding: Padding around the text within its
            background box.
        border_radius: The radius to apply round edges. If the
            selected value is higher than the lower dimension,
            width or height, is clipped.
        smart_position: Spread out the labels to avoid overlapping.
        color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
            strategy for mapping palette colors to labels. Options are
            ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
            and ``KEYPOINT`` (per keypoint index within each skeleton).

    Raises:
        ValueError: If ``color_lookup`` is ``TRACK``;
            :class:`~supervision.key_points.core.KeyPoints` carry no
            ``tracker_id``.
    """
    self.color_lookup = _validate_keypoint_color_lookup(color_lookup)
    if isinstance(color, list):
        warn_deprecated(
            "Passing a list[Color] as 'color' to VertexLabelAnnotator "
            "deprecated in `0.32.0`, removed in `0.35.0`. "
            "Use 'ColorPalette' with 'ColorLookup.KEYPOINT'."
        )
    if isinstance(text_color, list):
        warn_deprecated(
            "Passing a list[Color] as 'text_color' to VertexLabelAnnotator "
            "deprecated in `0.32.0`, removed in `0.35.0`. "
            "Use 'ColorPalette' with 'ColorLookup.KEYPOINT'."
        )
    self.border_radius: int = border_radius
    self.color: Color | list[Color] | ColorPalette = color
    self.text_color: Color | list[Color] | ColorPalette = text_color
    self.text_scale: float = text_scale
    self.text_thickness: int = text_thickness
    self.text_padding: int = text_padding
    self.smart_position = smart_position

annotate(scene: ImageType, key_points: KeyPoints, labels: list[str] | dict[int, list[str]] | None = None) -> ImageType

Draws labels at skeleton vertex positions on the image. Vertices marked not visible via key_points.visible, and vertices whose coordinates are not finite, are skipped.

Parameters:

Name Type Description Default
scene
ImageType

The image where vertex labels will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

A collection of key points where each key point consists of x and y coordinates.

required
labels
list[str] | dict[int, list[str]] | None

Labels to display at each keypoint. If None, keypoint indices are used. A list[str] applies the same labels to every instance. A dict[int, list[str]] maps class_id to per-class label lists, enabling correct labeling for datasets with multiple skeleton types.

None

Returns:

Type Description
ImageType

The annotated image, matching the type of scene (numpy.ndarray or PIL.Image.Image)

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example

Single-skeleton example:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
... )
>>> annotator = sv.VertexLabelAnnotator(
...     color=sv.Color.ROBOFLOW,
...     text_color=sv.Color.WHITE,
...     border_radius=5,
... )
>>> result = annotator.annotate(
...     scene=image.copy(),
...     key_points=key_points,
...     labels=["head", "L-foot", "R-foot"],
... )

Multi-skeleton example with per-class labels:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]],
...          [[700, 300], [650, 500], [0, 0]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0, 1]),
...     visible=np.array(
...         [[True, True, True],
...          [True, True, False]],
...     ),
... )
>>> annotator = sv.VertexLabelAnnotator(
...     color=sv.Color.ROBOFLOW,
...     text_color=sv.Color.WHITE,
...     border_radius=5,
... )
>>> result = annotator.annotate(
...     scene=image.copy(),
...     key_points=key_points,
...     labels={
...         0: ["head", "L-foot", "R-foot"],
...         1: ["top", "bottom", "pad"],
...     },
... )

Per-keypoint palette example:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
... )
>>> annotator = sv.VertexLabelAnnotator(
...     color=sv.ColorPalette.DEFAULT,
...     text_color=sv.Color.BLACK,
...     color_lookup=sv.ColorLookup.KEYPOINT,
... )
>>> result = annotator.annotate(
...     scene=image.copy(),
...     key_points=key_points,
...     labels=["head", "L-foot", "R-foot"],
... )
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    key_points: KeyPoints,
    labels: list[str] | dict[int, list[str]] | None = None,
) -> ImageType:
    """Draws labels at skeleton vertex positions on the image. Vertices marked not
    visible via ``key_points.visible``, and vertices whose coordinates are not
    finite, are skipped.

    Args:
        scene: The image where vertex labels will be drawn. `ImageType` is a
            flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
        key_points: A collection of key points where each key point consists of x
            and y coordinates.
        labels: Labels to display at each keypoint. If ``None``, keypoint
            indices are used. A ``list[str]`` applies the same labels to
            every instance. A ``dict[int, list[str]]`` maps ``class_id``
            to per-class label lists, enabling correct labeling for
            datasets with multiple skeleton types.

    Returns:
        The annotated image, matching the type of `scene` (`numpy.ndarray`
            or `PIL.Image.Image`)

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        Single-skeleton example:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ... )
        >>> annotator = sv.VertexLabelAnnotator(
        ...     color=sv.Color.ROBOFLOW,
        ...     text_color=sv.Color.WHITE,
        ...     border_radius=5,
        ... )
        >>> result = annotator.annotate(
        ...     scene=image.copy(),
        ...     key_points=key_points,
        ...     labels=["head", "L-foot", "R-foot"],
        ... )

        ```

        Multi-skeleton example with per-class labels:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]],
        ...          [[700, 300], [650, 500], [0, 0]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0, 1]),
        ...     visible=np.array(
        ...         [[True, True, True],
        ...          [True, True, False]],
        ...     ),
        ... )
        >>> annotator = sv.VertexLabelAnnotator(
        ...     color=sv.Color.ROBOFLOW,
        ...     text_color=sv.Color.WHITE,
        ...     border_radius=5,
        ... )
        >>> result = annotator.annotate(
        ...     scene=image.copy(),
        ...     key_points=key_points,
        ...     labels={
        ...         0: ["head", "L-foot", "R-foot"],
        ...         1: ["top", "bottom", "pad"],
        ...     },
        ... )

        ```

        Per-keypoint palette example:

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ... )
        >>> annotator = sv.VertexLabelAnnotator(
        ...     color=sv.ColorPalette.DEFAULT,
        ...     text_color=sv.Color.BLACK,
        ...     color_lookup=sv.ColorLookup.KEYPOINT,
        ... )
        >>> result = annotator.annotate(
        ...     scene=image.copy(),
        ...     key_points=key_points,
        ...     labels=["head", "L-foot", "R-foot"],
        ... )

        ```
    """
    font = cv2.FONT_HERSHEY_SIMPLEX

    skeletons_count, points_count, _ = key_points.xy.shape
    if skeletons_count == 0:
        return scene
    self._validate_legacy_color_lists(points_count)

    all_anchors: list[tuple[int, int]] = []
    all_labels: list[str] = []
    all_colors: list[Color] = []
    all_text_colors: list[Color] = []

    for i in range(skeletons_count):
        xy = key_points.xy[i, :, :2]

        class_id = (
            int(key_points.class_id[i]) if key_points.class_id is not None else None
        )
        instance_labels = self._resolve_labels(labels, points_count, class_id)

        for j in range(points_count):
            if not _has_finite_coordinates(xy[j]):
                continue
            if key_points.visible is not None:
                if not key_points.visible[i, j]:
                    continue
            elif np.allclose(xy[j], 0):
                continue

            anchor = (int(xy[j][0]), int(xy[j][1]))
            all_anchors.append(anchor)
            all_labels.append(instance_labels[j])
            all_colors.append(
                self._resolve_label_color_legacy(self.color, key_points, i, j)
            )
            all_text_colors.append(
                self._resolve_label_color_legacy(self.text_color, key_points, i, j)
            )

    if not all_anchors:
        return scene

    xyxy = np.array(
        [
            self.get_text_bounding_box(
                text=label,
                font=font,
                text_scale=self.text_scale,
                text_thickness=self.text_thickness,
                center_coordinates=anchor,
            )
            for anchor, label in zip(all_anchors, all_labels)
        ]
    )
    xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding)

    if self.smart_position:
        xyxy_padded = spread_out_boxes(xyxy_padded)
        xyxy = pad_boxes(xyxy=xyxy_padded, px=-self.text_padding)

    for text, color, text_color, box, box_padded in zip(
        all_labels, all_colors, all_text_colors, xyxy, xyxy_padded
    ):
        draw_rounded_rectangle(
            scene=scene,
            rect=Rect.from_xyxy(box_padded),
            color=color,
            border_radius=self.border_radius,
        )
        _draw_antialiased(
            scene,
            text_color.as_bgr(),
            lambda image, draw_color: cv2.putText(
                image,
                text,
                (box[0], box[3]),
                font,
                self.text_scale,
                draw_color,
                self.text_thickness,
                lineType=cv2.LINE_AA,
            ),
        )

    return scene

supervision.key_points.annotators.VertexEllipseAreaAnnotator

Bases: _BaseVertexEllipseAnnotator

Draws filled semi-transparent covariance ellipses at multiple sigma levels around each keypoint, each ring in a different color. This produces a bullseye-like uncertainty visualization where inner rings represent higher probability density.

Warning

This annotator uses key_points.data["covariance"] with shape (N, K, 2, 2) in pixel coordinates.

Source code in src/supervision/key_points/annotators.py
class VertexEllipseAreaAnnotator(_BaseVertexEllipseAnnotator):
    """Draws filled semi-transparent covariance ellipses at multiple sigma levels around
    each keypoint, each ring in a different color.  This produces a bullseye-like
    uncertainty visualization where inner rings represent higher probability density.

    !!! warning

    This annotator uses `key_points.data["covariance"]` with shape `(N, K, 2, 2)` in
    pixel coordinates.
    """

    def __init__(
        self,
        sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
        color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
        opacity: float = 0.4,
        max_axis: float | None = None,
    ) -> None:
        """
        Args:
            sigma: Sigma multipliers for each ring, drawn from outermost to
                innermost.  Accepts a single float or a sequence of floats.
                Defaults to ``(1.0, 2.0, 3.0)``.
            color: The color for each sigma level.  Accepts a single
                :class:`~supervision.draw.color.Color` or a sequence of colors
                (one per sigma level).
                Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
            opacity: Opacity of the overlay mask. Must be between ``0`` and
                ``1``.
            max_axis: Optional cap for ellipse semi-axis lengths in pixels.
        """
        super().__init__(sigma=sigma, color=color, max_axis=max_axis)
        self.opacity = opacity

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Draws filled semi-transparent covariance ellipses around each keypoint.
        Keypoints marked as not visible via ``key_points.visible``, and keypoints whose
        coordinates are not finite, are skipped.

        Args:
            scene: The image to annotate. ``ImageType`` accepts either
                ``numpy.ndarray`` or ``PIL.Image.Image``.
            key_points: Key points with covariance data in
                ``key_points.data["covariance"]``.

        Returns:
            The annotated image, matching the type of ``scene``.

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ...     data={
            ...         "covariance": np.array(
            ...             [[[[800, 0], [0, 400]],
            ...               [[400, 0], [0, 800]],
            ...               [[600, 0], [0, 600]]]],
            ...             dtype=np.float32,
            ...         )
            ...     },
            ... )
            >>> annotator = sv.VertexEllipseAreaAnnotator(
            ...     sigma=[1.0, 2.0],
            ...     color=[sv.Color.GREEN, sv.Color.RED],
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0:
            return scene
        if scene.ndim == 3 and scene.shape[2] == 4:
            return self._annotate_bgra(scene, key_points)

        overlay = scene.copy()
        for level in self._iter_ellipse_params(key_points):
            for center, axis_lengths, angle, _sigma, color in level:
                cv2.ellipse(
                    img=overlay,
                    center=center,
                    axes=axis_lengths,
                    angle=angle,
                    startAngle=0,
                    endAngle=360,
                    color=_color_for_canvas(color.as_bgr(), overlay),
                    thickness=-1,
                    lineType=cv2.LINE_AA,
                )

        cv2.addWeighted(overlay, self.opacity, scene, 1 - self.opacity, 0, dst=scene)
        return scene

    def _annotate_bgra(
        self, scene: npt.NDArray[np.uint8], key_points: KeyPoints
    ) -> npt.NDArray[np.uint8]:
        """Composite the filled ellipses over a BGRA scene by coverage and opacity.

        Each anti-aliased ellipse is rendered into its own coverage mask and layered
        over the earlier ones in premultiplied color, so neither the scene's hidden
        colors nor transparent black at the edges tint the result.
        """
        height, width = scene.shape[:2]
        premultiplied = np.zeros((height, width, 3), dtype=np.float32)
        coverage = np.zeros((height, width, 1), dtype=np.float32)
        for level in self._iter_ellipse_params(key_points):
            for center, axis_lengths, angle, _sigma, color in level:
                # One pixel of margin keeps the anti-aliased edge inside the region.
                reach = max(axis_lengths) + 1
                x0, y0 = max(center[0] - reach, 0), max(center[1] - reach, 0)
                x1 = min(center[0] + reach + 1, width)
                y1 = min(center[1] + reach + 1, height)
                if x0 >= x1 or y0 >= y1:
                    continue
                mask = np.zeros((y1 - y0, x1 - x0), dtype=np.uint8)
                cv2.ellipse(
                    img=mask,
                    center=(center[0] - x0, center[1] - y0),
                    axes=axis_lengths,
                    angle=angle,
                    startAngle=0,
                    endAngle=360,
                    color=255,
                    thickness=-1,
                    lineType=cv2.LINE_AA,
                )
                weight = mask[..., None].astype(np.float32) / 255.0
                region = (slice(y0, y1), slice(x0, x1))
                premultiplied[region] = premultiplied[region] * (
                    1 - weight
                ) + weight * np.array(color.as_bgr(), dtype=np.float32)
                coverage[region] = coverage[region] * (1 - weight) + weight

        colors = np.divide(
            premultiplied,
            coverage,
            out=np.zeros_like(premultiplied),
            where=np.broadcast_to(coverage > 0, premultiplied.shape),
        )
        return _composite_coverage_over_bgra(
            scene, colors, coverage[..., 0], self.opacity
        )

Methods:

__init__(sigma: float | Sequence[float] = (1.0, 2.0, 3.0), color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), opacity: float = 0.4, max_axis: float | None = None) -> None

Parameters:

Name Type Description Default
sigma
float | Sequence[float]

Sigma multipliers for each ring, drawn from outermost to innermost. Accepts a single float or a sequence of floats. Defaults to (1.0, 2.0, 3.0).

(1.0, 2.0, 3.0)
color
Color | Sequence[Color]

The color for each sigma level. Accepts a single :class:~supervision.draw.color.Color or a sequence of colors (one per sigma level). Defaults to (Color.GREEN, Color.YELLOW, Color.RED).

(GREEN, YELLOW, RED)
opacity
float

Opacity of the overlay mask. Must be between 0 and 1.

0.4
max_axis
float | None

Optional cap for ellipse semi-axis lengths in pixels.

None
Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
    color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
    opacity: float = 0.4,
    max_axis: float | None = None,
) -> None:
    """
    Args:
        sigma: Sigma multipliers for each ring, drawn from outermost to
            innermost.  Accepts a single float or a sequence of floats.
            Defaults to ``(1.0, 2.0, 3.0)``.
        color: The color for each sigma level.  Accepts a single
            :class:`~supervision.draw.color.Color` or a sequence of colors
            (one per sigma level).
            Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
        opacity: Opacity of the overlay mask. Must be between ``0`` and
            ``1``.
        max_axis: Optional cap for ellipse semi-axis lengths in pixels.
    """
    super().__init__(sigma=sigma, color=color, max_axis=max_axis)
    self.opacity = opacity

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Draws filled semi-transparent covariance ellipses around each keypoint. Keypoints marked as not visible via key_points.visible, and keypoints whose coordinates are not finite, are skipped.

Parameters:

Name Type Description Default
scene
ImageType

The image to annotate. ImageType accepts either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

Key points with covariance data in key_points.data["covariance"].

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene.

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
...     data={
...         "covariance": np.array(
...             [[[[800, 0], [0, 400]],
...               [[400, 0], [0, 800]],
...               [[600, 0], [0, 600]]]],
...             dtype=np.float32,
...         )
...     },
... )
>>> annotator = sv.VertexEllipseAreaAnnotator(
...     sigma=[1.0, 2.0],
...     color=[sv.Color.GREEN, sv.Color.RED],
... )
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Draws filled semi-transparent covariance ellipses around each keypoint.
    Keypoints marked as not visible via ``key_points.visible``, and keypoints whose
    coordinates are not finite, are skipped.

    Args:
        scene: The image to annotate. ``ImageType`` accepts either
            ``numpy.ndarray`` or ``PIL.Image.Image``.
        key_points: Key points with covariance data in
            ``key_points.data["covariance"]``.

    Returns:
        The annotated image, matching the type of ``scene``.

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ...     data={
        ...         "covariance": np.array(
        ...             [[[[800, 0], [0, 400]],
        ...               [[400, 0], [0, 800]],
        ...               [[600, 0], [0, 600]]]],
        ...             dtype=np.float32,
        ...         )
        ...     },
        ... )
        >>> annotator = sv.VertexEllipseAreaAnnotator(
        ...     sigma=[1.0, 2.0],
        ...     color=[sv.Color.GREEN, sv.Color.RED],
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0:
        return scene
    if scene.ndim == 3 and scene.shape[2] == 4:
        return self._annotate_bgra(scene, key_points)

    overlay = scene.copy()
    for level in self._iter_ellipse_params(key_points):
        for center, axis_lengths, angle, _sigma, color in level:
            cv2.ellipse(
                img=overlay,
                center=center,
                axes=axis_lengths,
                angle=angle,
                startAngle=0,
                endAngle=360,
                color=_color_for_canvas(color.as_bgr(), overlay),
                thickness=-1,
                lineType=cv2.LINE_AA,
            )

    cv2.addWeighted(overlay, self.opacity, scene, 1 - self.opacity, 0, dst=scene)
    return scene

supervision.key_points.annotators.VertexEllipseOutlineAnnotator

Bases: _BaseVertexEllipseAnnotator

Draws stroke-only concentric covariance ellipse rings at multiple sigma levels around each keypoint.

Warning

This annotator uses key_points.data["covariance"] with shape (N, K, 2, 2) in pixel coordinates.

Source code in src/supervision/key_points/annotators.py
class VertexEllipseOutlineAnnotator(_BaseVertexEllipseAnnotator):
    """Draws stroke-only concentric covariance ellipse rings at multiple sigma levels
    around each keypoint.

    !!! warning

    This annotator uses `key_points.data["covariance"]` with shape `(N, K, 2, 2)` in
    pixel coordinates.
    """

    def __init__(
        self,
        sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
        color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
        thickness: int = 2,
        max_axis: float | None = None,
    ) -> None:
        """
        Args:
            sigma: Sigma multipliers for each ring, drawn from outermost to
                innermost.  Accepts a single float or a sequence of floats.
                Defaults to ``(1.0, 2.0, 3.0)``.
            color: The color for each sigma level.  Accepts a single
                :class:`~supervision.draw.color.Color` or a sequence of colors
                (one per sigma level).
                Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
            thickness: Line thickness of the ellipse outlines.
            max_axis: Optional cap for ellipse semi-axis lengths in pixels.
        """
        super().__init__(sigma=sigma, color=color, max_axis=max_axis)
        self.thickness = thickness

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Draws stroke-only covariance ellipse outlines around each keypoint. Keypoints
        marked as not visible via ``key_points.visible``, and keypoints whose
        coordinates are not finite, are skipped.

        Args:
            scene: The image to annotate. ``ImageType`` accepts either
                ``numpy.ndarray`` or ``PIL.Image.Image``.
            key_points: Key points with covariance data in
                ``key_points.data["covariance"]``.

        Returns:
            The annotated image, matching the type of ``scene``.

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ...     data={
            ...         "covariance": np.array(
            ...             [[[[800, 0], [0, 400]],
            ...               [[400, 0], [0, 800]],
            ...               [[600, 0], [0, 600]]]],
            ...             dtype=np.float32,
            ...         )
            ...     },
            ... )
            >>> annotator = sv.VertexEllipseOutlineAnnotator(
            ...     sigma=[1.0, 2.0],
            ...     color=[sv.Color.GREEN, sv.Color.RED],
            ...     thickness=2,
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0:
            return scene

        for level in self._iter_ellipse_params(key_points):
            for center, axis_lengths, angle, _sigma, color in level:
                _draw_antialiased(
                    scene,
                    color.as_bgr(),
                    lambda image, draw_color: cv2.ellipse(
                        image,
                        center,
                        axis_lengths,
                        angle,
                        0,
                        360,
                        draw_color,
                        self.thickness,
                        lineType=cv2.LINE_AA,
                    ),
                )

        return scene

Methods:

__init__(sigma: float | Sequence[float] = (1.0, 2.0, 3.0), color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), thickness: int = 2, max_axis: float | None = None) -> None

Parameters:

Name Type Description Default
sigma
float | Sequence[float]

Sigma multipliers for each ring, drawn from outermost to innermost. Accepts a single float or a sequence of floats. Defaults to (1.0, 2.0, 3.0).

(1.0, 2.0, 3.0)
color
Color | Sequence[Color]

The color for each sigma level. Accepts a single :class:~supervision.draw.color.Color or a sequence of colors (one per sigma level). Defaults to (Color.GREEN, Color.YELLOW, Color.RED).

(GREEN, YELLOW, RED)
thickness
int

Line thickness of the ellipse outlines.

2
max_axis
float | None

Optional cap for ellipse semi-axis lengths in pixels.

None
Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
    color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
    thickness: int = 2,
    max_axis: float | None = None,
) -> None:
    """
    Args:
        sigma: Sigma multipliers for each ring, drawn from outermost to
            innermost.  Accepts a single float or a sequence of floats.
            Defaults to ``(1.0, 2.0, 3.0)``.
        color: The color for each sigma level.  Accepts a single
            :class:`~supervision.draw.color.Color` or a sequence of colors
            (one per sigma level).
            Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
        thickness: Line thickness of the ellipse outlines.
        max_axis: Optional cap for ellipse semi-axis lengths in pixels.
    """
    super().__init__(sigma=sigma, color=color, max_axis=max_axis)
    self.thickness = thickness

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Draws stroke-only covariance ellipse outlines around each keypoint. Keypoints marked as not visible via key_points.visible, and keypoints whose coordinates are not finite, are skipped.

Parameters:

Name Type Description Default
scene
ImageType

The image to annotate. ImageType accepts either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

Key points with covariance data in key_points.data["covariance"].

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene.

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
...     data={
...         "covariance": np.array(
...             [[[[800, 0], [0, 400]],
...               [[400, 0], [0, 800]],
...               [[600, 0], [0, 600]]]],
...             dtype=np.float32,
...         )
...     },
... )
>>> annotator = sv.VertexEllipseOutlineAnnotator(
...     sigma=[1.0, 2.0],
...     color=[sv.Color.GREEN, sv.Color.RED],
...     thickness=2,
... )
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Draws stroke-only covariance ellipse outlines around each keypoint. Keypoints
    marked as not visible via ``key_points.visible``, and keypoints whose
    coordinates are not finite, are skipped.

    Args:
        scene: The image to annotate. ``ImageType`` accepts either
            ``numpy.ndarray`` or ``PIL.Image.Image``.
        key_points: Key points with covariance data in
            ``key_points.data["covariance"]``.

    Returns:
        The annotated image, matching the type of ``scene``.

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ...     data={
        ...         "covariance": np.array(
        ...             [[[[800, 0], [0, 400]],
        ...               [[400, 0], [0, 800]],
        ...               [[600, 0], [0, 600]]]],
        ...             dtype=np.float32,
        ...         )
        ...     },
        ... )
        >>> annotator = sv.VertexEllipseOutlineAnnotator(
        ...     sigma=[1.0, 2.0],
        ...     color=[sv.Color.GREEN, sv.Color.RED],
        ...     thickness=2,
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0:
        return scene

    for level in self._iter_ellipse_params(key_points):
        for center, axis_lengths, angle, _sigma, color in level:
            _draw_antialiased(
                scene,
                color.as_bgr(),
                lambda image, draw_color: cv2.ellipse(
                    image,
                    center,
                    axis_lengths,
                    angle,
                    0,
                    360,
                    draw_color,
                    self.thickness,
                    lineType=cv2.LINE_AA,
                ),
            )

    return scene

supervision.key_points.annotators.VertexEllipseHaloAnnotator

Bases: _BaseVertexEllipseAnnotator

Draws filled covariance ellipses with a radial fade: full opacity at the center, smoothly falling off to zero at the ellipse boundary. The falloff follows a power curve controlled by decay, producing a soft glow that is strongest near the keypoint.

Warning

This annotator uses key_points.data["covariance"] with shape (N, K, 2, 2) in pixel coordinates.

Source code in src/supervision/key_points/annotators.py
class VertexEllipseHaloAnnotator(_BaseVertexEllipseAnnotator):
    """Draws filled covariance ellipses with a radial fade: full opacity at the center,
    smoothly falling off to zero at the ellipse boundary.  The falloff follows a power
    curve controlled by ``decay``, producing a soft glow that is strongest near the
    keypoint.

    !!! warning

    This annotator uses `key_points.data["covariance"]` with shape `(N, K, 2, 2)` in
    pixel coordinates.
    """

    _DECAY: float = 2.0

    def __init__(
        self,
        sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
        color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
        opacity: float = 0.6,
        max_axis: float | None = None,
    ) -> None:
        """
        Args:
            sigma: Sigma multipliers for each ring, drawn from outermost to
                innermost.  Accepts a single float or a sequence of floats.
                Defaults to ``(1.0, 2.0, 3.0)``.
            color: The color for each sigma level.  Accepts a single
                :class:`~supervision.draw.color.Color` or a sequence of colors
                (one per sigma level).
                Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
            opacity: Peak opacity at the ellipse center. Must be between ``0``
                and ``1``.
            max_axis: Optional cap for ellipse semi-axis lengths in pixels.
        """
        super().__init__(sigma=sigma, color=color, max_axis=max_axis)
        self.opacity = opacity

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Draws radially-fading covariance ellipses around each keypoint. Keypoints
        marked as not visible via ``key_points.visible``, and keypoints whose
        coordinates are not finite, are skipped.

        Args:
            scene: The image to annotate. ``ImageType`` accepts either
                ``numpy.ndarray`` or ``PIL.Image.Image``.
            key_points: Key points with covariance data in
                ``key_points.data["covariance"]``.

        Returns:
            The annotated image, matching the type of ``scene``.

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[400, 200], [300, 500], [500, 500]]],
            ...         dtype=np.float32,
            ...     ),
            ...     class_id=np.array([0]),
            ...     visible=np.array([[True, True, True]]),
            ...     data={
            ...         "covariance": np.array(
            ...             [[[[800, 0], [0, 400]],
            ...               [[400, 0], [0, 800]],
            ...               [[600, 0], [0, 600]]]],
            ...             dtype=np.float32,
            ...         )
            ...     },
            ... )
            >>> annotator = sv.VertexEllipseHaloAnnotator(
            ...     sigma=[1.0, 2.0],
            ...     color=[sv.Color.GREEN, sv.Color.RED],
            ... )
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0:
            return scene

        h, w = scene.shape[:2]
        # Blend in an (H, W, C) view so a grayscale scene broadcasts like a BGR one.
        composite: npt.NDArray[np.float32] = np.atleast_3d(scene).astype(np.float32)

        for level in self._iter_ellipse_params(key_points):
            for center, axis_lengths, angle, _sigma, color in level:
                ax, ay = axis_lengths
                if ax == 0 or ay == 0:
                    continue

                # `ax` runs along `angle`, not along the image x axis, so the region
                # must cover the rotated ellipse's bounding box or a vertical or
                # diagonal ellipse is cut off.
                pad = 2
                cos_t, sin_t = np.cos(np.radians(angle)), np.sin(np.radians(angle))
                roi_half_w = int(np.ceil(np.hypot(ax * cos_t, ay * sin_t))) + pad
                roi_half_h = int(np.ceil(np.hypot(ax * sin_t, ay * cos_t))) + pad
                cx, cy = center

                x_min = max(cx - roi_half_w, 0)
                x_max = min(cx + roi_half_w, w)
                y_min = max(cy - roi_half_h, 0)
                y_max = min(cy + roi_half_h, h)
                if x_min >= x_max or y_min >= y_max:
                    continue

                ys = np.arange(y_min, y_max, dtype=np.float32) - cy
                xs = np.arange(x_min, x_max, dtype=np.float32) - cx
                grid_x, grid_y = np.meshgrid(xs, ys)

                angle_rad = np.radians(-angle)
                cos_a = np.cos(angle_rad)
                sin_a = np.sin(angle_rad)
                rx = grid_x * cos_a - grid_y * sin_a
                ry = grid_x * sin_a + grid_y * cos_a

                dist_sq = (rx / ax) ** 2 + (ry / ay) ** 2
                inside = dist_sq <= 1.0

                falloff = np.zeros_like(dist_sq)
                falloff[inside] = (1.0 - dist_sq[inside]) ** self._DECAY

                scaled_alpha = falloff * self.opacity

                pixel = np.array(
                    _color_for_canvas(color.as_bgr(), scene), dtype=np.float32
                )
                roi = composite[y_min:y_max, x_min:x_max]
                alpha_3 = scaled_alpha[:, :, np.newaxis]
                roi[:] = roi * (1 - alpha_3) + pixel * alpha_3

        np.copyto(scene, composite.astype(np.uint8).reshape(scene.shape))
        return scene

Methods:

__init__(sigma: float | Sequence[float] = (1.0, 2.0, 3.0), color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), opacity: float = 0.6, max_axis: float | None = None) -> None

Parameters:

Name Type Description Default
sigma
float | Sequence[float]

Sigma multipliers for each ring, drawn from outermost to innermost. Accepts a single float or a sequence of floats. Defaults to (1.0, 2.0, 3.0).

(1.0, 2.0, 3.0)
color
Color | Sequence[Color]

The color for each sigma level. Accepts a single :class:~supervision.draw.color.Color or a sequence of colors (one per sigma level). Defaults to (Color.GREEN, Color.YELLOW, Color.RED).

(GREEN, YELLOW, RED)
opacity
float

Peak opacity at the ellipse center. Must be between 0 and 1.

0.6
max_axis
float | None

Optional cap for ellipse semi-axis lengths in pixels.

None
Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    sigma: float | Sequence[float] = (1.0, 2.0, 3.0),
    color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED),
    opacity: float = 0.6,
    max_axis: float | None = None,
) -> None:
    """
    Args:
        sigma: Sigma multipliers for each ring, drawn from outermost to
            innermost.  Accepts a single float or a sequence of floats.
            Defaults to ``(1.0, 2.0, 3.0)``.
        color: The color for each sigma level.  Accepts a single
            :class:`~supervision.draw.color.Color` or a sequence of colors
            (one per sigma level).
            Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``.
        opacity: Peak opacity at the ellipse center. Must be between ``0``
            and ``1``.
        max_axis: Optional cap for ellipse semi-axis lengths in pixels.
    """
    super().__init__(sigma=sigma, color=color, max_axis=max_axis)
    self.opacity = opacity

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Draws radially-fading covariance ellipses around each keypoint. Keypoints marked as not visible via key_points.visible, and keypoints whose coordinates are not finite, are skipped.

Parameters:

Name Type Description Default
scene
ImageType

The image to annotate. ImageType accepts either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

Key points with covariance data in key_points.data["covariance"].

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene.

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((800, 800, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[400, 200], [300, 500], [500, 500]]],
...         dtype=np.float32,
...     ),
...     class_id=np.array([0]),
...     visible=np.array([[True, True, True]]),
...     data={
...         "covariance": np.array(
...             [[[[800, 0], [0, 400]],
...               [[400, 0], [0, 800]],
...               [[600, 0], [0, 600]]]],
...             dtype=np.float32,
...         )
...     },
... )
>>> annotator = sv.VertexEllipseHaloAnnotator(
...     sigma=[1.0, 2.0],
...     color=[sv.Color.GREEN, sv.Color.RED],
... )
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Draws radially-fading covariance ellipses around each keypoint. Keypoints
    marked as not visible via ``key_points.visible``, and keypoints whose
    coordinates are not finite, are skipped.

    Args:
        scene: The image to annotate. ``ImageType`` accepts either
            ``numpy.ndarray`` or ``PIL.Image.Image``.
        key_points: Key points with covariance data in
            ``key_points.data["covariance"]``.

    Returns:
        The annotated image, matching the type of ``scene``.

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((800, 800, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[400, 200], [300, 500], [500, 500]]],
        ...         dtype=np.float32,
        ...     ),
        ...     class_id=np.array([0]),
        ...     visible=np.array([[True, True, True]]),
        ...     data={
        ...         "covariance": np.array(
        ...             [[[[800, 0], [0, 400]],
        ...               [[400, 0], [0, 800]],
        ...               [[600, 0], [0, 600]]]],
        ...             dtype=np.float32,
        ...         )
        ...     },
        ... )
        >>> annotator = sv.VertexEllipseHaloAnnotator(
        ...     sigma=[1.0, 2.0],
        ...     color=[sv.Color.GREEN, sv.Color.RED],
        ... )
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0:
        return scene

    h, w = scene.shape[:2]
    # Blend in an (H, W, C) view so a grayscale scene broadcasts like a BGR one.
    composite: npt.NDArray[np.float32] = np.atleast_3d(scene).astype(np.float32)

    for level in self._iter_ellipse_params(key_points):
        for center, axis_lengths, angle, _sigma, color in level:
            ax, ay = axis_lengths
            if ax == 0 or ay == 0:
                continue

            # `ax` runs along `angle`, not along the image x axis, so the region
            # must cover the rotated ellipse's bounding box or a vertical or
            # diagonal ellipse is cut off.
            pad = 2
            cos_t, sin_t = np.cos(np.radians(angle)), np.sin(np.radians(angle))
            roi_half_w = int(np.ceil(np.hypot(ax * cos_t, ay * sin_t))) + pad
            roi_half_h = int(np.ceil(np.hypot(ax * sin_t, ay * cos_t))) + pad
            cx, cy = center

            x_min = max(cx - roi_half_w, 0)
            x_max = min(cx + roi_half_w, w)
            y_min = max(cy - roi_half_h, 0)
            y_max = min(cy + roi_half_h, h)
            if x_min >= x_max or y_min >= y_max:
                continue

            ys = np.arange(y_min, y_max, dtype=np.float32) - cy
            xs = np.arange(x_min, x_max, dtype=np.float32) - cx
            grid_x, grid_y = np.meshgrid(xs, ys)

            angle_rad = np.radians(-angle)
            cos_a = np.cos(angle_rad)
            sin_a = np.sin(angle_rad)
            rx = grid_x * cos_a - grid_y * sin_a
            ry = grid_x * sin_a + grid_y * cos_a

            dist_sq = (rx / ax) ** 2 + (ry / ay) ** 2
            inside = dist_sq <= 1.0

            falloff = np.zeros_like(dist_sq)
            falloff[inside] = (1.0 - dist_sq[inside]) ** self._DECAY

            scaled_alpha = falloff * self.opacity

            pixel = np.array(
                _color_for_canvas(color.as_bgr(), scene), dtype=np.float32
            )
            roi = composite[y_min:y_max, x_min:x_max]
            alpha_3 = scaled_alpha[:, :, np.newaxis]
            roi[:] = roi * (1 - alpha_3) + pixel * alpha_3

    np.copyto(scene, composite.astype(np.uint8).reshape(scene.shape))
    return scene

supervision.key_points.annotators.JointAngleAnnotator

Bases: BaseKeyPointAnnotator

Draws an arc at each joint, between its two rays, labelled with the angle.

The angles come from :func:~supervision.key_points.angles.joint_angles, so a joint is skipped whenever its angle is NaN: one of its points is hidden via key_points.visible, has a non-finite x/y coordinate or sits at [0, 0]. The annotator applies no confidence threshold of its own; filter or hide unreliable points before annotating. Joints narrower than one degree get no arc, only their label when show_value is set. Because the interior angle never exceeds 180 degrees, the arc of a joint that bends through straight moves to the other side. On a BGRA scene, arcs and labels are composited according to their coverage and other pixels keep their alpha.

Source code in src/supervision/key_points/annotators.py
class JointAngleAnnotator(BaseKeyPointAnnotator):
    """Draws an arc at each joint, between its two rays, labelled with the angle.

    The angles come from :func:`~supervision.key_points.angles.joint_angles`, so a
    joint is skipped whenever its angle is ``NaN``: one of its points is hidden via
    ``key_points.visible``, has a non-finite x/y coordinate or sits at ``[0, 0]``.
    The annotator applies no confidence threshold of its own; filter or hide
    unreliable points before annotating. Joints narrower than one degree get no
    arc, only their label when ``show_value`` is set. Because the interior angle
    never exceeds 180 degrees, the arc of a joint that bends through straight moves
    to the other side. On a BGRA scene, arcs and labels are composited according
    to their coverage and other pixels keep their alpha.
    """

    def __init__(
        self,
        angles: Sequence[JointAngle],
        color: Color | ColorPalette = Color.ROBOFLOW,
        thickness: int = 2,
        radius: int = 20,
        show_value: bool = True,
        text_color: Color | ColorPalette = Color.WHITE,
        text_scale: float = 0.5,
        text_thickness: int = 1,
        text_padding: int = 4,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ) -> None:
        """
        Args:
            angles: The joints to draw, see
                :class:`~supervision.key_points.angles.JointAngle`.
            color: The :class:`~supervision.draw.color.Color` or
                :class:`~supervision.draw.color.ColorPalette` of the arcs and of the
                label backgrounds.
            thickness: The line thickness of the arcs.
            radius: The radius of the arcs, in pixels.
            show_value: Whether to label each arc with its angle in whole degrees,
                such as ``90°``. The label carries the degree sign, so a bare number
                is never read as radians.
            text_color: The :class:`~supervision.draw.color.Color` or
                :class:`~supervision.draw.color.ColorPalette` of the label text.
            text_scale: The font scale of the label text.
            text_thickness: The thickness of the label text.
            text_padding: The padding between the label text and its background.
            color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
                strategy for mapping palette colors to joints. Options are
                ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
                and ``KEYPOINT`` (per keypoint index; a joint takes the color of
                its ``joint`` point).

        Raises:
            ValueError: If ``radius`` or ``thickness`` is not positive, or if
                ``color_lookup`` is ``TRACK``;
                :class:`~supervision.key_points.core.KeyPoints` carry no
                ``tracker_id``.
        """
        if radius <= 0:
            raise ValueError(f"radius must be positive, got {radius}.")
        if thickness <= 0:
            raise ValueError(f"thickness must be positive, got {thickness}.")
        self.angles = tuple(angles)
        self.color = color
        self.thickness = thickness
        self.radius = radius
        self.show_value = show_value
        self.text_color = text_color
        self.text_scale = text_scale
        self.text_thickness = text_thickness
        self.text_padding = text_padding
        self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
        """Annotates the given scene with an arc, and optionally the angle in
        degrees, at every measurable joint of every skeleton.

        Args:
            scene: The image where the joint angles will be drawn. `ImageType` is a
                flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
            key_points: A collection of key points. Only the first two coordinate
                channels, x and y, determine angles and pixel positions.

        Returns:
            The annotated image, matching the type of `scene` (`numpy.ndarray`
                or `PIL.Image.Image`)

        Raises:
            TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.
            ValueError: If a joint refers to a position outside the key points.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((200, 200, 3), dtype=np.uint8)
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array(
            ...         [[[100, 50], [100, 100], [150, 100]]],
            ...         dtype=np.float32,
            ...     )
            ... )
            >>> from supervision.key_points.angles import JointAngle
            >>> knee = JointAngle(name="knee", start=0, joint=1, end=2)
            >>> annotator = sv.JointAngleAnnotator(angles=[knee])
            >>> result = annotator.annotate(image.copy(), key_points)

            ```
        """
        if len(key_points) == 0 or not self.angles:
            return scene

        values = joint_angles(key_points, self.angles)
        xy = key_points.xy[..., :2].astype(np.float64)
        measured = list(zip(*np.nonzero(np.isfinite(values))))
        # Resolve every color before the first draw, as VertexLabelAnnotator does,
        # so a lookup that raises leaves the caller's scene untouched.
        joint_colors = [
            self._resolve_joint_colors(
                key_points, int(skeleton_index), self.angles[angle_index].joint
            )
            for skeleton_index, angle_index in measured
        ]
        for (skeleton_index, angle_index), (color, text_color) in zip(
            measured, joint_colors
        ):
            angle = self.angles[angle_index]
            joint_xy = xy[skeleton_index, angle.joint]
            heading_start = self._heading(xy[skeleton_index, angle.start] - joint_xy)
            heading_end = self._heading(xy[skeleton_index, angle.end] - joint_xy)
            # The interior angle never exceeds 180 degrees, so the arc follows the
            # shorter way round from ray start to ray end. Both backends draw an arc
            # clockwise from the smaller to the larger angle in image coordinates.
            sweep = (heading_end - heading_start + 180.0) % 360.0 - 180.0
            start_angle, end_angle = sorted((heading_start, heading_start + sweep))
            # Both backends draw whole degrees, so a sub-degree arc would collapse
            # into a dot on the joint; such joints keep only their label.
            if end_angle - start_angle >= 1.0:
                _draw_antialiased(
                    scene,
                    color.as_bgr(),
                    lambda image, draw_color: cv2.ellipse(
                        image,
                        (int(joint_xy[0]), int(joint_xy[1])),
                        (self.radius, self.radius),
                        0.0,
                        start_angle,
                        end_angle,
                        draw_color,
                        self.thickness,
                        cv2.LINE_AA,
                    ),
                )
            if text_color is not None:
                self._draw_value(
                    scene=scene,
                    text=f"{values[skeleton_index, angle_index]:.0f}\N{DEGREE SIGN}",
                    color=color,
                    text_color=text_color,
                    joint_xy=joint_xy,
                    bisector=np.radians(heading_start + sweep / 2.0),
                )
        return scene

    def _resolve_joint_colors(
        self, key_points: KeyPoints, skeleton_index: int, joint_index: int
    ) -> tuple[Color, Color | None]:
        """Return the arc color of a joint and its text color, or ``None`` for the text
        color when no label is shown.

        Both follow ``color_lookup``; under ``KEYPOINT`` a joint takes the colors of its
        joint. A label that is not shown never resolves its text color, so an unused
        ``text_color`` palette cannot raise.
        """
        color = _resolve_keypoint_color(
            color=self.color,
            color_lookup=self.color_lookup,
            key_points=key_points,
            instance_idx=skeleton_index,
            keypoint_idx=joint_index,
        )
        if not self.show_value:
            return color, None
        text_color = _resolve_keypoint_color(
            color=self.text_color,
            color_lookup=self.color_lookup,
            key_points=key_points,
            instance_idx=skeleton_index,
            keypoint_idx=joint_index,
        )
        return color, text_color

    @staticmethod
    def _heading(ray: npt.NDArray[np.float64]) -> float:
        """Return the direction of a ray in degrees, clockwise from +x in the image."""
        return float(np.degrees(np.arctan2(ray[1], ray[0])))

    def _draw_value(
        self,
        scene: npt.NDArray[np.uint8],
        text: str,
        color: Color,
        text_color: Color,
        joint_xy: npt.NDArray[np.float64],
        bisector: float,
    ) -> None:
        """Draw the label on the bisector, just outside the arc so it never covers the
        arc or the joint itself."""
        (text_width, text_height), _ = cv2.getTextSize(
            text, cv2.FONT_HERSHEY_SIMPLEX, self.text_scale, self.text_thickness
        )
        half_diagonal = 0.5 * float(
            np.hypot(
                text_width + 2 * self.text_padding, text_height + 2 * self.text_padding
            )
        )
        distance = self.radius + self.thickness + half_diagonal
        center = joint_xy + distance * np.array([np.cos(bisector), np.sin(bisector)])
        draw_text(
            scene=scene,
            text=text,
            text_anchor=Point(x=float(center[0]), y=float(center[1])),
            text_color=text_color,
            text_scale=self.text_scale,
            text_thickness=self.text_thickness,
            text_padding=self.text_padding,
            background_color=color,
        )

Methods:

__init__(angles: Sequence[JointAngle], color: Color | ColorPalette = Color.ROBOFLOW, thickness: int = 2, radius: int = 20, show_value: bool = True, text_color: Color | ColorPalette = Color.WHITE, text_scale: float = 0.5, text_thickness: int = 1, text_padding: int = 4, color_lookup: ColorLookup = ColorLookup.CLASS) -> None

Parameters:

Name Type Description Default
angles
Sequence[JointAngle]

The joints to draw, see :class:~supervision.key_points.angles.JointAngle.

required
color
Color | ColorPalette

The :class:~supervision.draw.color.Color or :class:~supervision.draw.color.ColorPalette of the arcs and of the label backgrounds.

ROBOFLOW
thickness
int

The line thickness of the arcs.

2
radius
int

The radius of the arcs, in pixels.

20
show_value
bool

Whether to label each arc with its angle in whole degrees, such as 90°. The label carries the degree sign, so a bare number is never read as radians.

True
text_color
Color | ColorPalette

The :class:~supervision.draw.color.Color or :class:~supervision.draw.color.ColorPalette of the label text.

WHITE
text_scale
float

The font scale of the label text.

0.5
text_thickness
int

The thickness of the label text.

1
text_padding
int

The padding between the label text and its background.

4
color_lookup
ColorLookup

:class:~supervision.annotators.utils.ColorLookup strategy for mapping palette colors to joints. Options are INDEX (per-skeleton index), CLASS (per class_id), and KEYPOINT (per keypoint index; a joint takes the color of its joint point).

CLASS

Raises:

Type Description
ValueError

If radius or thickness is not positive, or if color_lookup is TRACK; :class:~supervision.key_points.core.KeyPoints carry no tracker_id.

Source code in src/supervision/key_points/annotators.py
def __init__(
    self,
    angles: Sequence[JointAngle],
    color: Color | ColorPalette = Color.ROBOFLOW,
    thickness: int = 2,
    radius: int = 20,
    show_value: bool = True,
    text_color: Color | ColorPalette = Color.WHITE,
    text_scale: float = 0.5,
    text_thickness: int = 1,
    text_padding: int = 4,
    color_lookup: ColorLookup = ColorLookup.CLASS,
) -> None:
    """
    Args:
        angles: The joints to draw, see
            :class:`~supervision.key_points.angles.JointAngle`.
        color: The :class:`~supervision.draw.color.Color` or
            :class:`~supervision.draw.color.ColorPalette` of the arcs and of the
            label backgrounds.
        thickness: The line thickness of the arcs.
        radius: The radius of the arcs, in pixels.
        show_value: Whether to label each arc with its angle in whole degrees,
            such as ``90°``. The label carries the degree sign, so a bare number
            is never read as radians.
        text_color: The :class:`~supervision.draw.color.Color` or
            :class:`~supervision.draw.color.ColorPalette` of the label text.
        text_scale: The font scale of the label text.
        text_thickness: The thickness of the label text.
        text_padding: The padding between the label text and its background.
        color_lookup: :class:`~supervision.annotators.utils.ColorLookup`
            strategy for mapping palette colors to joints. Options are
            ``INDEX`` (per-skeleton index), ``CLASS`` (per ``class_id``),
            and ``KEYPOINT`` (per keypoint index; a joint takes the color of
            its ``joint`` point).

    Raises:
        ValueError: If ``radius`` or ``thickness`` is not positive, or if
            ``color_lookup`` is ``TRACK``;
            :class:`~supervision.key_points.core.KeyPoints` carry no
            ``tracker_id``.
    """
    if radius <= 0:
        raise ValueError(f"radius must be positive, got {radius}.")
    if thickness <= 0:
        raise ValueError(f"thickness must be positive, got {thickness}.")
    self.angles = tuple(angles)
    self.color = color
    self.thickness = thickness
    self.radius = radius
    self.show_value = show_value
    self.text_color = text_color
    self.text_scale = text_scale
    self.text_thickness = text_thickness
    self.text_padding = text_padding
    self.color_lookup = _validate_keypoint_color_lookup(color_lookup)

annotate(scene: ImageType, key_points: KeyPoints) -> ImageType

Annotates the given scene with an arc, and optionally the angle in degrees, at every measurable joint of every skeleton.

Parameters:

Name Type Description Default
scene
ImageType

The image where the joint angles will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
key_points
KeyPoints

A collection of key points. Only the first two coordinate channels, x and y, determine angles and pixel positions.

required

Returns:

Type Description
ImageType

The annotated image, matching the type of scene (numpy.ndarray or PIL.Image.Image)

Raises:

Type Description
TypeError

If scene is not a numpy.ndarray or PIL.Image.Image.

ValueError

If a joint refers to a position outside the key points.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((200, 200, 3), dtype=np.uint8)
>>> key_points = sv.KeyPoints(
...     xy=np.array(
...         [[[100, 50], [100, 100], [150, 100]]],
...         dtype=np.float32,
...     )
... )
>>> from supervision.key_points.angles import JointAngle
>>> knee = JointAngle(name="knee", start=0, joint=1, end=2)
>>> annotator = sv.JointAngleAnnotator(angles=[knee])
>>> result = annotator.annotate(image.copy(), key_points)
Source code in src/supervision/key_points/annotators.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
    """Annotates the given scene with an arc, and optionally the angle in
    degrees, at every measurable joint of every skeleton.

    Args:
        scene: The image where the joint angles will be drawn. `ImageType` is a
            flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
        key_points: A collection of key points. Only the first two coordinate
            channels, x and y, determine angles and pixel positions.

    Returns:
        The annotated image, matching the type of `scene` (`numpy.ndarray`
            or `PIL.Image.Image`)

    Raises:
        TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`.
        ValueError: If a joint refers to a position outside the key points.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((200, 200, 3), dtype=np.uint8)
        >>> key_points = sv.KeyPoints(
        ...     xy=np.array(
        ...         [[[100, 50], [100, 100], [150, 100]]],
        ...         dtype=np.float32,
        ...     )
        ... )
        >>> from supervision.key_points.angles import JointAngle
        >>> knee = JointAngle(name="knee", start=0, joint=1, end=2)
        >>> annotator = sv.JointAngleAnnotator(angles=[knee])
        >>> result = annotator.annotate(image.copy(), key_points)

        ```
    """
    if len(key_points) == 0 or not self.angles:
        return scene

    values = joint_angles(key_points, self.angles)
    xy = key_points.xy[..., :2].astype(np.float64)
    measured = list(zip(*np.nonzero(np.isfinite(values))))
    # Resolve every color before the first draw, as VertexLabelAnnotator does,
    # so a lookup that raises leaves the caller's scene untouched.
    joint_colors = [
        self._resolve_joint_colors(
            key_points, int(skeleton_index), self.angles[angle_index].joint
        )
        for skeleton_index, angle_index in measured
    ]
    for (skeleton_index, angle_index), (color, text_color) in zip(
        measured, joint_colors
    ):
        angle = self.angles[angle_index]
        joint_xy = xy[skeleton_index, angle.joint]
        heading_start = self._heading(xy[skeleton_index, angle.start] - joint_xy)
        heading_end = self._heading(xy[skeleton_index, angle.end] - joint_xy)
        # The interior angle never exceeds 180 degrees, so the arc follows the
        # shorter way round from ray start to ray end. Both backends draw an arc
        # clockwise from the smaller to the larger angle in image coordinates.
        sweep = (heading_end - heading_start + 180.0) % 360.0 - 180.0
        start_angle, end_angle = sorted((heading_start, heading_start + sweep))
        # Both backends draw whole degrees, so a sub-degree arc would collapse
        # into a dot on the joint; such joints keep only their label.
        if end_angle - start_angle >= 1.0:
            _draw_antialiased(
                scene,
                color.as_bgr(),
                lambda image, draw_color: cv2.ellipse(
                    image,
                    (int(joint_xy[0]), int(joint_xy[1])),
                    (self.radius, self.radius),
                    0.0,
                    start_angle,
                    end_angle,
                    draw_color,
                    self.thickness,
                    cv2.LINE_AA,
                ),
            )
        if text_color is not None:
            self._draw_value(
                scene=scene,
                text=f"{values[skeleton_index, angle_index]:.0f}\N{DEGREE SIGN}",
                color=color,
                text_color=text_color,
                joint_xy=joint_xy,
                bisector=np.radians(heading_start + sweep / 2.0),
            )
    return scene

Comments