Skip to content

Annotators

Annotators accept detections and apply box or mask visualizations to the detections. Annotators have many available styles.

Pillow scenes

Annotators also accept a PIL.Image.Image as scene. They update it in place and change only the pixels they draw, so transparency and 16-bit depth of untouched pixels stay intact. For annotators that draw through NumPy, palette images (modes P and PA) use opaque slots unused by untouched pixels to add drawn colors to RGB palettes; RGBA palettes and colors without a free slot use the nearest opaque entry. A palette that is full and has no opaque entry raises ValueError on this drawing path. RichLabelAnnotator draws directly through Pillow and uses Pillow's native palette handling instead.

import supervision as sv

image = ...
detections = sv.Detections(...)

box_annotator = sv.BoxAnnotator()
annotated_frame = box_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

bounding-box-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

round_box_annotator = sv.RoundBoxAnnotator()
annotated_frame = round_box_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

round-box-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

corner_annotator = sv.BoxCornerAnnotator()
annotated_frame = corner_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

box-corner-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

circle_annotator = sv.CircleAnnotator()
annotated_frame = circle_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

circle-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

ellipse_annotator = sv.EllipseAnnotator()
annotated_frame = ellipse_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

ellipse-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

polygon_annotator = sv.PolygonAnnotator()
annotated_frame = polygon_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

polygon-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

color_annotator = sv.ColorAnnotator()
annotated_frame = color_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

box-mask-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

halo_annotator = sv.HaloAnnotator()
annotated_frame = halo_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

halo-annotator-example

import supervision as sv
from rfdetr.detr import RFDETRSegSmall

image = ...
model = RFDETRSegSmall()
# RF-DETR segmentation models return masks in `detections.mask`.
detections = model.predict(image[:, :, ::-1])

mask_annotator = sv.MaskAnnotator()
annotated_frame = mask_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

Note

MaskAnnotator expects detections.mask to contain instance segmentation masks aligned to the image passed to annotate. For dense masks, provide a boolean array of shape (N, H, W) where (H, W) matches the image height and width (it also accepts sv.CompactMask). If your model returns framework-specific results, convert them to sv.Detections first. RF-DETR's predict() already returns sv.Detections; for other models use sv.Detections.from_inference(...) or sv.Detections.from_ultralytics(...).

mask-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

dot_annotator = sv.DotAnnotator()
annotated_frame = dot_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

dot-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

triangle_annotator = sv.TriangleAnnotator()
annotated_frame = triangle_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

triangle-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

labels = [
    f"{class_name} {confidence:.2f}"
    for class_name, confidence in zip(
        detections["class_name"],
        detections.confidence,
    )
]

label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
annotated_frame = label_annotator.annotate(
    scene=image.copy(), detections=detections, labels=labels
)

label-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

labels = [
    f"{class_name} {confidence:.2f}"
    for class_name, confidence in zip(
        detections["class_name"],
        detections.confidence,
    )
]

rich_label_annotator = sv.RichLabelAnnotator(
    font_path="TTF_FONT_PATH",
    text_position=sv.Position.CENTER,
)
annotated_frame = rich_label_annotator.annotate(
    scene=image.copy(),
    detections=detections,
    labels=labels,
)

label-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

blur_annotator = sv.BlurAnnotator()
annotated_frame = blur_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

blur-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

pixelate_annotator = sv.PixelateAnnotator()
annotated_frame = pixelate_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

pixelate-annotator-example

<!-- === "Crop"

import supervision as sv

image = ...
detections = sv.Detections(...)

crop_annotator = sv.CropAnnotator()
annotated_frame = crop_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

crop-annotator-example

-->

Removed tracker wrapper

sv.ByteTrack was removed as of supervision-0.31.0. Use ByteTrackTracker from the external trackers package (pip install trackers) instead — its update method is update(), not update_with_detections().

import supervision as sv
from rfdetr import RFDETRMedium
from trackers import ByteTrackTracker

model = RFDETRMedium()

trace_annotator = sv.TraceAnnotator()

video_info = sv.VideoInfo.from_video_path(video_path="...")
frames_generator = sv.get_video_frames_generator(source_path="...")
tracker = ByteTrackTracker(
    track_activation_threshold=0.25, minimum_consecutive_frames=1
)

with sv.VideoSink(target_path="...", video_info=video_info) as sink:
    for frame in frames_generator:
        detections = model.predict(frame[:, :, ::-1])
        detections = tracker.update(detections)
        detections = detections[detections.tracker_id != -1]
        annotated_frame = trace_annotator.annotate(
            scene=frame.copy(),
            detections=detections,
        )
        sink.write_frame(frame=annotated_frame)

trace-annotator-example

import supervision as sv
from rfdetr import RFDETRMedium

model = RFDETRMedium()

heat_map_annotator = sv.HeatMapAnnotator()

video_info = sv.VideoInfo.from_video_path(video_path="...")
frames_generator = sv.get_video_frames_generator(source_path="...")

with sv.VideoSink(target_path="...", video_info=video_info) as sink:
    for frame in frames_generator:
        detections = model.predict(frame[:, :, ::-1])
        annotated_frame = heat_map_annotator.annotate(
            scene=frame.copy(),
            detections=detections,
        )
        sink.write_frame(frame=annotated_frame)

heat-map-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

percentage_bar_annotator = sv.PercentageBarAnnotator()
annotated_frame = percentage_bar_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

percentage-bar-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

icon_paths = ["<ICON_PATH>" for _ in detections]

icon_annotator = sv.IconAnnotator()
annotated_frame = icon_annotator.annotate(
    scene=image.copy(),
    detections=detections,
    icon_path=icon_paths,
)

icon-annotator-example

import supervision as sv

image = ...
detections = sv.Detections(...)

background_overlay_annotator = sv.BackgroundOverlayAnnotator()
annotated_frame = background_overlay_annotator.annotate(
    scene=image.copy(),
    detections=detections,
)

background-overlay-annotator-example

import supervision as sv

image = ...
detections_1 = sv.Detections(...)
detections_2 = sv.Detections(...)

comparison_annotator = sv.ComparisonAnnotator()
annotated_frame = comparison_annotator.annotate(
    scene=image.copy(),
    detections_1=detections_1,
    detections_2=detections_2,
)

comparison-annotator-example

Try Supervision Annotators on your own image

Visualize annotators on images with COCO classes such as people, vehicles, animals, household items.

supervision.annotators.core.BoxAnnotator

Bases: BaseAnnotator

A class for drawing bounding boxes on an image using provided detections.

Source code in src/supervision/annotators/core.py
class BoxAnnotator(BaseAnnotator):
    """A class for drawing bounding boxes on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the bounding box lines.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with bounding boxes based on the provided
        detections.

        Args:
            scene: The image where bounding boxes will be drawn. `ImageType`
                is a flexible type, accepting either `numpy.ndarray` or
                `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> box_annotator = sv.BoxAnnotator()
            >>> annotated_frame = box_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![bounding-box-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/bounding-box-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            cv2.rectangle(
                img=scene,
                pt1=(x1, y1),
                pt2=(x2, y2),
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the bounding box lines.

2
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the bounding box lines.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with bounding boxes based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> box_annotator = sv.BoxAnnotator()
>>> annotated_frame = box_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

bounding-box-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with bounding boxes based on the provided
    detections.

    Args:
        scene: The image where bounding boxes will be drawn. `ImageType`
            is a flexible type, accepting either `numpy.ndarray` or
            `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> box_annotator = sv.BoxAnnotator()
        >>> annotated_frame = box_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![bounding-box-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/bounding-box-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
        cv2.rectangle(
            img=scene,
            pt1=(x1, y1),
            pt2=(x2, y2),
            color=_color_for_canvas(color.as_bgr(), scene),
            thickness=self.thickness,
        )
    return scene

supervision.annotators.core.RoundBoxAnnotator

Bases: BaseAnnotator

A class for drawing bounding boxes with round edges on an image using provided detections.

Source code in src/supervision/annotators/core.py
class RoundBoxAnnotator(BaseAnnotator):
    """A class for drawing bounding boxes with round edges on an image using provided
    detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        roundness: float = 0.6,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the bounding box lines.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            roundness: Percent of roundness for edges of bounding box.
                Value must be float 0 < roundness <= 1.0
                By default roundness percent is calculated based on smaller side
                length (width or height).
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.color_lookup: ColorLookup = color_lookup
        if not 0 < roundness <= 1.0:
            raise ValueError("roundness attribute must be float between (0, 1.0]")
        self.roundness: float = roundness

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with bounding boxes with rounded edges based on the
        provided detections.

        Args:
            scene: The image where rounded bounding boxes will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> round_box_annotator = sv.RoundBoxAnnotator()
            >>> annotated_frame = round_box_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![round-box-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/round-box-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)

            radius = (
                int((x2 - x1) // 2 * self.roundness)
                if abs(x1 - x2) < abs(y1 - y2)
                else int((y2 - y1) // 2 * self.roundness)
            )

            circle_coordinates = [
                ((x1 + radius), (y1 + radius)),
                ((x2 - radius), (y1 + radius)),
                ((x2 - radius), (y2 - radius)),
                ((x1 + radius), (y2 - radius)),
            ]

            line_coordinates = [
                ((x1 + radius, y1), (x2 - radius, y1)),
                ((x2, y1 + radius), (x2, y2 - radius)),
                ((x1 + radius, y2), (x2 - radius, y2)),
                ((x1, y1 + radius), (x1, y2 - radius)),
            ]

            start_angles = (180, 270, 0, 90)
            end_angles = (270, 360, 90, 180)

            for center_coordinates, line, start_angle, end_angle in zip(
                circle_coordinates, line_coordinates, start_angles, end_angles
            ):
                cv2.ellipse(
                    img=scene,
                    center=center_coordinates,
                    axes=(radius, radius),
                    angle=0,
                    startAngle=start_angle,
                    endAngle=end_angle,
                    color=_color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )

                cv2.line(
                    img=scene,
                    pt1=line[0],
                    pt2=line[1],
                    color=_color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )

        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS, roundness: float = 0.6)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the bounding box lines.

2
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
roundness
float

Percent of roundness for edges of bounding box. Value must be float 0 < roundness <= 1.0 By default roundness percent is calculated based on smaller side length (width or height).

0.6
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    roundness: float = 0.6,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the bounding box lines.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        roundness: Percent of roundness for edges of bounding box.
            Value must be float 0 < roundness <= 1.0
            By default roundness percent is calculated based on smaller side
            length (width or height).
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.color_lookup: ColorLookup = color_lookup
    if not 0 < roundness <= 1.0:
        raise ValueError("roundness attribute must be float between (0, 1.0]")
    self.roundness: float = roundness

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with bounding boxes with rounded edges based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> round_box_annotator = sv.RoundBoxAnnotator()
>>> annotated_frame = round_box_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

round-box-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with bounding boxes with rounded edges based on the
    provided detections.

    Args:
        scene: The image where rounded bounding boxes will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> round_box_annotator = sv.RoundBoxAnnotator()
        >>> annotated_frame = round_box_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![round-box-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/round-box-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)

        radius = (
            int((x2 - x1) // 2 * self.roundness)
            if abs(x1 - x2) < abs(y1 - y2)
            else int((y2 - y1) // 2 * self.roundness)
        )

        circle_coordinates = [
            ((x1 + radius), (y1 + radius)),
            ((x2 - radius), (y1 + radius)),
            ((x2 - radius), (y2 - radius)),
            ((x1 + radius), (y2 - radius)),
        ]

        line_coordinates = [
            ((x1 + radius, y1), (x2 - radius, y1)),
            ((x2, y1 + radius), (x2, y2 - radius)),
            ((x1 + radius, y2), (x2 - radius, y2)),
            ((x1, y1 + radius), (x1, y2 - radius)),
        ]

        start_angles = (180, 270, 0, 90)
        end_angles = (270, 360, 90, 180)

        for center_coordinates, line, start_angle, end_angle in zip(
            circle_coordinates, line_coordinates, start_angles, end_angles
        ):
            cv2.ellipse(
                img=scene,
                center=center_coordinates,
                axes=(radius, radius),
                angle=0,
                startAngle=start_angle,
                endAngle=end_angle,
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )

            cv2.line(
                img=scene,
                pt1=line[0],
                pt2=line[1],
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )

    return scene

supervision.annotators.core.BoxCornerAnnotator

Bases: BaseAnnotator

A class for drawing box corners on an image using provided detections.

Source code in src/supervision/annotators/core.py
class BoxCornerAnnotator(BaseAnnotator):
    """A class for drawing box corners on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 4,
        corner_length: int = 15,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the corner lines.
            corner_length: Length of each corner line.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.corner_length: int = corner_length
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with box corners based on the provided detections.

        Args:
            scene: The image where box corners will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> corner_annotator = sv.BoxCornerAnnotator()
            >>> annotated_frame = corner_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![box-corner-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/box-corner-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)]

            for x, y in corners:
                x_end = x + self.corner_length if x == x1 else x - self.corner_length
                cv2.line(
                    scene,
                    (x, y),
                    (x_end, y),
                    _color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )

                y_end = y + self.corner_length if y == y1 else y - self.corner_length
                cv2.line(
                    scene,
                    (x, y),
                    (x, y_end),
                    _color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 4, corner_length: int = 15, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the corner lines.

4
corner_length
int

Length of each corner line.

15
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 4,
    corner_length: int = 15,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the corner lines.
        corner_length: Length of each corner line.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.corner_length: int = corner_length
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with box corners based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> corner_annotator = sv.BoxCornerAnnotator()
>>> annotated_frame = corner_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

box-corner-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with box corners based on the provided detections.

    Args:
        scene: The image where box corners will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> corner_annotator = sv.BoxCornerAnnotator()
        >>> annotated_frame = corner_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![box-corner-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/box-corner-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
        corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)]

        for x, y in corners:
            x_end = x + self.corner_length if x == x1 else x - self.corner_length
            cv2.line(
                scene,
                (x, y),
                (x_end, y),
                _color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )

            y_end = y + self.corner_length if y == y1 else y - self.corner_length
            cv2.line(
                scene,
                (x, y),
                (x, y_end),
                _color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )
    return scene

supervision.annotators.core.OrientedBoxAnnotator

Bases: BaseAnnotator

A class for drawing oriented bounding boxes on an image using provided detections.

Source code in src/supervision/annotators/core.py
class OrientedBoxAnnotator(BaseAnnotator):
    """A class for drawing oriented bounding boxes on an image using provided
    detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the bounding box lines.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with oriented bounding boxes based on the provided
        detections.

        Args:
            scene: The image where bounding boxes will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from ultralytics import YOLO

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = YOLO("yolov8n-obb.pt")

            result = model(image)[0]
            detections = sv.Detections.from_ultralytics(result)

            oriented_box_annotator = sv.OrientedBoxAnnotator()
            annotated_frame = oriented_box_annotator.annotate(
                scene=image.copy(),
                detections=detections
            )
            ```

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> from supervision.config import ORIENTED_BOX_COORDINATES
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> obb = np.array([[[20, 20], [80, 20], [80, 80], [20, 80]]])
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0]),
            ...     data={ORIENTED_BOX_COORDINATES: obb},
            ... )
            >>> oriented_box_annotator = sv.OrientedBoxAnnotator()
            >>> annotated_frame = oriented_box_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if detections.data is None or ORIENTED_BOX_COORDINATES not in detections.data:
            return scene
        obb_boxes = np.array(detections.data[ORIENTED_BOX_COORDINATES]).astype(int)

        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            obb = obb_boxes[detection_idx]

            cv2.drawContours(
                scene,
                [obb],
                0,
                _color_for_canvas(color.as_bgr(), scene),
                self.thickness,
            )

        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the bounding box lines.

2
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the bounding box lines.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with oriented bounding boxes based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

from supervision import _cv2 as cv2
import supervision as sv
from ultralytics import YOLO

image = cv2.imread("<SOURCE_IMAGE_PATH>")
model = YOLO("yolov8n-obb.pt")

result = model(image)[0]
detections = sv.Detections.from_ultralytics(result)

oriented_box_annotator = sv.OrientedBoxAnnotator()
annotated_frame = oriented_box_annotator.annotate(
    scene=image.copy(),
    detections=detections
)
>>> import numpy as np
>>> import supervision as sv
>>> from supervision.config import ORIENTED_BOX_COORDINATES
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> obb = np.array([[[20, 20], [80, 20], [80, 80], [20, 80]]])
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0]),
...     data={ORIENTED_BOX_COORDINATES: obb},
... )
>>> oriented_box_annotator = sv.OrientedBoxAnnotator()
>>> annotated_frame = oriented_box_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )
Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with oriented bounding boxes based on the provided
    detections.

    Args:
        scene: The image where bounding boxes will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```python
        from supervision import _cv2 as cv2
        import supervision as sv
        from ultralytics import YOLO

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        model = YOLO("yolov8n-obb.pt")

        result = model(image)[0]
        detections = sv.Detections.from_ultralytics(result)

        oriented_box_annotator = sv.OrientedBoxAnnotator()
        annotated_frame = oriented_box_annotator.annotate(
            scene=image.copy(),
            detections=detections
        )
        ```

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from supervision.config import ORIENTED_BOX_COORDINATES
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> obb = np.array([[[20, 20], [80, 20], [80, 80], [20, 80]]])
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0]),
        ...     data={ORIENTED_BOX_COORDINATES: obb},
        ... )
        >>> oriented_box_annotator = sv.OrientedBoxAnnotator()
        >>> annotated_frame = oriented_box_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if detections.data is None or ORIENTED_BOX_COORDINATES not in detections.data:
        return scene
    obb_boxes = np.array(detections.data[ORIENTED_BOX_COORDINATES]).astype(int)

    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        obb = obb_boxes[detection_idx]

        cv2.drawContours(
            scene,
            [obb],
            0,
            _color_for_canvas(color.as_bgr(), scene),
            self.thickness,
        )

    return scene

supervision.annotators.core.ColorAnnotator

Bases: BaseAnnotator

A class for drawing box masks on an image using provided detections.

Source code in src/supervision/annotators/core.py
class ColorAnnotator(BaseAnnotator):
    """A class for drawing box masks on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        opacity: float = 0.5,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.color_lookup: ColorLookup = color_lookup
        self.opacity = opacity

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with box masks based on the provided detections.

        Args:
            scene: The image where bounding boxes will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> color_annotator = sv.ColorAnnotator()
            >>> annotated_frame = color_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![box-mask-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/box-mask-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if scene.ndim == 3 and scene.shape[2] == 4:
            # Boxes are drawn on a separate color layer and coverage mask so the
            # scene's hidden colors under transparent pixels cannot tint them.
            box_colors = np.zeros((*scene.shape[:2], 3), dtype=np.uint8)
            coverage = np.zeros(scene.shape[:2], dtype=np.uint8)
            for detection_idx, color in _iter_resolved_colors(
                detections, self.color, self.color_lookup, custom_color_lookup
            ):
                x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
                cv2.rectangle(box_colors, (x1, y1), (x2, y2), color.as_bgr(), -1)
                cv2.rectangle(coverage, (x1, y1), (x2, y2), 255, -1)
            _composite_coverage_over_bgra(scene, box_colors, coverage, self.opacity)
            return scene

        resolved = list(
            _iter_resolved_colors(
                detections, self.color, self.color_lookup, custom_color_lookup
            )
        )
        if not resolved:
            return scene

        height, width = scene.shape[:2]
        boxes_to_draw: list[tuple[int, int, int, int, Color]] = []
        rx1, ry1 = width, height
        rx2, ry2 = -1, -1
        for detection_idx, color in resolved:
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            bx1, bx2 = (int(x1), int(x2)) if x1 <= x2 else (int(x2), int(x1))
            by1, by2 = (int(y1), int(y2)) if y1 <= y2 else (int(y2), int(y1))
            cx1, cy1 = max(bx1, 0), max(by1, 0)
            cx2, cy2 = min(bx2, width - 1), min(by2, height - 1)
            if cx1 <= cx2 and cy1 <= cy2:
                boxes_to_draw.append((cx1, cy1, cx2, cy2, color))
                if cx1 < rx1:
                    rx1 = cx1
                if cy1 < ry1:
                    ry1 = cy1
                if cx2 > rx2:
                    rx2 = cx2
                if cy2 > ry2:
                    ry2 = cy2

        if not boxes_to_draw:
            return scene

        # Copy and blend only the bounding ROI of drawn boxes instead of the full frame.
        scene_roi = scene[ry1 : ry2 + 1, rx1 : rx2 + 1]
        roi_with_boxes = scene_roi.copy()
        for bx1, by1, bx2, by2, color in boxes_to_draw:
            cv2.rectangle(
                img=roi_with_boxes,
                pt1=(bx1 - rx1, by1 - ry1),
                pt2=(bx2 - rx1, by2 - ry1),
                color=_color_for_canvas(color.as_bgr(), roi_with_boxes),
                thickness=-1,
            )

        blended_roi = cv2.addWeighted(
            roi_with_boxes, self.opacity, scene_roi, 1 - self.opacity, gamma=0
        )
        scene_roi[:] = blended_roi.reshape(scene_roi.shape)
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, opacity: float = 0.5, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
opacity
float

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

0.5
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    opacity: float = 0.5,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.color_lookup: ColorLookup = color_lookup
    self.opacity = opacity

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with box masks based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> color_annotator = sv.ColorAnnotator()
>>> annotated_frame = color_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

box-mask-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with box masks based on the provided detections.

    Args:
        scene: The image where bounding boxes will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> color_annotator = sv.ColorAnnotator()
        >>> annotated_frame = color_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![box-mask-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/box-mask-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if scene.ndim == 3 and scene.shape[2] == 4:
        # Boxes are drawn on a separate color layer and coverage mask so the
        # scene's hidden colors under transparent pixels cannot tint them.
        box_colors = np.zeros((*scene.shape[:2], 3), dtype=np.uint8)
        coverage = np.zeros(scene.shape[:2], dtype=np.uint8)
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            cv2.rectangle(box_colors, (x1, y1), (x2, y2), color.as_bgr(), -1)
            cv2.rectangle(coverage, (x1, y1), (x2, y2), 255, -1)
        _composite_coverage_over_bgra(scene, box_colors, coverage, self.opacity)
        return scene

    resolved = list(
        _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        )
    )
    if not resolved:
        return scene

    height, width = scene.shape[:2]
    boxes_to_draw: list[tuple[int, int, int, int, Color]] = []
    rx1, ry1 = width, height
    rx2, ry2 = -1, -1
    for detection_idx, color in resolved:
        x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
        bx1, bx2 = (int(x1), int(x2)) if x1 <= x2 else (int(x2), int(x1))
        by1, by2 = (int(y1), int(y2)) if y1 <= y2 else (int(y2), int(y1))
        cx1, cy1 = max(bx1, 0), max(by1, 0)
        cx2, cy2 = min(bx2, width - 1), min(by2, height - 1)
        if cx1 <= cx2 and cy1 <= cy2:
            boxes_to_draw.append((cx1, cy1, cx2, cy2, color))
            if cx1 < rx1:
                rx1 = cx1
            if cy1 < ry1:
                ry1 = cy1
            if cx2 > rx2:
                rx2 = cx2
            if cy2 > ry2:
                ry2 = cy2

    if not boxes_to_draw:
        return scene

    # Copy and blend only the bounding ROI of drawn boxes instead of the full frame.
    scene_roi = scene[ry1 : ry2 + 1, rx1 : rx2 + 1]
    roi_with_boxes = scene_roi.copy()
    for bx1, by1, bx2, by2, color in boxes_to_draw:
        cv2.rectangle(
            img=roi_with_boxes,
            pt1=(bx1 - rx1, by1 - ry1),
            pt2=(bx2 - rx1, by2 - ry1),
            color=_color_for_canvas(color.as_bgr(), roi_with_boxes),
            thickness=-1,
        )

    blended_roi = cv2.addWeighted(
        roi_with_boxes, self.opacity, scene_roi, 1 - self.opacity, gamma=0
    )
    scene_roi[:] = blended_roi.reshape(scene_roi.shape)
    return scene

supervision.annotators.core.CircleAnnotator

Bases: BaseAnnotator

A class for drawing circle on an image using provided detections.

Source code in src/supervision/annotators/core.py
class CircleAnnotator(BaseAnnotator):
    """A class for drawing circle on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the circle line.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with circles based on the provided detections.

        Args:
            scene: The image where box corners will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> circle_annotator = sv.CircleAnnotator()
            >>> annotated_frame = circle_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```


        ![circle-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/circle-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            center = ((x1 + x2) // 2, (y1 + y2) // 2)
            distance = sqrt((x1 - center[0]) ** 2 + (y1 - center[1]) ** 2)
            cv2.circle(
                img=scene,
                center=center,
                radius=int(distance),
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )

        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the circle line.

2
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the circle line.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with circles based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> circle_annotator = sv.CircleAnnotator()
>>> annotated_frame = circle_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

circle-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with circles based on the provided detections.

    Args:
        scene: The image where box corners will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> circle_annotator = sv.CircleAnnotator()
        >>> annotated_frame = circle_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```


    ![circle-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/circle-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
        center = ((x1 + x2) // 2, (y1 + y2) // 2)
        distance = sqrt((x1 - center[0]) ** 2 + (y1 - center[1]) ** 2)
        cv2.circle(
            img=scene,
            center=center,
            radius=int(distance),
            color=_color_for_canvas(color.as_bgr(), scene),
            thickness=self.thickness,
        )

    return scene

supervision.annotators.core.DotAnnotator

Bases: BaseAnnotator

A class for drawing dots on an image at specific coordinates based on provided detections.

Source code in src/supervision/annotators/core.py
class DotAnnotator(BaseAnnotator):
    """A class for drawing dots on an image at specific coordinates based on provided
    detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        radius: int = 4,
        position: Position = Position.CENTER,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        outline_thickness: int = 0,
        outline_color: Color | ColorPalette | str = Color.BLACK,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            radius: Radius of the drawn dots.
            position: The anchor position for placing the dot.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            outline_thickness: Thickness of the outline of the dot.
            outline_color: The color or color palette to
                use for outline. It is activated by setting outline_thickness to a value
                greater than 0.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.radius: int = radius
        self.position: Position = position
        self.color_lookup: ColorLookup = color_lookup
        self.outline_thickness = outline_thickness
        self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color)

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with dots based on the provided detections.

        Args:
            scene: The image where dots will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> dot_annotator = sv.DotAnnotator()
            >>> annotated_frame = dot_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![dot-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/dot-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        xy = detections.get_anchors_coordinates(anchor=self.position)
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            center = (int(xy[detection_idx, 0]), int(xy[detection_idx, 1]))

            cv2.circle(
                scene, center, self.radius, _color_for_canvas(color.as_bgr(), scene), -1
            )
            if self.outline_thickness:
                outline_color = _resolve_annotator_color(
                    color=self.outline_color,
                    detections=detections,
                    detection_idx=detection_idx,
                    color_lookup=self.color_lookup,
                    custom_color_lookup=custom_color_lookup,
                )
                cv2.circle(
                    scene,
                    center,
                    self.radius,
                    _color_for_canvas(outline_color.as_bgr(), scene),
                    self.outline_thickness,
                )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, radius: int = 4, position: Position = Position.CENTER, color_lookup: ColorLookup = ColorLookup.CLASS, outline_thickness: int = 0, outline_color: Color | ColorPalette | str = Color.BLACK)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
radius
int

Radius of the drawn dots.

4
position
Position

The anchor position for placing the dot.

CENTER
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
outline_thickness
int

Thickness of the outline of the dot.

0
outline_color
Color | ColorPalette | str

The color or color palette to use for outline. It is activated by setting outline_thickness to a value greater than 0.

BLACK
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    radius: int = 4,
    position: Position = Position.CENTER,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    outline_thickness: int = 0,
    outline_color: Color | ColorPalette | str = Color.BLACK,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        radius: Radius of the drawn dots.
        position: The anchor position for placing the dot.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        outline_thickness: Thickness of the outline of the dot.
        outline_color: The color or color palette to
            use for outline. It is activated by setting outline_thickness to a value
            greater than 0.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.radius: int = radius
    self.position: Position = position
    self.color_lookup: ColorLookup = color_lookup
    self.outline_thickness = outline_thickness
    self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color)

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with dots based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> dot_annotator = sv.DotAnnotator()
>>> annotated_frame = dot_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

dot-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with dots based on the provided detections.

    Args:
        scene: The image where dots will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> dot_annotator = sv.DotAnnotator()
        >>> annotated_frame = dot_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![dot-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/dot-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    xy = detections.get_anchors_coordinates(anchor=self.position)
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        center = (int(xy[detection_idx, 0]), int(xy[detection_idx, 1]))

        cv2.circle(
            scene, center, self.radius, _color_for_canvas(color.as_bgr(), scene), -1
        )
        if self.outline_thickness:
            outline_color = _resolve_annotator_color(
                color=self.outline_color,
                detections=detections,
                detection_idx=detection_idx,
                color_lookup=self.color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            cv2.circle(
                scene,
                center,
                self.radius,
                _color_for_canvas(outline_color.as_bgr(), scene),
                self.outline_thickness,
            )
    return scene

supervision.annotators.core.TriangleAnnotator

Bases: BaseAnnotator

A class for drawing triangle markers on an image at specific coordinates based on provided detections.

Source code in src/supervision/annotators/core.py
class TriangleAnnotator(BaseAnnotator):
    """A class for drawing triangle markers on an image at specific coordinates based on
    provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        base: int = 10,
        height: int = 10,
        position: Position = Position.TOP_CENTER,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        outline_thickness: int = 0,
        outline_color: Color | ColorPalette | str = Color.BLACK,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            base: The base width of the triangle.
            height: The height of the triangle.
            position: The anchor position for placing the triangle.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            outline_thickness: Thickness of the outline of the triangle.
            outline_color: The color or color palette to
                use for outline. It is activated by setting outline_thickness to a value
                greater than 0.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.base: int = base
        self.height: int = height
        self.position: Position = position
        self.color_lookup: ColorLookup = color_lookup
        self.outline_thickness: int = outline_thickness
        self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color)

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with triangles based on the provided detections.

        Args:
            scene: The image where triangles will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> triangle_annotator = sv.TriangleAnnotator()
            >>> annotated_frame = triangle_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![triangle-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/triangle-annotator-example.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        xy = detections.get_anchors_coordinates(anchor=self.position)
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            tip_x, tip_y = int(xy[detection_idx, 0]), int(xy[detection_idx, 1])
            vertices = np.array(
                [
                    [tip_x - self.base // 2, tip_y - self.height],
                    [tip_x + self.base // 2, tip_y - self.height],
                    [tip_x, tip_y],
                ],
                np.int32,
            )

            cv2.fillPoly(scene, [vertices], _color_for_canvas(color.as_bgr(), scene))
            if self.outline_thickness:
                outline_color = _resolve_annotator_color(
                    color=self.outline_color,
                    detections=detections,
                    detection_idx=detection_idx,
                    color_lookup=self.color_lookup,
                    custom_color_lookup=custom_color_lookup,
                )
                cv2.polylines(
                    scene,
                    [vertices],
                    True,
                    _color_for_canvas(outline_color.as_bgr(), scene),
                    thickness=self.outline_thickness,
                )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, base: int = 10, height: int = 10, position: Position = Position.TOP_CENTER, color_lookup: ColorLookup = ColorLookup.CLASS, outline_thickness: int = 0, outline_color: Color | ColorPalette | str = Color.BLACK)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
base
int

The base width of the triangle.

10
height
int

The height of the triangle.

10
position
Position

The anchor position for placing the triangle.

TOP_CENTER
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
outline_thickness
int

Thickness of the outline of the triangle.

0
outline_color
Color | ColorPalette | str

The color or color palette to use for outline. It is activated by setting outline_thickness to a value greater than 0.

BLACK
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    base: int = 10,
    height: int = 10,
    position: Position = Position.TOP_CENTER,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    outline_thickness: int = 0,
    outline_color: Color | ColorPalette | str = Color.BLACK,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        base: The base width of the triangle.
        height: The height of the triangle.
        position: The anchor position for placing the triangle.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        outline_thickness: Thickness of the outline of the triangle.
        outline_color: The color or color palette to
            use for outline. It is activated by setting outline_thickness to a value
            greater than 0.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.base: int = base
    self.height: int = height
    self.position: Position = position
    self.color_lookup: ColorLookup = color_lookup
    self.outline_thickness: int = outline_thickness
    self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color)

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with triangles based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> triangle_annotator = sv.TriangleAnnotator()
>>> annotated_frame = triangle_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

triangle-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with triangles based on the provided detections.

    Args:
        scene: The image where triangles will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> triangle_annotator = sv.TriangleAnnotator()
        >>> annotated_frame = triangle_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![triangle-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/triangle-annotator-example.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    xy = detections.get_anchors_coordinates(anchor=self.position)
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        tip_x, tip_y = int(xy[detection_idx, 0]), int(xy[detection_idx, 1])
        vertices = np.array(
            [
                [tip_x - self.base // 2, tip_y - self.height],
                [tip_x + self.base // 2, tip_y - self.height],
                [tip_x, tip_y],
            ],
            np.int32,
        )

        cv2.fillPoly(scene, [vertices], _color_for_canvas(color.as_bgr(), scene))
        if self.outline_thickness:
            outline_color = _resolve_annotator_color(
                color=self.outline_color,
                detections=detections,
                detection_idx=detection_idx,
                color_lookup=self.color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            cv2.polylines(
                scene,
                [vertices],
                True,
                _color_for_canvas(outline_color.as_bgr(), scene),
                thickness=self.outline_thickness,
            )
    return scene

supervision.annotators.core.EllipseAnnotator

Bases: BaseAnnotator

A class for drawing ellipses on an image using provided detections.

Source code in src/supervision/annotators/core.py
class EllipseAnnotator(BaseAnnotator):
    """A class for drawing ellipses on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        start_angle: int = -45,
        end_angle: int = 235,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the ellipse lines.
            start_angle: Starting angle of the ellipse.
            end_angle: Ending angle of the ellipse.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.start_angle: int = start_angle
        self.end_angle: int = end_angle
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with ellipses based on the provided detections.

        Args:
            scene: The image where ellipses will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> ellipse_annotator = sv.EllipseAnnotator()
            >>> annotated_frame = ellipse_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![ellipse-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/ellipse-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        for detection_idx, color in _iter_resolved_colors(
            detections, self.color, self.color_lookup, custom_color_lookup
        ):
            x1, _y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
            center = (int((x1 + x2) / 2), y2)
            width = x2 - x1
            cv2.ellipse(
                scene,
                center=center,
                axes=(int(width), int(0.35 * width)),
                angle=0.0,
                startAngle=self.start_angle,
                endAngle=self.end_angle,
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
                lineType=cv2.LINE_4,
            )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, start_angle: int = -45, end_angle: int = 235, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the ellipse lines.

2
start_angle
int

Starting angle of the ellipse.

-45
end_angle
int

Ending angle of the ellipse.

235
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    start_angle: int = -45,
    end_angle: int = 235,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the ellipse lines.
        start_angle: Starting angle of the ellipse.
        end_angle: Ending angle of the ellipse.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.start_angle: int = start_angle
    self.end_angle: int = end_angle
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with ellipses based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> ellipse_annotator = sv.EllipseAnnotator()
>>> annotated_frame = ellipse_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

ellipse-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with ellipses based on the provided detections.

    Args:
        scene: The image where ellipses will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> ellipse_annotator = sv.EllipseAnnotator()
        >>> annotated_frame = ellipse_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![ellipse-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/ellipse-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    for detection_idx, color in _iter_resolved_colors(
        detections, self.color, self.color_lookup, custom_color_lookup
    ):
        x1, _y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
        center = (int((x1 + x2) / 2), y2)
        width = x2 - x1
        cv2.ellipse(
            scene,
            center=center,
            axes=(int(width), int(0.35 * width)),
            angle=0.0,
            startAngle=self.start_angle,
            endAngle=self.end_angle,
            color=_color_for_canvas(color.as_bgr(), scene),
            thickness=self.thickness,
            lineType=cv2.LINE_4,
        )
    return scene

supervision.annotators.core.HaloAnnotator

Bases: BaseAnnotator

A class for drawing Halos on an image using provided detections.

Warning

This annotator uses :class:~supervision.detection.core.Detections.mask.

Source code in src/supervision/annotators/core.py
class HaloAnnotator(BaseAnnotator):
    """A class for drawing Halos on an image using provided detections.

    !!! warning

    This annotator uses
    :class:`~supervision.detection.core.Detections`.mask.
    """

    requires_mask = True

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        opacity: float = 0.8,
        kernel_size: int = 40,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            kernel_size: The size of the average pooling kernel used for creating
                the halo.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.opacity = opacity
        self.color_lookup: ColorLookup = color_lookup
        self.kernel_size: int = kernel_size

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with halos based on the provided detections.

        Args:
            scene: The image where the halo effect will be applied.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
                or `(H, W, 1)`; halos are drawn in the first (blue) channel of
                their color, as OpenCV draws boxes and polygons.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     mask=np.zeros((1, 100, 100), dtype=bool),
            ...     class_id=np.array([0])
            ... )
            >>> halo_annotator = sv.HaloAnnotator()
            >>> annotated_frame = halo_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![halo-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/halo-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if detections.mask is None:
            return scene
        colored_mask = np.zeros_like(scene, dtype=np.uint8)
        fmask = _paint_masks_by_area(
            colored_mask,
            detections,
            self.color,
            self.color_lookup if custom_color_lookup is None else custom_color_lookup,
            collect_union=True,
        )
        assert fmask is not None  # collect_union=True always returns an array

        # OpenCV drops a singleton channel axis; restore the scene's layout.
        colored_mask = cv2.blur(
            colored_mask, (self.kernel_size, self.kernel_size)
        ).reshape(scene.shape)
        colored_mask[fmask] = 0
        if colored_mask.ndim == 2 or colored_mask.shape[2] == 1:
            gray = colored_mask.reshape(scene.shape[:2])
        else:
            gray = cv2.cvtColor(colored_mask, cv2.COLOR_BGR2GRAY)
        gray_max = gray.max()
        if gray_max == 0:
            # no halo to draw (e.g. empty masks); leave the scene untouched
            return scene
        # Blend in horizontal row strips to avoid allocating full-frame float64
        # 3-channel temporaries while preserving exact arithmetic and skipping
        # rows with zero halo intensity.
        is_bgra = scene.ndim == 3 and scene.shape[2] == 4
        strip_rows = 64
        height = scene.shape[0]
        for start in range(0, height, strip_rows):
            stop = min(start + strip_rows, height)
            gray_strip = gray[start:stop]
            if not gray_strip.any():
                continue
            # Retain the original operation order before uint8 truncation.
            alpha = self.opacity * gray_strip / gray_max
            alpha_mask = alpha if scene.ndim == 2 else alpha[:, :, np.newaxis]
            scene_strip = scene[start:stop]
            color_strip = colored_mask[start:stop]
            blended_strip = np.clip(
                scene_strip.astype(np.float32) * (1 - alpha_mask)
                + color_strip.astype(np.float32) * alpha_mask,
                0,
                255,
            ).astype(np.uint8)
            if is_bgra:
                translucent = scene_strip[..., 3] < 255
                if translucent.any():
                    composited = _composite_over_bgra(
                        scene_strip, color_strip[..., :3], alpha[..., np.newaxis]
                    )
                    blended_strip[translucent] = composited[translucent]
                blended_strip[..., 3][~translucent] = 255
            scene[start:stop] = blended_strip
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, opacity: float = 0.8, kernel_size: int = 40, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
opacity
float

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

0.8
kernel_size
int

The size of the average pooling kernel used for creating the halo.

40
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    opacity: float = 0.8,
    kernel_size: int = 40,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        kernel_size: The size of the average pooling kernel used for creating
            the halo.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.opacity = opacity
    self.color_lookup: ColorLookup = color_lookup
    self.kernel_size: int = kernel_size

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with halos based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

The image where the halo effect will be applied. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale arrays may have shape (H, W) or (H, W, 1); halos are drawn in the first (blue) channel of their color, as OpenCV draws boxes and polygons.

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     mask=np.zeros((1, 100, 100), dtype=bool),
...     class_id=np.array([0])
... )
>>> halo_annotator = sv.HaloAnnotator()
>>> annotated_frame = halo_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

halo-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with halos based on the provided detections.

    Args:
        scene: The image where the halo effect will be applied.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
            or `(H, W, 1)`; halos are drawn in the first (blue) channel of
            their color, as OpenCV draws boxes and polygons.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     mask=np.zeros((1, 100, 100), dtype=bool),
        ...     class_id=np.array([0])
        ... )
        >>> halo_annotator = sv.HaloAnnotator()
        >>> annotated_frame = halo_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![halo-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/halo-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if detections.mask is None:
        return scene
    colored_mask = np.zeros_like(scene, dtype=np.uint8)
    fmask = _paint_masks_by_area(
        colored_mask,
        detections,
        self.color,
        self.color_lookup if custom_color_lookup is None else custom_color_lookup,
        collect_union=True,
    )
    assert fmask is not None  # collect_union=True always returns an array

    # OpenCV drops a singleton channel axis; restore the scene's layout.
    colored_mask = cv2.blur(
        colored_mask, (self.kernel_size, self.kernel_size)
    ).reshape(scene.shape)
    colored_mask[fmask] = 0
    if colored_mask.ndim == 2 or colored_mask.shape[2] == 1:
        gray = colored_mask.reshape(scene.shape[:2])
    else:
        gray = cv2.cvtColor(colored_mask, cv2.COLOR_BGR2GRAY)
    gray_max = gray.max()
    if gray_max == 0:
        # no halo to draw (e.g. empty masks); leave the scene untouched
        return scene
    # Blend in horizontal row strips to avoid allocating full-frame float64
    # 3-channel temporaries while preserving exact arithmetic and skipping
    # rows with zero halo intensity.
    is_bgra = scene.ndim == 3 and scene.shape[2] == 4
    strip_rows = 64
    height = scene.shape[0]
    for start in range(0, height, strip_rows):
        stop = min(start + strip_rows, height)
        gray_strip = gray[start:stop]
        if not gray_strip.any():
            continue
        # Retain the original operation order before uint8 truncation.
        alpha = self.opacity * gray_strip / gray_max
        alpha_mask = alpha if scene.ndim == 2 else alpha[:, :, np.newaxis]
        scene_strip = scene[start:stop]
        color_strip = colored_mask[start:stop]
        blended_strip = np.clip(
            scene_strip.astype(np.float32) * (1 - alpha_mask)
            + color_strip.astype(np.float32) * alpha_mask,
            0,
            255,
        ).astype(np.uint8)
        if is_bgra:
            translucent = scene_strip[..., 3] < 255
            if translucent.any():
                composited = _composite_over_bgra(
                    scene_strip, color_strip[..., :3], alpha[..., np.newaxis]
                )
                blended_strip[translucent] = composited[translucent]
            blended_strip[..., 3][~translucent] = 255
        scene[start:stop] = blended_strip
    return scene

supervision.annotators.core.PercentageBarAnnotator

Bases: BaseAnnotator

A class for drawing percentage bars on an image using provided detections.

Source code in src/supervision/annotators/core.py
class PercentageBarAnnotator(BaseAnnotator):
    """A class for drawing percentage bars on an image using provided detections."""

    def __init__(
        self,
        height: int = 16,
        width: int = 80,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        border_color: Color | str = Color.BLACK,
        position: Position = Position.TOP_CENTER,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        border_thickness: int | None = None,
    ):
        """
        Args:
            height: The height in pixels of the percentage bar.
            width: The width in pixels of the percentage bar.
            color: The color or color palette to use for
                annotating detections.
            border_color: The color of the border lines.
            position: The anchor position of drawing the percentage bar.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            border_thickness: The thickness of the border lines.
        """
        self.height: int = height
        self.width: int = width
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.border_color = cast(Color, _normalize_color_input(border_color))
        self.position: Position = position
        self.color_lookup: ColorLookup = color_lookup

        self.border_thickness = (
            border_thickness
            if border_thickness is not None
            else int(0.15 * self.height)
        )

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
        custom_values: npt.NDArray[np.float64] | None = None,
    ) -> ImageType:
        """Annotates the given scene with percentage bars based on the provided
        detections. The percentage bars visually represent the confidence or custom
        values associated with each detection.

        Args:
            scene: The image where percentage bars will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.
            custom_values: Custom values array to use instead
                of the default detection confidences. This array should have the
                same length as the number of detections and contain a value between
                0 and 1 (inclusive) for each detection, representing the percentage
                to be displayed.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     confidence=np.array([0.9]),
            ...     class_id=np.array([0])
            ... )
            >>> percentage_bar_annotator = sv.PercentageBarAnnotator()
            >>> annotated_frame = percentage_bar_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![percentage-bar-example](https://media.roboflow.com/
        supervision-annotator-examples/percentage-bar-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        self._validate_custom_values(custom_values=custom_values, detections=detections)

        anchors = detections.get_anchors_coordinates(anchor=self.position)
        for detection_idx in range(len(detections)):
            anchor = anchors[detection_idx]
            border_coordinates = self.calculate_border_coordinates(
                anchor_xy=(int(anchor[0]), int(anchor[1])),
                border_wh=(self.width, self.height),
                position=self.position,
            )
            border_width = border_coordinates[1][0] - border_coordinates[0][0]

            if custom_values is not None:
                value = custom_values[detection_idx]
            else:
                assert detections.confidence is not None  # MyPy type hint
                value = detections.confidence[detection_idx]

            color = _resolve_annotator_color(
                color=self.color,
                detections=detections,
                detection_idx=detection_idx,
                color_lookup=self.color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            cv2.rectangle(
                img=scene,
                pt1=border_coordinates[0],
                pt2=(
                    border_coordinates[0][0] + int(border_width * value),
                    border_coordinates[1][1],
                ),
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=-1,
            )
            cv2.rectangle(
                img=scene,
                pt1=border_coordinates[0],
                pt2=border_coordinates[1],
                color=_color_for_canvas(self.border_color.as_bgr(), scene),
                thickness=self.border_thickness,
            )
        return scene

    @staticmethod
    def calculate_border_coordinates(
        anchor_xy: tuple[int, int], border_wh: tuple[int, int], position: Position
    ) -> tuple[tuple[int, int], tuple[int, int]]:
        """Compute the border corner coordinates for a given anchor position."""
        cx, cy = anchor_xy
        width, height = border_wh

        if position == Position.TOP_LEFT:
            return (cx - width, cy - height), (cx, cy)
        elif position == Position.TOP_CENTER:
            return (cx - width // 2, cy), (cx + width // 2, cy - height)
        elif position == Position.TOP_RIGHT:
            return (cx, cy), (cx + width, cy - height)
        elif position == Position.CENTER_LEFT:
            return (cx - width, cy - height // 2), (cx, cy + height // 2)
        elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
            return (
                (cx - width // 2, cy - height // 2),
                (cx + width // 2, cy + height // 2),
            )
        elif position == Position.CENTER_RIGHT:
            return (cx, cy - height // 2), (cx + width, cy + height // 2)
        elif position == Position.BOTTOM_LEFT:
            return (cx - width, cy), (cx, cy + height)
        elif position == Position.BOTTOM_CENTER:
            return (cx - width // 2, cy), (cx + width // 2, cy + height)
        elif position == Position.BOTTOM_RIGHT:
            return (cx, cy), (cx + width, cy + height)
        raise ValueError(f"Unsupported position: {position}")

    @staticmethod
    def _validate_custom_values(
        custom_values: npt.NDArray[np.float64] | list[float] | None,
        detections: Detections,
    ) -> None:
        if custom_values is None:
            if detections.confidence is None:
                raise ValueError(
                    "The provided detections do not contain confidence values. "
                    "Please provide `custom_values` or ensure that the detections "
                    "contain confidence values (e.g. by using a different model)."
                )

        else:
            if not isinstance(custom_values, (np.ndarray, list)):
                raise TypeError(
                    "custom_values must be either a numpy array or a list of floats."
                )

            if len(custom_values) != len(detections):
                raise ValueError(
                    "The length of custom_values must match the number of detections."
                )

            if not all(0 <= value <= 1 for value in custom_values):
                raise ValueError("All values in custom_values must be between 0 and 1.")

Methods:

__init__(height: int = 16, width: int = 80, color: Color | ColorPalette | str = ColorPalette.DEFAULT, border_color: Color | str = Color.BLACK, position: Position = Position.TOP_CENTER, color_lookup: ColorLookup = ColorLookup.CLASS, border_thickness: int | None = None)

Parameters:

Name Type Description Default
height
int

The height in pixels of the percentage bar.

16
width
int

The width in pixels of the percentage bar.

80
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
border_color
Color | str

The color of the border lines.

BLACK
position
Position

The anchor position of drawing the percentage bar.

TOP_CENTER
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
border_thickness
int | None

The thickness of the border lines.

None
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    height: int = 16,
    width: int = 80,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    border_color: Color | str = Color.BLACK,
    position: Position = Position.TOP_CENTER,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    border_thickness: int | None = None,
):
    """
    Args:
        height: The height in pixels of the percentage bar.
        width: The width in pixels of the percentage bar.
        color: The color or color palette to use for
            annotating detections.
        border_color: The color of the border lines.
        position: The anchor position of drawing the percentage bar.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        border_thickness: The thickness of the border lines.
    """
    self.height: int = height
    self.width: int = width
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.border_color = cast(Color, _normalize_color_input(border_color))
    self.position: Position = position
    self.color_lookup: ColorLookup = color_lookup

    self.border_thickness = (
        border_thickness
        if border_thickness is not None
        else int(0.15 * self.height)
    )

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None, custom_values: npt.NDArray[np.float64] | None = None) -> ImageType

Annotates the given scene with percentage bars based on the provided detections. The percentage bars visually represent the confidence or custom values associated with each detection.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None
custom_values
NDArray[float64] | None

Custom values array to use instead of the default detection confidences. This array should have the same length as the number of detections and contain a value between 0 and 1 (inclusive) for each detection, representing the percentage to be displayed.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     confidence=np.array([0.9]),
...     class_id=np.array([0])
... )
>>> percentage_bar_annotator = sv.PercentageBarAnnotator()
>>> annotated_frame = percentage_bar_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

percentage-bar-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
    custom_values: npt.NDArray[np.float64] | None = None,
) -> ImageType:
    """Annotates the given scene with percentage bars based on the provided
    detections. The percentage bars visually represent the confidence or custom
    values associated with each detection.

    Args:
        scene: The image where percentage bars will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.
        custom_values: Custom values array to use instead
            of the default detection confidences. This array should have the
            same length as the number of detections and contain a value between
            0 and 1 (inclusive) for each detection, representing the percentage
            to be displayed.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     confidence=np.array([0.9]),
        ...     class_id=np.array([0])
        ... )
        >>> percentage_bar_annotator = sv.PercentageBarAnnotator()
        >>> annotated_frame = percentage_bar_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![percentage-bar-example](https://media.roboflow.com/
    supervision-annotator-examples/percentage-bar-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    self._validate_custom_values(custom_values=custom_values, detections=detections)

    anchors = detections.get_anchors_coordinates(anchor=self.position)
    for detection_idx in range(len(detections)):
        anchor = anchors[detection_idx]
        border_coordinates = self.calculate_border_coordinates(
            anchor_xy=(int(anchor[0]), int(anchor[1])),
            border_wh=(self.width, self.height),
            position=self.position,
        )
        border_width = border_coordinates[1][0] - border_coordinates[0][0]

        if custom_values is not None:
            value = custom_values[detection_idx]
        else:
            assert detections.confidence is not None  # MyPy type hint
            value = detections.confidence[detection_idx]

        color = _resolve_annotator_color(
            color=self.color,
            detections=detections,
            detection_idx=detection_idx,
            color_lookup=self.color_lookup,
            custom_color_lookup=custom_color_lookup,
        )
        cv2.rectangle(
            img=scene,
            pt1=border_coordinates[0],
            pt2=(
                border_coordinates[0][0] + int(border_width * value),
                border_coordinates[1][1],
            ),
            color=_color_for_canvas(color.as_bgr(), scene),
            thickness=-1,
        )
        cv2.rectangle(
            img=scene,
            pt1=border_coordinates[0],
            pt2=border_coordinates[1],
            color=_color_for_canvas(self.border_color.as_bgr(), scene),
            thickness=self.border_thickness,
        )
    return scene

calculate_border_coordinates(anchor_xy: tuple[int, int], border_wh: tuple[int, int], position: Position) -> tuple[tuple[int, int], tuple[int, int]] staticmethod

Compute the border corner coordinates for a given anchor position.

Source code in src/supervision/annotators/core.py
@staticmethod
def calculate_border_coordinates(
    anchor_xy: tuple[int, int], border_wh: tuple[int, int], position: Position
) -> tuple[tuple[int, int], tuple[int, int]]:
    """Compute the border corner coordinates for a given anchor position."""
    cx, cy = anchor_xy
    width, height = border_wh

    if position == Position.TOP_LEFT:
        return (cx - width, cy - height), (cx, cy)
    elif position == Position.TOP_CENTER:
        return (cx - width // 2, cy), (cx + width // 2, cy - height)
    elif position == Position.TOP_RIGHT:
        return (cx, cy), (cx + width, cy - height)
    elif position == Position.CENTER_LEFT:
        return (cx - width, cy - height // 2), (cx, cy + height // 2)
    elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
        return (
            (cx - width // 2, cy - height // 2),
            (cx + width // 2, cy + height // 2),
        )
    elif position == Position.CENTER_RIGHT:
        return (cx, cy - height // 2), (cx + width, cy + height // 2)
    elif position == Position.BOTTOM_LEFT:
        return (cx - width, cy), (cx, cy + height)
    elif position == Position.BOTTOM_CENTER:
        return (cx - width // 2, cy), (cx + width // 2, cy + height)
    elif position == Position.BOTTOM_RIGHT:
        return (cx, cy), (cx + width, cy + height)
    raise ValueError(f"Unsupported position: {position}")

supervision.annotators.core.HeatMapAnnotator

Bases: BaseAnnotator

A class for drawing heatmaps on an image based on provided detections.

Heat accumulates over time and is drawn as a semi-transparent overlay of blurred circles.

Source code in src/supervision/annotators/core.py
class HeatMapAnnotator(BaseAnnotator):
    """A class for drawing heatmaps on an image based on provided detections.

    Heat accumulates over time and is drawn as a semi-transparent overlay of blurred
    circles.
    """

    def __init__(
        self,
        position: Position = Position.BOTTOM_CENTER,
        opacity: float = 0.2,
        radius: int = 40,
        kernel_size: int | None = 25,
        top_hue: int = 0,
        low_hue: int = 125,
    ):
        """
        Args:
            position: The position of the heatmap. Defaults to
                `BOTTOM_CENTER`.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            radius: Radius of the heat circle.
            kernel_size: Kernel size for blurring the heatmap. Pass `None`
                to disable blurring entirely.
            top_hue: Hue at the top of the heatmap. Defaults to 0 (red).
            low_hue: Hue at the bottom of the heatmap. Defaults to 125 (blue).
        """
        self.position = position
        self.opacity = opacity
        self.radius = radius
        self.kernel_size = kernel_size
        self.top_hue = top_hue
        self.low_hue = low_hue
        self.heat_mask: npt.NDArray[np.float32] | None = None

    def reset(self) -> None:
        """Clears the accumulated heat so the annotator can be reused across independent
        streams. :meth:`~supervision.annotators.core.HeatMapAnnotator.annotate` already
        reinitializes the heat mask when the scene resolution changes; call this to
        discard heat from a previous stream that shares the same resolution.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((40, 40, 3), dtype=np.uint8)
            >>> detections = sv.Detections(xyxy=np.array([[10, 10, 20, 20]]))
            >>> heat_map_annotator = sv.HeatMapAnnotator()
            >>> _ = heat_map_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )
            >>> bool(heat_map_annotator.heat_mask.sum() > 0)
            True
            >>> heat_map_annotator.reset()
            >>> heat_map_annotator.heat_mask is None
            True

            ```
        """
        self.heat_mask = None

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
        """Annotates the scene with a heatmap based on the provided detections.

        Args:
            scene: The image where the heatmap will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.

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

        Note:
            When `detections` is empty or no heat has accumulated yet, the
            scene is returned unchanged without raising a ``RuntimeWarning``.

        Examples:
            ```python
            import supervision as sv
            from rfdetr import RFDETRMedium

            model = RFDETRMedium()

            heat_map_annotator = sv.HeatMapAnnotator()

            video_info = sv.VideoInfo.from_video_path(video_path='...')
            frames_generator = sv.get_video_frames_generator(source_path='...')

            with sv.VideoSink(target_path='...', video_info=video_info) as sink:
               for frame in frames_generator:
                   detections = model.predict(frame[:, :, ::-1])
                   annotated_frame = heat_map_annotator.annotate(
                       scene=frame.copy(),
                       detections=detections)
                   sink.write_frame(frame=annotated_frame)
            ```

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0]),
            ... )
            >>> heat_map_annotator = sv.HeatMapAnnotator()
            >>> annotated_frame = heat_map_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )
            >>> bool(heat_map_annotator.heat_mask.sum() > 0)
            True

            ```

        ![heatmap-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/heat-map-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        height, width = scene.shape[:2]
        if self.heat_mask is None or self.heat_mask.shape != (height, width):
            self.heat_mask = np.zeros((height, width), dtype=np.float32)

        anchors = detections.get_anchors_coordinates(self.position)
        if len(anchors) > 0:
            xs = anchors[:, 0].astype(np.int64)
            ys = anchors[:, 1].astype(np.int64)
            rx1 = max(int(xs.min()) - self.radius, 0)
            ry1 = max(int(ys.min()) - self.radius, 0)
            rx2 = min(int(xs.max()) + self.radius + 1, width)
            ry2 = min(int(ys.max()) + self.radius + 1, height)
            if rx1 < rx2 and ry1 < ry2:
                # Accumulate into a uint8 ROI mask (4x smaller than full float32)
                # and add in place to `self.heat_mask`.
                mask_roi = np.zeros((ry2 - ry1, rx2 - rx1), dtype=np.uint8)
                for x, y in zip(xs.tolist(), ys.tolist()):
                    cv2.circle(
                        img=mask_roi,
                        center=(x - rx1, y - ry1),
                        radius=self.radius,
                        color=(1,),
                        thickness=-1,
                    )
                self.heat_mask[ry1:ry2, rx1:rx2] += mask_roi

        heat_mask = self.heat_mask
        max_val = heat_mask.max()
        if max_val <= 0:
            return scene

        mask2d = heat_mask > 0
        row_any = np.asarray(mask2d.any(axis=1))
        hy1 = int(row_any.argmax())
        hy2 = height - int(row_any[::-1].argmax())
        col_any = np.asarray(mask2d[hy1:hy2].any(axis=0))
        hx1 = int(col_any.argmax())
        hx2 = width - int(col_any[::-1].argmax())

        # Keep float32 division before multiplication to preserve exact hue rounding.
        heat_hue = (
            self.low_hue - heat_mask / max_val * (self.low_hue - self.top_hue)
        ).astype(np.uint8)
        if self.kernel_size is not None:
            heat_hue = cast(
                npt.NDArray[np.uint8],
                cv2.blur(heat_hue, (self.kernel_size, self.kernel_size)),
            )

        if cv2.BACKEND_NAME == "fallback":
            block_lut, tail_lut = _heatmap_hsv_to_bgr_luts()
            heat_hue_roi = heat_hue[hy1:hy2, hx1:hx2]
            heat_bgr_roi = block_lut[heat_hue_roi]
            tail_start = width - (width % _HEATMAP_HSV_VECTOR_BLOCK)
            if hx2 > tail_start and not np.array_equal(block_lut, tail_lut):
                local_tail = max(0, tail_start - hx1)
                heat_bgr_roi[:, local_tail:] = tail_lut[heat_hue_roi[:, local_tail:]]
        else:
            # Native OpenCV can round HSV colors differently by SIMD width and
            # column position. Convert at the original frame width before cropping.
            hsv = np.full((height, width, 3), 255, dtype=np.uint8)
            hsv[..., 0] = heat_hue
            heat_bgr = cast(npt.NDArray[np.uint8], cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR))
            heat_bgr_roi = heat_bgr[hy1:hy2, hx1:hx2]
        scene_roi: npt.NDArray[np.uint8] = scene[hy1:hy2, hx1:hx2]
        mask2d_roi = mask2d[hy1:hy2, hx1:hx2]

        if scene.ndim == 3 and scene.shape[2] == 4:
            alpha = np.full((*scene_roi.shape[:2], 1), self.opacity, dtype=np.float32)
            blended_roi = _composite_over_bgra(scene_roi, heat_bgr_roi, alpha)
            scene_roi[mask2d_roi] = blended_roi[mask2d_roi]
            return scene

        heat_overlay_roi = _match_overlay_to_scene_channels(
            overlay=heat_bgr_roi, roi=scene_roi
        )
        # Blend only the active pixels in `mask2d_roi` (exact 1D addWeighted),
        # avoiding full-frame temporary allocations on both OpenCV and fallback.
        blended_pixels = cv2.addWeighted(
            heat_overlay_roi[mask2d_roi],
            self.opacity,
            scene_roi[mask2d_roi],
            1 - self.opacity,
            0,
        )
        scene_roi[mask2d_roi] = blended_pixels.reshape(scene_roi[mask2d_roi].shape)
        return scene

Methods:

__init__(position: Position = Position.BOTTOM_CENTER, opacity: float = 0.2, radius: int = 40, kernel_size: int | None = 25, top_hue: int = 0, low_hue: int = 125)

Parameters:

Name Type Description Default
position
Position

The position of the heatmap. Defaults to BOTTOM_CENTER.

BOTTOM_CENTER
opacity
float

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

0.2
radius
int

Radius of the heat circle.

40
kernel_size
int | None

Kernel size for blurring the heatmap. Pass None to disable blurring entirely.

25
top_hue
int

Hue at the top of the heatmap. Defaults to 0 (red).

0
low_hue
int

Hue at the bottom of the heatmap. Defaults to 125 (blue).

125
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    position: Position = Position.BOTTOM_CENTER,
    opacity: float = 0.2,
    radius: int = 40,
    kernel_size: int | None = 25,
    top_hue: int = 0,
    low_hue: int = 125,
):
    """
    Args:
        position: The position of the heatmap. Defaults to
            `BOTTOM_CENTER`.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        radius: Radius of the heat circle.
        kernel_size: Kernel size for blurring the heatmap. Pass `None`
            to disable blurring entirely.
        top_hue: Hue at the top of the heatmap. Defaults to 0 (red).
        low_hue: Hue at the bottom of the heatmap. Defaults to 125 (blue).
    """
    self.position = position
    self.opacity = opacity
    self.radius = radius
    self.kernel_size = kernel_size
    self.top_hue = top_hue
    self.low_hue = low_hue
    self.heat_mask: npt.NDArray[np.float32] | None = None

annotate(scene: ImageType, detections: Detections) -> ImageType

Annotates the scene with a heatmap based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required

Returns:

Type Description
ImageType

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

Note

When detections is empty or no heat has accumulated yet, the scene is returned unchanged without raising a RuntimeWarning.

Examples:

import supervision as sv
from rfdetr import RFDETRMedium

model = RFDETRMedium()

heat_map_annotator = sv.HeatMapAnnotator()

video_info = sv.VideoInfo.from_video_path(video_path='...')
frames_generator = sv.get_video_frames_generator(source_path='...')

with sv.VideoSink(target_path='...', video_info=video_info) as sink:
   for frame in frames_generator:
       detections = model.predict(frame[:, :, ::-1])
       annotated_frame = heat_map_annotator.annotate(
           scene=frame.copy(),
           detections=detections)
       sink.write_frame(frame=annotated_frame)
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0]),
... )
>>> heat_map_annotator = sv.HeatMapAnnotator()
>>> annotated_frame = heat_map_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )
>>> bool(heat_map_annotator.heat_mask.sum() > 0)
True

heatmap-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
    """Annotates the scene with a heatmap based on the provided detections.

    Args:
        scene: The image where the heatmap will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.

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

    Note:
        When `detections` is empty or no heat has accumulated yet, the
        scene is returned unchanged without raising a ``RuntimeWarning``.

    Examples:
        ```python
        import supervision as sv
        from rfdetr import RFDETRMedium

        model = RFDETRMedium()

        heat_map_annotator = sv.HeatMapAnnotator()

        video_info = sv.VideoInfo.from_video_path(video_path='...')
        frames_generator = sv.get_video_frames_generator(source_path='...')

        with sv.VideoSink(target_path='...', video_info=video_info) as sink:
           for frame in frames_generator:
               detections = model.predict(frame[:, :, ::-1])
               annotated_frame = heat_map_annotator.annotate(
                   scene=frame.copy(),
                   detections=detections)
               sink.write_frame(frame=annotated_frame)
        ```

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0]),
        ... )
        >>> heat_map_annotator = sv.HeatMapAnnotator()
        >>> annotated_frame = heat_map_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )
        >>> bool(heat_map_annotator.heat_mask.sum() > 0)
        True

        ```

    ![heatmap-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/heat-map-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    height, width = scene.shape[:2]
    if self.heat_mask is None or self.heat_mask.shape != (height, width):
        self.heat_mask = np.zeros((height, width), dtype=np.float32)

    anchors = detections.get_anchors_coordinates(self.position)
    if len(anchors) > 0:
        xs = anchors[:, 0].astype(np.int64)
        ys = anchors[:, 1].astype(np.int64)
        rx1 = max(int(xs.min()) - self.radius, 0)
        ry1 = max(int(ys.min()) - self.radius, 0)
        rx2 = min(int(xs.max()) + self.radius + 1, width)
        ry2 = min(int(ys.max()) + self.radius + 1, height)
        if rx1 < rx2 and ry1 < ry2:
            # Accumulate into a uint8 ROI mask (4x smaller than full float32)
            # and add in place to `self.heat_mask`.
            mask_roi = np.zeros((ry2 - ry1, rx2 - rx1), dtype=np.uint8)
            for x, y in zip(xs.tolist(), ys.tolist()):
                cv2.circle(
                    img=mask_roi,
                    center=(x - rx1, y - ry1),
                    radius=self.radius,
                    color=(1,),
                    thickness=-1,
                )
            self.heat_mask[ry1:ry2, rx1:rx2] += mask_roi

    heat_mask = self.heat_mask
    max_val = heat_mask.max()
    if max_val <= 0:
        return scene

    mask2d = heat_mask > 0
    row_any = np.asarray(mask2d.any(axis=1))
    hy1 = int(row_any.argmax())
    hy2 = height - int(row_any[::-1].argmax())
    col_any = np.asarray(mask2d[hy1:hy2].any(axis=0))
    hx1 = int(col_any.argmax())
    hx2 = width - int(col_any[::-1].argmax())

    # Keep float32 division before multiplication to preserve exact hue rounding.
    heat_hue = (
        self.low_hue - heat_mask / max_val * (self.low_hue - self.top_hue)
    ).astype(np.uint8)
    if self.kernel_size is not None:
        heat_hue = cast(
            npt.NDArray[np.uint8],
            cv2.blur(heat_hue, (self.kernel_size, self.kernel_size)),
        )

    if cv2.BACKEND_NAME == "fallback":
        block_lut, tail_lut = _heatmap_hsv_to_bgr_luts()
        heat_hue_roi = heat_hue[hy1:hy2, hx1:hx2]
        heat_bgr_roi = block_lut[heat_hue_roi]
        tail_start = width - (width % _HEATMAP_HSV_VECTOR_BLOCK)
        if hx2 > tail_start and not np.array_equal(block_lut, tail_lut):
            local_tail = max(0, tail_start - hx1)
            heat_bgr_roi[:, local_tail:] = tail_lut[heat_hue_roi[:, local_tail:]]
    else:
        # Native OpenCV can round HSV colors differently by SIMD width and
        # column position. Convert at the original frame width before cropping.
        hsv = np.full((height, width, 3), 255, dtype=np.uint8)
        hsv[..., 0] = heat_hue
        heat_bgr = cast(npt.NDArray[np.uint8], cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR))
        heat_bgr_roi = heat_bgr[hy1:hy2, hx1:hx2]
    scene_roi: npt.NDArray[np.uint8] = scene[hy1:hy2, hx1:hx2]
    mask2d_roi = mask2d[hy1:hy2, hx1:hx2]

    if scene.ndim == 3 and scene.shape[2] == 4:
        alpha = np.full((*scene_roi.shape[:2], 1), self.opacity, dtype=np.float32)
        blended_roi = _composite_over_bgra(scene_roi, heat_bgr_roi, alpha)
        scene_roi[mask2d_roi] = blended_roi[mask2d_roi]
        return scene

    heat_overlay_roi = _match_overlay_to_scene_channels(
        overlay=heat_bgr_roi, roi=scene_roi
    )
    # Blend only the active pixels in `mask2d_roi` (exact 1D addWeighted),
    # avoiding full-frame temporary allocations on both OpenCV and fallback.
    blended_pixels = cv2.addWeighted(
        heat_overlay_roi[mask2d_roi],
        self.opacity,
        scene_roi[mask2d_roi],
        1 - self.opacity,
        0,
    )
    scene_roi[mask2d_roi] = blended_pixels.reshape(scene_roi[mask2d_roi].shape)
    return scene

reset() -> None

Clears the accumulated heat so the annotator can be reused across independent streams. :meth:~supervision.annotators.core.HeatMapAnnotator.annotate already reinitializes the heat mask when the scene resolution changes; call this to discard heat from a previous stream that shares the same resolution.

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((40, 40, 3), dtype=np.uint8)
>>> detections = sv.Detections(xyxy=np.array([[10, 10, 20, 20]]))
>>> heat_map_annotator = sv.HeatMapAnnotator()
>>> _ = heat_map_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )
>>> bool(heat_map_annotator.heat_mask.sum() > 0)
True
>>> heat_map_annotator.reset()
>>> heat_map_annotator.heat_mask is None
True
Source code in src/supervision/annotators/core.py
def reset(self) -> None:
    """Clears the accumulated heat so the annotator can be reused across independent
    streams. :meth:`~supervision.annotators.core.HeatMapAnnotator.annotate` already
    reinitializes the heat mask when the scene resolution changes; call this to
    discard heat from a previous stream that shares the same resolution.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((40, 40, 3), dtype=np.uint8)
        >>> detections = sv.Detections(xyxy=np.array([[10, 10, 20, 20]]))
        >>> heat_map_annotator = sv.HeatMapAnnotator()
        >>> _ = heat_map_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )
        >>> bool(heat_map_annotator.heat_mask.sum() > 0)
        True
        >>> heat_map_annotator.reset()
        >>> heat_map_annotator.heat_mask is None
        True

        ```
    """
    self.heat_mask = None

supervision.annotators.core.MaskAnnotator

Bases: BaseAnnotator

A class for drawing masks on an image using provided detections.

Warning

This annotator uses :class:~supervision.detection.core.Detections.mask.

Source code in src/supervision/annotators/core.py
class MaskAnnotator(BaseAnnotator):
    """A class for drawing masks on an image using provided detections.

    !!! warning

    This annotator uses
    :class:`~supervision.detection.core.Detections`.mask.
    """

    requires_mask = True

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        opacity: float = 0.5,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.opacity = opacity
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with masks based on the provided detections.

        Args:
            scene: The image where masks will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
                or `(H, W, 1)`; masks are drawn in the first (blue) channel of
                their color, as OpenCV draws boxes and polygons.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     mask=np.zeros((1, 100, 100), dtype=bool),
            ...     class_id=np.array([0])
            ... )
            >>> mask_annotator = sv.MaskAnnotator()
            >>> annotated_frame = mask_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![mask-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/mask-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if detections.mask is None:
            return scene

        image_shape = (int(scene.shape[0]), int(scene.shape[1]))
        effective_lookup = (
            self.color_lookup if custom_color_lookup is None else custom_color_lookup
        )
        if len(detections) > 0:
            _resolve_detection_color(
                color=self.color,
                detections=detections,
                detection_idx=0,
                color_lookup=effective_lookup,
            )
        roi = _masks_to_roi(detections.mask, image_shape, detections.xyxy)
        if roi is None:
            return scene

        x1, y1, x2, y2 = roi
        scene_roi = scene[y1:y2, x1:x2]
        colored_mask = np.array(scene_roi, copy=True, dtype=np.uint8)
        is_bgra = scene.ndim == 3 and scene.shape[2] == 4
        mask_union = _paint_masks_by_area(
            colored_mask,
            detections,
            self.color,
            effective_lookup,
            collect_union=is_bgra,
            canvas_origin=(x1, y1),
        )
        if is_bgra:
            assert mask_union is not None
            alpha = mask_union[..., np.newaxis].astype(np.float32) * self.opacity
            tmp = _composite_over_bgra(scene_roi, colored_mask[..., :3], alpha)
        else:
            tmp = cv2.addWeighted(
                colored_mask, self.opacity, scene_roi, 1 - self.opacity, 0
            )
        # OpenCV drops a singleton channel axis; restore it before assignment.
        scene_roi[:] = tmp.reshape(scene_roi.shape)
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, opacity: float = 0.5, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
opacity
float

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

0.5
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    opacity: float = 0.5,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.opacity = opacity
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with masks based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

The image where masks will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale arrays may have shape (H, W) or (H, W, 1); masks are drawn in the first (blue) channel of their color, as OpenCV draws boxes and polygons.

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     mask=np.zeros((1, 100, 100), dtype=bool),
...     class_id=np.array([0])
... )
>>> mask_annotator = sv.MaskAnnotator()
>>> annotated_frame = mask_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

mask-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with masks based on the provided detections.

    Args:
        scene: The image where masks will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
            or `(H, W, 1)`; masks are drawn in the first (blue) channel of
            their color, as OpenCV draws boxes and polygons.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     mask=np.zeros((1, 100, 100), dtype=bool),
        ...     class_id=np.array([0])
        ... )
        >>> mask_annotator = sv.MaskAnnotator()
        >>> annotated_frame = mask_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![mask-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/mask-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if detections.mask is None:
        return scene

    image_shape = (int(scene.shape[0]), int(scene.shape[1]))
    effective_lookup = (
        self.color_lookup if custom_color_lookup is None else custom_color_lookup
    )
    if len(detections) > 0:
        _resolve_detection_color(
            color=self.color,
            detections=detections,
            detection_idx=0,
            color_lookup=effective_lookup,
        )
    roi = _masks_to_roi(detections.mask, image_shape, detections.xyxy)
    if roi is None:
        return scene

    x1, y1, x2, y2 = roi
    scene_roi = scene[y1:y2, x1:x2]
    colored_mask = np.array(scene_roi, copy=True, dtype=np.uint8)
    is_bgra = scene.ndim == 3 and scene.shape[2] == 4
    mask_union = _paint_masks_by_area(
        colored_mask,
        detections,
        self.color,
        effective_lookup,
        collect_union=is_bgra,
        canvas_origin=(x1, y1),
    )
    if is_bgra:
        assert mask_union is not None
        alpha = mask_union[..., np.newaxis].astype(np.float32) * self.opacity
        tmp = _composite_over_bgra(scene_roi, colored_mask[..., :3], alpha)
    else:
        tmp = cv2.addWeighted(
            colored_mask, self.opacity, scene_roi, 1 - self.opacity, 0
        )
    # OpenCV drops a singleton channel axis; restore it before assignment.
    scene_roi[:] = tmp.reshape(scene_roi.shape)
    return scene

supervision.annotators.label_map.LabelMapAnnotator

Colours a dense class-id map over an image, one palette colour per class.

A semantic segmentation model labels every pixel with a class id. This annotator paints that (H, W) map directly through a colour lookup table, so it holds one array the size of the image instead of one mask per class, which is what :class:~supervision.annotators.core.MaskAnnotator draws from :class:~supervision.detection.core.Detections.

Class i takes palette colour i, wrapping around a palette shorter than the class list, as :class:~supervision.annotators.core.MaskAnnotator does, so the two annotators colour a class alike.

import supervision as sv
from PIL import Image

image = Image.open("<SOURCE_IMAGE_PATH>")
label_map = ...  # (H, W) integer class ids from a semantic segmentation model

label_map_annotator = sv.LabelMapAnnotator(opacity=0.6)
annotated_image = label_map_annotator.annotate(image.copy(), label_map)
Source code in src/supervision/annotators/label_map.py
class LabelMapAnnotator:
    """Colours a dense class-id map over an image, one palette colour per class.

    A semantic segmentation model labels every pixel with a class id. This annotator
    paints that `(H, W)` map directly through a colour lookup table, so it holds one
    array the size of the image instead of one mask per class, which is what
    :class:`~supervision.annotators.core.MaskAnnotator` draws from
    :class:`~supervision.detection.core.Detections`.

    Class `i` takes palette colour `i`, wrapping around a palette shorter than the
    class list, as :class:`~supervision.annotators.core.MaskAnnotator` does, so the
    two annotators colour a class alike.

    === "Image"

        ```python
        import supervision as sv
        from PIL import Image

        image = Image.open("<SOURCE_IMAGE_PATH>")
        label_map = ...  # (H, W) integer class ids from a semantic segmentation model

        label_map_annotator = sv.LabelMapAnnotator(opacity=0.6)
        annotated_image = label_map_annotator.annotate(image.copy(), label_map)
        ```
    """

    def __init__(
        self,
        color: ColorPalette = ColorPalette.DEFAULT,
        opacity: float = 0.6,
        background_id: int | None = 0,
    ) -> None:
        """
        Args:
            color: Colour palette; class `i` takes the colour at index `i`.
            opacity: Opacity of the colours over the scene, from 0 to 1. Values
                outside are clamped: `<= 0` draws nothing and `>= 1` fully replaces
                the painted pixels.
            background_id: Class id left unpainted, so the scene shows through. `0`
                by default, as in
                :meth:`~supervision.detection.core.Detections.from_semantic_segmentation`.
                Pass `None` to paint every class. Negative ids are ignore labels and
                are never painted.

        Raises:
            ValueError: If the palette holds no colour.
        """
        if not color.colors:
            raise ValueError("color must be a palette with at least one colour.")
        self.color = color
        self.opacity = opacity
        self.background_id = background_id

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, label_map: Any) -> ImageType:
        """Colour the class-id map over the scene.

        Args:
            scene: The image to draw on, a 3-channel `uint8` `numpy.ndarray` (BGR) or
                a `PIL.Image.Image`. It is drawn on in place.
            label_map: Per-pixel class ids, an `(H, W)` integer array or tensor with
                the scene's height and width.

        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 `scene` is not a 3-channel `uint8` image, if `label_map` is
                not a 2-D integer array of the scene's size, or if its ids span more
                than 1,048,576 values from smallest to largest.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> palette = sv.ColorPalette.from_hex(["#ff0000", "#00ff00", "#0000ff"])
            >>> annotator = sv.LabelMapAnnotator(color=palette, opacity=1.0)
            >>> scene = np.zeros((1, 2, 3), dtype=np.uint8)
            >>> annotator.annotate(scene, np.array([[1, 0]]))[..., ::-1].tolist()
            [[[0, 255, 0], [0, 0, 0]]]

            ```
        """
        # The conversion decorator rejects other types and turns a Pillow image into
        # an array, so this always holds; it narrows `ImageType` for the type checker.
        assert isinstance(scene, np.ndarray)
        if scene.ndim != 3 or scene.shape[2] != 3:
            raise ValueError(
                f"LabelMapAnnotator draws on 3-channel images, got shape {scene.shape}."
            )
        # The colours are uint8; a wider scene would blend differently on OpenCV and
        # on the NumPy fallback, and `opacity >= 1` would write 0-255 into a float one.
        if scene.dtype != np.uint8:
            raise ValueError(
                f"LabelMapAnnotator draws on uint8 images, got dtype {scene.dtype}."
            )
        class_ids = self._check_label_map(label_map, scene.shape[:2])
        if class_ids.size == 0:
            return scene

        painted = class_ids >= 0
        if self.background_id is not None:
            painted &= class_ids != self.background_id
        _blend(scene, painted, self._colors_of(class_ids), self.opacity)
        return scene

    def _colors_of(self, class_ids: npt.NDArray[np.integer]) -> npt.NDArray[np.uint8]:
        """Return an `(H, W, 3)` BGR colour per pixel from one lookup table.

        The table runs from the smallest to the largest id in the map, so its size
        follows the ids present, not the palette or the dtype. Negative ids index like
        any other and are masked out by the caller.
        """
        palette = np.array(
            [color.as_bgr() for color in self.color.colors], dtype=np.uint8
        )
        # Python ints, because the difference of two `int8` ids would wrap.
        lowest, highest = int(class_ids.min()), int(class_ids.max())
        span = highest - lowest
        if span >= _MAX_ID_SPAN:
            raise ValueError(
                f"label_map ids span more than {_MAX_ID_SPAN} values, from {lowest} "
                f"to {highest}; it does not look like a class-id map."
            )
        # Bounded offsets keep the LUT indices integral even at the dtype limits.
        palette_size = len(palette)
        palette_indices = (np.arange(span + 1) + lowest % palette_size) % palette_size
        table = palette[palette_indices]
        # Unsigned subtraction is safe because every id is at least the minimum.
        # Widen signed inputs so narrow dtypes can hold the full range of offsets.
        wide = (
            class_ids
            if class_ids.dtype.kind == "u"
            else class_ids.astype(np.int64, copy=False)
        )
        offsets = wide - np.asarray(lowest, dtype=wide.dtype)
        colors: npt.NDArray[np.uint8] = table[offsets]
        return colors

    @staticmethod
    def _check_label_map(
        label_map: Any, scene_size: tuple[int, int]
    ) -> npt.NDArray[np.integer]:
        """Return `label_map` as an integer array of the scene's size, or raise."""
        if not isinstance(label_map, np.ndarray) and not hasattr(label_map, "cpu"):
            raise ValueError(
                "label_map must be an (H, W) integer array or tensor, got "
                f"{type(label_map).__name__}."
            )
        class_ids = _to_numpy(label_map)
        if class_ids.ndim != 2:
            raise ValueError(
                f"label_map must be a 2-D array, got shape {class_ids.shape}."
            )
        if class_ids.dtype.kind not in ("i", "u"):
            raise ValueError(
                f"label_map must hold integer class ids, got dtype {class_ids.dtype}."
            )
        if class_ids.shape != scene_size:
            raise ValueError(
                f"label_map shape {class_ids.shape} does not match the scene's "
                f"height and width {scene_size}."
            )
        return class_ids

Methods:

__init__(color: ColorPalette = ColorPalette.DEFAULT, opacity: float = 0.6, background_id: int | None = 0) -> None

Parameters:

Name Type Description Default
color
ColorPalette

Colour palette; class i takes the colour at index i.

DEFAULT
opacity
float

Opacity of the colours over the scene, from 0 to 1. Values outside are clamped: <= 0 draws nothing and >= 1 fully replaces the painted pixels.

0.6
background_id
int | None

Class id left unpainted, so the scene shows through. 0 by default, as in :meth:~supervision.detection.core.Detections.from_semantic_segmentation. Pass None to paint every class. Negative ids are ignore labels and are never painted.

0

Raises:

Type Description
ValueError

If the palette holds no colour.

Source code in src/supervision/annotators/label_map.py
def __init__(
    self,
    color: ColorPalette = ColorPalette.DEFAULT,
    opacity: float = 0.6,
    background_id: int | None = 0,
) -> None:
    """
    Args:
        color: Colour palette; class `i` takes the colour at index `i`.
        opacity: Opacity of the colours over the scene, from 0 to 1. Values
            outside are clamped: `<= 0` draws nothing and `>= 1` fully replaces
            the painted pixels.
        background_id: Class id left unpainted, so the scene shows through. `0`
            by default, as in
            :meth:`~supervision.detection.core.Detections.from_semantic_segmentation`.
            Pass `None` to paint every class. Negative ids are ignore labels and
            are never painted.

    Raises:
        ValueError: If the palette holds no colour.
    """
    if not color.colors:
        raise ValueError("color must be a palette with at least one colour.")
    self.color = color
    self.opacity = opacity
    self.background_id = background_id

annotate(scene: ImageType, label_map: Any) -> ImageType

Colour the class-id map over the scene.

Parameters:

Name Type Description Default
scene
ImageType

The image to draw on, a 3-channel uint8 numpy.ndarray (BGR) or a PIL.Image.Image. It is drawn on in place.

required
label_map
Any

Per-pixel class ids, an (H, W) integer array or tensor with the scene's height and width.

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 scene is not a 3-channel uint8 image, if label_map is not a 2-D integer array of the scene's size, or if its ids span more than 1,048,576 values from smallest to largest.

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> palette = sv.ColorPalette.from_hex(["#ff0000", "#00ff00", "#0000ff"])
>>> annotator = sv.LabelMapAnnotator(color=palette, opacity=1.0)
>>> scene = np.zeros((1, 2, 3), dtype=np.uint8)
>>> annotator.annotate(scene, np.array([[1, 0]]))[..., ::-1].tolist()
[[[0, 255, 0], [0, 0, 0]]]
Source code in src/supervision/annotators/label_map.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, label_map: Any) -> ImageType:
    """Colour the class-id map over the scene.

    Args:
        scene: The image to draw on, a 3-channel `uint8` `numpy.ndarray` (BGR) or
            a `PIL.Image.Image`. It is drawn on in place.
        label_map: Per-pixel class ids, an `(H, W)` integer array or tensor with
            the scene's height and width.

    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 `scene` is not a 3-channel `uint8` image, if `label_map` is
            not a 2-D integer array of the scene's size, or if its ids span more
            than 1,048,576 values from smallest to largest.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> palette = sv.ColorPalette.from_hex(["#ff0000", "#00ff00", "#0000ff"])
        >>> annotator = sv.LabelMapAnnotator(color=palette, opacity=1.0)
        >>> scene = np.zeros((1, 2, 3), dtype=np.uint8)
        >>> annotator.annotate(scene, np.array([[1, 0]]))[..., ::-1].tolist()
        [[[0, 255, 0], [0, 0, 0]]]

        ```
    """
    # The conversion decorator rejects other types and turns a Pillow image into
    # an array, so this always holds; it narrows `ImageType` for the type checker.
    assert isinstance(scene, np.ndarray)
    if scene.ndim != 3 or scene.shape[2] != 3:
        raise ValueError(
            f"LabelMapAnnotator draws on 3-channel images, got shape {scene.shape}."
        )
    # The colours are uint8; a wider scene would blend differently on OpenCV and
    # on the NumPy fallback, and `opacity >= 1` would write 0-255 into a float one.
    if scene.dtype != np.uint8:
        raise ValueError(
            f"LabelMapAnnotator draws on uint8 images, got dtype {scene.dtype}."
        )
    class_ids = self._check_label_map(label_map, scene.shape[:2])
    if class_ids.size == 0:
        return scene

    painted = class_ids >= 0
    if self.background_id is not None:
        painted &= class_ids != self.background_id
    _blend(scene, painted, self._colors_of(class_ids), self.opacity)
    return scene

supervision.annotators.core.PolygonAnnotator

Bases: BaseAnnotator

A class for drawing polygons on an image using provided detections.

Warning

This annotator uses :class:~supervision.detection.core.Detections.mask.

Source code in src/supervision/annotators/core.py
class PolygonAnnotator(BaseAnnotator):
    """A class for drawing polygons on an image using provided detections.

    !!! warning

    This annotator uses
    :class:`~supervision.detection.core.Detections`.mask.
    """

    requires_mask = True

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        thickness: int = 2,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating detections.
            thickness: Thickness of the polygon lines.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.thickness: int = thickness
        self.color_lookup: ColorLookup = color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with polygons based on the provided detections.

        Args:
            scene: The image where polygons will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> polygon_annotator = sv.PolygonAnnotator()
            >>> annotated_frame = polygon_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        Note:
            When `detections.mask` is a
            :class:`~supervision.detection.compact_mask.CompactMask`, each
            detection's polygon is decoded from a bbox-sized crop (O(crop_area))
            rather than a full-frame ``(H, W)`` allocation (O(H·W)). Polygon
            coordinates are
            shifted from crop-local space to image space via the stored
            ``(x1, y1)`` bbox origin. Pixels outside the declared ``xyxy`` box
            are not represented in compact storage and will not be drawn.

        ![polygon-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/polygon-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if detections.mask is None:
            return scene

        for detection_idx, mask, offset in _iter_mask_crops(detections):
            color = _resolve_annotator_color(
                color=self.color,
                detections=detections,
                detection_idx=detection_idx,
                color_lookup=self.color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            for polygon in mask_to_polygons(mask=mask):
                if offset is not None:
                    # translate crop-local polygon to image space via (x1, y1) origin
                    polygon = polygon + offset
                scene = draw_polygon(
                    scene=scene,
                    polygon=cast(npt.NDArray[np.int_], polygon),
                    color=color,
                    thickness=self.thickness,
                )

        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating detections.

DEFAULT
thickness
int

Thickness of the polygon lines.

2
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    thickness: int = 2,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color or color palette to use for
            annotating detections.
        thickness: Thickness of the polygon lines.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.thickness: int = thickness
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with polygons based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> polygon_annotator = sv.PolygonAnnotator()
>>> annotated_frame = polygon_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )
Note

When detections.mask is a :class:~supervision.detection.compact_mask.CompactMask, each detection's polygon is decoded from a bbox-sized crop (O(crop_area)) rather than a full-frame (H, W) allocation (O(H·W)). Polygon coordinates are shifted from crop-local space to image space via the stored (x1, y1) bbox origin. Pixels outside the declared xyxy box are not represented in compact storage and will not be drawn.

polygon-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with polygons based on the provided detections.

    Args:
        scene: The image where polygons will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> polygon_annotator = sv.PolygonAnnotator()
        >>> annotated_frame = polygon_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    Note:
        When `detections.mask` is a
        :class:`~supervision.detection.compact_mask.CompactMask`, each
        detection's polygon is decoded from a bbox-sized crop (O(crop_area))
        rather than a full-frame ``(H, W)`` allocation (O(H·W)). Polygon
        coordinates are
        shifted from crop-local space to image space via the stored
        ``(x1, y1)`` bbox origin. Pixels outside the declared ``xyxy`` box
        are not represented in compact storage and will not be drawn.

    ![polygon-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/polygon-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if detections.mask is None:
        return scene

    for detection_idx, mask, offset in _iter_mask_crops(detections):
        color = _resolve_annotator_color(
            color=self.color,
            detections=detections,
            detection_idx=detection_idx,
            color_lookup=self.color_lookup,
            custom_color_lookup=custom_color_lookup,
        )
        for polygon in mask_to_polygons(mask=mask):
            if offset is not None:
                # translate crop-local polygon to image space via (x1, y1) origin
                polygon = polygon + offset
            scene = draw_polygon(
                scene=scene,
                polygon=cast(npt.NDArray[np.int_], polygon),
                color=color,
                thickness=self.thickness,
            )

    return scene

supervision.annotators.core.LabelAnnotator

Bases: _BaseLabelAnnotator

A class for annotating labels on an image using provided detections.

Source code in src/supervision/annotators/core.py
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
class LabelAnnotator(_BaseLabelAnnotator):
    """A class for annotating labels on an image using provided detections."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        text_color: Color | ColorPalette | str = Color.WHITE,
        text_scale: float = 0.5,
        text_thickness: int = 1,
        text_padding: int = 10,
        text_position: Position = Position.TOP_LEFT,
        text_offset: tuple[int, int] = (0, 0),
        border_radius: int = 0,
        smart_position: bool = False,
        max_line_length: int | None = None,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating the text background.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            text_color: The color or color palette to use
                for the text.
            text_scale: Font scale for the text.
            text_thickness: Thickness of the text characters.
            text_padding: Padding around the text within its background box.
            text_position: Position of the text relative to the detection.
                Possible values are defined in the
                :class:`~supervision.geometry.core.Position` enum.
            text_offset: A tuple of 2D coordinates `(x, y)` to
                offset the text position from the anchor point, in pixels.
            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.
            max_line_length: Maximum number of characters per line
                before wrapping the text. None means no wrapping.
        """
        self.text_scale: float = text_scale
        self.text_thickness: int = text_thickness
        super().__init__(
            color=color,
            color_lookup=color_lookup,
            text_color=text_color,
            text_padding=text_padding,
            text_position=text_position,
            text_offset=text_offset,
            border_radius=border_radius,
            smart_position=smart_position,
            max_line_length=max_line_length,
        )

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        labels: list[str] | None = None,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with labels based on the provided detections.

        Args:
            scene: The image where labels will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            labels: Custom labels for each detection.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     confidence=np.array([0.9]),
            ...     class_id=np.array([0]),
            ...     data={'class_name': np.array(['person'])}
            ... )
            >>> labels = [
            ...     f"{class_name} {confidence:.2f}"
            ...     for class_name, confidence
            ...     in zip(detections['class_name'], detections.confidence)
            ... ]
            >>> label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
            >>> annotated_frame = label_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections,
            ...     labels=labels
            ... )

            ```

        ![label-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/label-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        _validate_labels(labels, detections)

        labels = get_labels_text(detections, labels)
        label_properties: npt.NDArray[np.float32] = self._get_label_properties(
            detections, labels
        )

        if self.smart_position:
            label_properties = self._adjust_labels_in_frame(
                (scene.shape[1], scene.shape[0]),
                labels,
                label_properties,
            )

        self._draw_labels(
            scene=scene,
            labels=labels,
            label_properties=label_properties,
            detections=detections,
            custom_color_lookup=custom_color_lookup,
        )

        return scene

    def _get_label_properties(
        self,
        detections: Detections,
        labels: list[str],
    ) -> Any:
        label_properties = []
        anchors_coordinates: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
            anchor=self.text_anchor
        ).astype(int)

        for label, center_coordinates in zip(labels, anchors_coordinates):
            center_coordinates = (
                center_coordinates[0] + self.text_offset[0],
                center_coordinates[1] + self.text_offset[1],
            )

            wrapped_lines = wrap_text(label, self.max_line_length)
            line_heights = []
            line_widths = []

            for line in wrapped_lines:
                (text_w, text_h) = cv2.getTextSize(
                    text=line,
                    fontFace=CV2_FONT,
                    fontScale=self.text_scale,
                    thickness=self.text_thickness,
                )[0]
                if not line:
                    # Reserve the same height `_draw_labels` skips for a blank line
                    text_h = cv2.getTextSize(
                        text="Tg",
                        fontFace=CV2_FONT,
                        fontScale=self.text_scale,
                        thickness=self.text_thickness,
                    )[0][1]
                line_heights.append(text_h)
                line_widths.append(text_w)

            # Get the maximum width and total height
            max_width = max(line_widths) if line_widths else 0
            total_height = (
                sum(line_heights) + (len(line_heights) - 1) * self.text_padding
            )

            # Add padding around all sides
            width_padded = max_width + 2 * self.text_padding
            height_padded = total_height + 2 * self.text_padding

            text_background_xyxy = resolve_text_background_xyxy(
                center_coordinates=center_coordinates,
                text_wh=(width_padded, height_padded),
                position=self.text_anchor,
            )

            label_properties.append(
                [
                    *text_background_xyxy,
                    total_height,
                ]
            )
        return np.array(label_properties, dtype=np.float32).reshape(-1, 5)

    def _draw_labels(
        self,
        scene: npt.NDArray[np.uint8],
        labels: list[str],
        label_properties: npt.NDArray[np.float32],
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None,
    ) -> None:
        assert len(labels) == len(label_properties) == len(detections), (
            f"Number of label properties ({len(label_properties)}), "
            f"labels ({len(labels)}) and detections ({len(detections)}) "
            "do not match."
        )

        color_lookup = (
            custom_color_lookup
            if custom_color_lookup is not None
            else self.color_lookup
        )

        for idx, label_property in enumerate(label_properties):
            background_color = _resolve_detection_color(
                color=self.color,
                detections=detections,
                detection_idx=idx,
                color_lookup=color_lookup,
            )
            text_color = _resolve_detection_color(
                color=self.text_color,
                detections=detections,
                detection_idx=idx,
                color_lookup=color_lookup,
            )

            box_xyxy = label_property[:4].astype(int)

            self.draw_rounded_rectangle(
                scene=scene,
                xyxy=box_xyxy,
                color=_color_for_canvas(background_color.as_bgr(), scene),
                border_radius=self.border_radius,
            )

            # Handle multiline text
            wrapped_lines = wrap_text(labels[idx], self.max_line_length)
            current_y = box_xyxy[1] + self.text_padding  # Start y position

            for line in wrapped_lines:
                if not line:
                    # Use a character with ascenders and descenders as height reference
                    (_, text_h) = cv2.getTextSize(
                        text="Tg",
                        fontFace=CV2_FONT,
                        fontScale=self.text_scale,
                        thickness=self.text_thickness,
                    )[0]
                    current_y += text_h + self.text_padding
                    continue

                (_, text_h) = cv2.getTextSize(
                    text=line,
                    fontFace=CV2_FONT,
                    fontScale=self.text_scale,
                    thickness=self.text_thickness,
                )[0]

                text_x = box_xyxy[0] + self.text_padding
                text_y = current_y + text_h  # Add height to get to text baseline

                _draw_antialiased(
                    scene,
                    text_color.as_bgr(),
                    lambda image, color: cv2.putText(
                        image,
                        line,
                        (text_x, text_y),
                        CV2_FONT,
                        self.text_scale,
                        color,
                        self.text_thickness,
                        lineType=cv2.LINE_AA,
                    ),
                )

                current_y += text_h + self.text_padding  # Move to next line position

    @staticmethod
    def draw_rounded_rectangle(
        scene: npt.NDArray[np.uint8],
        xyxy: tuple[int, int, int, int],
        color: tuple[int, ...],
        border_radius: int,
    ) -> npt.NDArray[np.uint8]:
        """Draw a filled rectangle with optional rounded corners on an image.

        Args:
            scene: BGR image array to draw on; modified in-place and returned.
            xyxy: Bounding box as (x1, y1, x2, y2) pixel coordinates.
            color: Fill color as a BGR tuple (e.g. ``(0, 0, 255)`` for red), or a
                BGRA tuple for a BGRA ``scene``.
            border_radius: Corner rounding radius in pixels. Values <= 0
                (including values clamped to 0 by a degenerate box) draw a
                plain filled rectangle with square corners.

        Returns:
            The annotated ``scene`` array.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> scene = np.zeros((200, 200, 3), dtype=np.uint8)
            >>> scene = sv.LabelAnnotator.draw_rounded_rectangle(
            ...     scene=scene,
            ...     xyxy=(10, 10, 100, 50),
            ...     color=(0, 255, 0),
            ...     border_radius=0,
            ... )
            >>> bool(scene[30, 50].tolist() == [0, 255, 0])
            True

            ```
        """
        x1, y1, x2, y2 = xyxy
        width = x2 - x1
        height = y2 - y1

        border_radius = min(border_radius, min(width, height) // 2)

        if border_radius <= 0:
            # square corners: a single fill rectangle (the common default), rather
            # than two rectangles plus four zero-radius corner circles
            cv2.rectangle(
                img=scene,
                pt1=(x1, y1),
                pt2=(x2, y2),
                color=color,
                thickness=-1,
            )
            return scene

        rectangle_coordinates = [
            ((x1 + border_radius, y1), (x2 - border_radius, y2)),
            ((x1, y1 + border_radius), (x2, y2 - border_radius)),
        ]
        circle_centers = [
            (x1 + border_radius, y1 + border_radius),
            (x2 - border_radius, y1 + border_radius),
            (x1 + border_radius, y2 - border_radius),
            (x2 - border_radius, y2 - border_radius),
        ]

        for coordinates in rectangle_coordinates:
            cv2.rectangle(
                img=scene,
                pt1=coordinates[0],
                pt2=coordinates[1],
                color=color,
                thickness=-1,
            )
        for center in circle_centers:
            cv2.circle(
                img=scene,
                center=center,
                radius=border_radius,
                color=color,
                thickness=-1,
            )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, color_lookup: ColorLookup = ColorLookup.CLASS, text_color: Color | ColorPalette | str = Color.WHITE, text_scale: float = 0.5, text_thickness: int = 1, text_padding: int = 10, text_position: Position = Position.TOP_LEFT, text_offset: tuple[int, int] = (0, 0), border_radius: int = 0, smart_position: bool = False, max_line_length: int | None = None)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating the text background.

DEFAULT
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
text_color
Color | ColorPalette | str

The color or color palette to use for the text.

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
text_position
Position

Position of the text relative to the detection. Possible values are defined in the :class:~supervision.geometry.core.Position enum.

TOP_LEFT
text_offset
tuple[int, int]

A tuple of 2D coordinates (x, y) to offset the text position from the anchor point, in pixels.

(0, 0)
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
max_line_length
int | None

Maximum number of characters per line before wrapping the text. None means no wrapping.

None
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    text_color: Color | ColorPalette | str = Color.WHITE,
    text_scale: float = 0.5,
    text_thickness: int = 1,
    text_padding: int = 10,
    text_position: Position = Position.TOP_LEFT,
    text_offset: tuple[int, int] = (0, 0),
    border_radius: int = 0,
    smart_position: bool = False,
    max_line_length: int | None = None,
):
    """
    Args:
        color: The color or color palette to use for
            annotating the text background.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        text_color: The color or color palette to use
            for the text.
        text_scale: Font scale for the text.
        text_thickness: Thickness of the text characters.
        text_padding: Padding around the text within its background box.
        text_position: Position of the text relative to the detection.
            Possible values are defined in the
            :class:`~supervision.geometry.core.Position` enum.
        text_offset: A tuple of 2D coordinates `(x, y)` to
            offset the text position from the anchor point, in pixels.
        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.
        max_line_length: Maximum number of characters per line
            before wrapping the text. None means no wrapping.
    """
    self.text_scale: float = text_scale
    self.text_thickness: int = text_thickness
    super().__init__(
        color=color,
        color_lookup=color_lookup,
        text_color=text_color,
        text_padding=text_padding,
        text_position=text_position,
        text_offset=text_offset,
        border_radius=border_radius,
        smart_position=smart_position,
        max_line_length=max_line_length,
    )

annotate(scene: ImageType, detections: Detections, labels: list[str] | None = None, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with labels based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
labels
list[str] | None

Custom labels for each detection.

None
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     confidence=np.array([0.9]),
...     class_id=np.array([0]),
...     data={'class_name': np.array(['person'])}
... )
>>> labels = [
...     f"{class_name} {confidence:.2f}"
...     for class_name, confidence
...     in zip(detections['class_name'], detections.confidence)
... ]
>>> label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
>>> annotated_frame = label_annotator.annotate(
...     scene=image.copy(),
...     detections=detections,
...     labels=labels
... )

label-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    labels: list[str] | None = None,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with labels based on the provided detections.

    Args:
        scene: The image where labels will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        labels: Custom labels for each detection.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     confidence=np.array([0.9]),
        ...     class_id=np.array([0]),
        ...     data={'class_name': np.array(['person'])}
        ... )
        >>> labels = [
        ...     f"{class_name} {confidence:.2f}"
        ...     for class_name, confidence
        ...     in zip(detections['class_name'], detections.confidence)
        ... ]
        >>> label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
        >>> annotated_frame = label_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections,
        ...     labels=labels
        ... )

        ```

    ![label-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/label-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    _validate_labels(labels, detections)

    labels = get_labels_text(detections, labels)
    label_properties: npt.NDArray[np.float32] = self._get_label_properties(
        detections, labels
    )

    if self.smart_position:
        label_properties = self._adjust_labels_in_frame(
            (scene.shape[1], scene.shape[0]),
            labels,
            label_properties,
        )

    self._draw_labels(
        scene=scene,
        labels=labels,
        label_properties=label_properties,
        detections=detections,
        custom_color_lookup=custom_color_lookup,
    )

    return scene

draw_rounded_rectangle(scene: npt.NDArray[np.uint8], xyxy: tuple[int, int, int, int], color: tuple[int, ...], border_radius: int) -> npt.NDArray[np.uint8] staticmethod

Draw a filled rectangle with optional rounded corners on an image.

Parameters:

Name Type Description Default
scene
NDArray[uint8]

BGR image array to draw on; modified in-place and returned.

required
xyxy
tuple[int, int, int, int]

Bounding box as (x1, y1, x2, y2) pixel coordinates.

required
color
tuple[int, ...]

Fill color as a BGR tuple (e.g. (0, 0, 255) for red), or a BGRA tuple for a BGRA scene.

required
border_radius
int

Corner rounding radius in pixels. Values <= 0 (including values clamped to 0 by a degenerate box) draw a plain filled rectangle with square corners.

required

Returns:

Type Description
NDArray[uint8]

The annotated scene array.

Example
>>> import numpy as np
>>> import supervision as sv
>>> scene = np.zeros((200, 200, 3), dtype=np.uint8)
>>> scene = sv.LabelAnnotator.draw_rounded_rectangle(
...     scene=scene,
...     xyxy=(10, 10, 100, 50),
...     color=(0, 255, 0),
...     border_radius=0,
... )
>>> bool(scene[30, 50].tolist() == [0, 255, 0])
True
Source code in src/supervision/annotators/core.py
@staticmethod
def draw_rounded_rectangle(
    scene: npt.NDArray[np.uint8],
    xyxy: tuple[int, int, int, int],
    color: tuple[int, ...],
    border_radius: int,
) -> npt.NDArray[np.uint8]:
    """Draw a filled rectangle with optional rounded corners on an image.

    Args:
        scene: BGR image array to draw on; modified in-place and returned.
        xyxy: Bounding box as (x1, y1, x2, y2) pixel coordinates.
        color: Fill color as a BGR tuple (e.g. ``(0, 0, 255)`` for red), or a
            BGRA tuple for a BGRA ``scene``.
        border_radius: Corner rounding radius in pixels. Values <= 0
            (including values clamped to 0 by a degenerate box) draw a
            plain filled rectangle with square corners.

    Returns:
        The annotated ``scene`` array.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> scene = np.zeros((200, 200, 3), dtype=np.uint8)
        >>> scene = sv.LabelAnnotator.draw_rounded_rectangle(
        ...     scene=scene,
        ...     xyxy=(10, 10, 100, 50),
        ...     color=(0, 255, 0),
        ...     border_radius=0,
        ... )
        >>> bool(scene[30, 50].tolist() == [0, 255, 0])
        True

        ```
    """
    x1, y1, x2, y2 = xyxy
    width = x2 - x1
    height = y2 - y1

    border_radius = min(border_radius, min(width, height) // 2)

    if border_radius <= 0:
        # square corners: a single fill rectangle (the common default), rather
        # than two rectangles plus four zero-radius corner circles
        cv2.rectangle(
            img=scene,
            pt1=(x1, y1),
            pt2=(x2, y2),
            color=color,
            thickness=-1,
        )
        return scene

    rectangle_coordinates = [
        ((x1 + border_radius, y1), (x2 - border_radius, y2)),
        ((x1, y1 + border_radius), (x2, y2 - border_radius)),
    ]
    circle_centers = [
        (x1 + border_radius, y1 + border_radius),
        (x2 - border_radius, y1 + border_radius),
        (x1 + border_radius, y2 - border_radius),
        (x2 - border_radius, y2 - border_radius),
    ]

    for coordinates in rectangle_coordinates:
        cv2.rectangle(
            img=scene,
            pt1=coordinates[0],
            pt2=coordinates[1],
            color=color,
            thickness=-1,
        )
    for center in circle_centers:
        cv2.circle(
            img=scene,
            center=center,
            radius=border_radius,
            color=color,
            thickness=-1,
        )
    return scene

supervision.annotators.core.RichLabelAnnotator

Bases: _BaseLabelAnnotator

A class for annotating labels on an image using provided detections, with support for Unicode characters by using a custom font.

Source code in src/supervision/annotators/core.py
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
class RichLabelAnnotator(_BaseLabelAnnotator):
    """A class for annotating labels on an image using provided detections, with support
    for Unicode characters by using a custom font."""

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        color_lookup: ColorLookup = ColorLookup.CLASS,
        text_color: Color | ColorPalette | str = Color.WHITE,
        font_path: str | None = None,
        font_size: int = 10,
        text_padding: int = 10,
        text_position: Position = Position.TOP_LEFT,
        text_offset: tuple[int, int] = (0, 0),
        border_radius: int = 0,
        smart_position: bool = False,
        max_line_length: int | None = None,
    ):
        """
        Args:
            color: The color or color palette to use for
                annotating the text background.
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
            text_color: The color to use for the text.
            font_path: Path to the font file (e.g., ".ttf" or ".otf")
                to use for rendering text. If `None`, the default PIL font will be used.
                With the `rtl` extra installed, Arabic and Hebrew lines in RGB or
                RGBA images are drawn with `khatt`, using this font when supplied.
                Missing glyphs use Noto Naskh Arabic or Rubik (Hebrew). Other image
                modes fall back to Pillow, which requires Raqm for shaping and may
                not support every image mode.
            font_size: Font size for the text.
            text_padding: Padding around the text within its background box.
            text_position: Position of the text relative to the detection.
                Possible values are defined in the
                :class:`~supervision.geometry.core.Position` enum.
            text_offset: A tuple of 2D coordinates `(x, y)` to
                offset the text position from the anchor point, in pixels.
            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.
            max_line_length: Maximum number of characters per line
                before wrapping the text. None means no wrapping.
        """
        self.font_path = font_path
        self.font_size = font_size
        self.font = self._load_font(font_size, font_path)
        # khatt draws in the font file Pillow loaded (which may be resolved from a
        # system font directory), or its bundled Arabic font when the default PIL
        # font (no Arabic glyphs, loaded from memory) is in use
        loaded_path = getattr(self.font, "path", None)
        self._rtl_font = loaded_path if isinstance(loaded_path, str) else None
        super().__init__(
            color=color,
            color_lookup=color_lookup,
            text_color=text_color,
            text_padding=text_padding,
            text_position=text_position,
            text_offset=text_offset,
            border_radius=border_radius,
            smart_position=smart_position,
            max_line_length=max_line_length,
        )

    @ensure_pil_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        labels: list[str] | None = None,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the given scene with labels based on the provided detections, with
        support for Unicode characters.

        Args:
            scene: The image where labels will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale scenes, shaped `(H, W)` or
                `(H, W, 1)` or given as a Pillow grayscale image (`1`, `L`, `LA`,
                `I`, `F` or `I;16`), are supported.
            detections: Object detections to annotate.
            labels: Custom labels for each detection.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> from PIL import Image
            >>> image = Image.fromarray(np.zeros((100, 100, 3), dtype=np.uint8))
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     confidence=np.array([0.9]),
            ...     class_id=np.array([0]),
            ...     data={'class_name': np.array(['person'])}
            ... )
            >>> labels = [
            ...     f"{class_name} {confidence:.2f}"
            ...     for class_name, confidence
            ...     in zip(detections['class_name'], detections.confidence)
            ... ]
            >>> rich_label_annotator = sv.RichLabelAnnotator()
            >>> annotated_frame = rich_label_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections,
            ...     labels=labels
            ... )

            ```
        """
        _validate_labels(labels, detections)

        draw = ImageDraw.Draw(scene)
        labels = get_labels_text(detections, labels)
        label_properties: npt.NDArray[np.float32] = self._get_label_properties(
            draw, detections, labels
        )

        if self.smart_position:
            scene_pil = cast(Image.Image, scene)
            label_properties = self._adjust_labels_in_frame(
                (scene_pil.width, scene_pil.height),
                labels,
                label_properties,
            )

        self._draw_labels(
            scene=cast(Image.Image, scene),
            draw=draw,
            labels=labels,
            label_properties=label_properties,
            detections=detections,
            custom_color_lookup=custom_color_lookup,
        )

        return scene

    def _rtl_engine(self, draw: ImageDraw.ImageDraw, line: str) -> ModuleType | None:
        """The `khatt` module when `line` holds right-to-left text, the scene is RGB or
        RGBA and the `rtl` extra is installed, else `None` (the line is measured and
        drawn by Pillow)."""
        if not _RTL_TEXT.search(line):
            return None
        if draw.mode not in ("RGB", "RGBA"):
            _warn_unshaped_rtl_text(unsupported_mode=True)
            return None
        try:
            return importlib.import_module("khatt")
        except ModuleNotFoundError as exc:
            if exc.name != "khatt":
                raise
            _warn_unshaped_rtl_text()
            return None

    def _rtl_options(self) -> dict[str, Any]:
        # khatt's bundled Noto Naskh Arabic and Rubik (Hebrew) cover characters
        # the label font lacks
        if self._rtl_font is None:
            return {
                "font": "noto-naskh",
                "size_px": self.font_size,
                "fallback_fonts": ("rubik",),
            }
        return {
            "font": self._rtl_font,
            "size_px": self.font_size,
            "fallback_fonts": ("noto-naskh", "rubik"),
        }

    def _text_bbox(
        self, draw: ImageDraw.ImageDraw, line: str
    ) -> tuple[float, float, float, float]:
        khatt = self._rtl_engine(draw, line)
        if khatt is not None:
            left, top, right, bottom = khatt.text_bbox(line, **self._rtl_options())
        else:
            left, top, right, bottom = draw.textbbox((0, 0), line, font=self.font)
        return left, top, right, bottom

    def _get_label_properties(
        self, draw: ImageDraw.ImageDraw, detections: Detections, labels: list[str]
    ) -> Any:
        label_properties = []

        anchor_coordinates: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
            anchor=self.text_anchor
        ).astype(int)

        for label, center_coordinates in zip(labels, anchor_coordinates):
            center_coordinates = (
                center_coordinates[0] + self.text_offset[0],
                center_coordinates[1] + self.text_offset[1],
            )

            wrapped_lines = wrap_text(label, self.max_line_length)

            # Calculate the total text height and maximum width
            max_width = 0.0
            total_height = 0.0

            for line in wrapped_lines:
                left, top, right, bottom = self._text_bbox(draw, line)
                line_width = right - left
                line_height = bottom - top

                max_width = max(max_width, line_width)
                total_height += line_height

            # Add inter-line spacing
            if len(wrapped_lines) > 1:
                total_height += (len(wrapped_lines) - 1) * self.text_padding

            width_padded = int(max_width + 2 * self.text_padding)
            height_padded = int(total_height + 2 * self.text_padding)

            text_background_xyxy = resolve_text_background_xyxy(
                center_coordinates=center_coordinates,
                text_wh=(width_padded, height_padded),
                position=self.text_anchor,
            )

            # Get the text origin offsets
            text_left, text_top, _, _ = draw.textbbox((0, 0), "Tg", font=self.font)

            label_properties.append([*text_background_xyxy, text_left, text_top])

        result: npt.NDArray[np.float32] = np.array(
            label_properties, dtype=np.float32
        ).reshape(-1, 6)
        return result

    def _draw_labels(
        self,
        scene: Image.Image,
        draw: ImageDraw.ImageDraw,
        labels: list[str],
        label_properties: npt.NDArray[np.float32],
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None,
    ) -> None:
        """Draw each label's background and text in a fill valid for `scene.mode`."""
        assert len(labels) == len(label_properties) == len(detections), (
            f"Number of label properties ({len(label_properties)}), "
            f"labels ({len(labels)}) and detections ({len(detections)}) "
            "do not match."
        )
        color_lookup = (
            custom_color_lookup
            if custom_color_lookup is not None
            else self.color_lookup
        )

        for idx, label_property in enumerate(label_properties):
            background_color = _resolve_detection_color(
                color=self.color,
                detections=detections,
                detection_idx=idx,
                color_lookup=color_lookup,
            )
            text_color = _resolve_detection_color(
                color=self.text_color,
                detections=detections,
                detection_idx=idx,
                color_lookup=color_lookup,
            )

            box_xyxy = label_property[:4].astype(int)

            # Draw the rounded rectangle background
            draw.rounded_rectangle(
                tuple(box_xyxy),
                radius=self.border_radius,
                fill=_pillow_fill(background_color, scene.mode),
                outline=None,
            )

            # Draw each line of text
            wrapped_lines = wrap_text(labels[idx], self.max_line_length)
            # The box is sized from each line's measured ink, so each line is placed
            # by its own bounds too. A shared "Tg" origin put a low glyph, such as a
            # period, below a tightly padded box.
            ink_top = box_xyxy[1] + self.text_padding

            for line in wrapped_lines:
                left, top, right, bottom = self._text_bbox(draw, line)
                khatt = self._rtl_engine(draw, line)
                if khatt is not None:
                    # Right-aligned in the box. Oversized boxes extend beyond the
                    # frame, so align shaped RTL text to the visible right edge
                    # instead.
                    right_edge = box_xyxy[2]
                    if self.smart_position and box_xyxy[2] - box_xyxy[0] > scene.width:
                        right_edge = min(right_edge, scene.width)
                    khatt.draw_text(
                        scene,
                        (right_edge - self.text_padding - right, ink_top - top),
                        line,
                        fill=text_color.as_rgb(),
                        **self._rtl_options(),
                    )
                else:
                    draw.text(
                        xy=(box_xyxy[0] + self.text_padding - left, ink_top - top),
                        text=line,
                        font=self.font,
                        fill=_pillow_fill(text_color, scene.mode),
                    )

                # Move to the next line position
                ink_top += bottom - top + self.text_padding

    @staticmethod
    def _load_font(
        font_size: int, font_path: str | None
    ) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
        def load_default_font(
            size: int,
        ) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
            try:
                return ImageFont.load_default(size)
            except TypeError:
                return ImageFont.load_default()

        if font_path is None:
            return load_default_font(font_size)

        try:
            return ImageFont.truetype(font_path, font_size)
        except OSError:
            logger.warning(
                "Font path '%s' not found. Using PIL's default font.", font_path
            )
            return load_default_font(font_size)

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, color_lookup: ColorLookup = ColorLookup.CLASS, text_color: Color | ColorPalette | str = Color.WHITE, font_path: str | None = None, font_size: int = 10, text_padding: int = 10, text_position: Position = Position.TOP_LEFT, text_offset: tuple[int, int] = (0, 0), border_radius: int = 0, smart_position: bool = False, max_line_length: int | None = None)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color or color palette to use for annotating the text background.

DEFAULT
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
text_color
Color | ColorPalette | str

The color to use for the text.

WHITE
font_path
str | None

Path to the font file (e.g., ".ttf" or ".otf") to use for rendering text. If None, the default PIL font will be used. With the rtl extra installed, Arabic and Hebrew lines in RGB or RGBA images are drawn with khatt, using this font when supplied. Missing glyphs use Noto Naskh Arabic or Rubik (Hebrew). Other image modes fall back to Pillow, which requires Raqm for shaping and may not support every image mode.

None
font_size
int

Font size for the text.

10
text_padding
int

Padding around the text within its background box.

10
text_position
Position

Position of the text relative to the detection. Possible values are defined in the :class:~supervision.geometry.core.Position enum.

TOP_LEFT
text_offset
tuple[int, int]

A tuple of 2D coordinates (x, y) to offset the text position from the anchor point, in pixels.

(0, 0)
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
max_line_length
int | None

Maximum number of characters per line before wrapping the text. None means no wrapping.

None
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    color_lookup: ColorLookup = ColorLookup.CLASS,
    text_color: Color | ColorPalette | str = Color.WHITE,
    font_path: str | None = None,
    font_size: int = 10,
    text_padding: int = 10,
    text_position: Position = Position.TOP_LEFT,
    text_offset: tuple[int, int] = (0, 0),
    border_radius: int = 0,
    smart_position: bool = False,
    max_line_length: int | None = None,
):
    """
    Args:
        color: The color or color palette to use for
            annotating the text background.
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
        text_color: The color to use for the text.
        font_path: Path to the font file (e.g., ".ttf" or ".otf")
            to use for rendering text. If `None`, the default PIL font will be used.
            With the `rtl` extra installed, Arabic and Hebrew lines in RGB or
            RGBA images are drawn with `khatt`, using this font when supplied.
            Missing glyphs use Noto Naskh Arabic or Rubik (Hebrew). Other image
            modes fall back to Pillow, which requires Raqm for shaping and may
            not support every image mode.
        font_size: Font size for the text.
        text_padding: Padding around the text within its background box.
        text_position: Position of the text relative to the detection.
            Possible values are defined in the
            :class:`~supervision.geometry.core.Position` enum.
        text_offset: A tuple of 2D coordinates `(x, y)` to
            offset the text position from the anchor point, in pixels.
        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.
        max_line_length: Maximum number of characters per line
            before wrapping the text. None means no wrapping.
    """
    self.font_path = font_path
    self.font_size = font_size
    self.font = self._load_font(font_size, font_path)
    # khatt draws in the font file Pillow loaded (which may be resolved from a
    # system font directory), or its bundled Arabic font when the default PIL
    # font (no Arabic glyphs, loaded from memory) is in use
    loaded_path = getattr(self.font, "path", None)
    self._rtl_font = loaded_path if isinstance(loaded_path, str) else None
    super().__init__(
        color=color,
        color_lookup=color_lookup,
        text_color=text_color,
        text_padding=text_padding,
        text_position=text_position,
        text_offset=text_offset,
        border_radius=border_radius,
        smart_position=smart_position,
        max_line_length=max_line_length,
    )

annotate(scene: ImageType, detections: Detections, labels: list[str] | None = None, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the given scene with labels based on the provided detections, with support for Unicode characters.

Parameters:

Name Type Description Default
scene
ImageType

The image where labels will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale scenes, shaped (H, W) or (H, W, 1) or given as a Pillow grayscale image (1, L, LA, I, F or I;16), are supported.

required
detections
Detections

Object detections to annotate.

required
labels
list[str] | None

Custom labels for each detection.

None
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> from PIL import Image
>>> image = Image.fromarray(np.zeros((100, 100, 3), dtype=np.uint8))
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     confidence=np.array([0.9]),
...     class_id=np.array([0]),
...     data={'class_name': np.array(['person'])}
... )
>>> labels = [
...     f"{class_name} {confidence:.2f}"
...     for class_name, confidence
...     in zip(detections['class_name'], detections.confidence)
... ]
>>> rich_label_annotator = sv.RichLabelAnnotator()
>>> annotated_frame = rich_label_annotator.annotate(
...     scene=image.copy(),
...     detections=detections,
...     labels=labels
... )
Source code in src/supervision/annotators/core.py
@ensure_pil_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    labels: list[str] | None = None,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the given scene with labels based on the provided detections, with
    support for Unicode characters.

    Args:
        scene: The image where labels will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale scenes, shaped `(H, W)` or
            `(H, W, 1)` or given as a Pillow grayscale image (`1`, `L`, `LA`,
            `I`, `F` or `I;16`), are supported.
        detections: Object detections to annotate.
        labels: Custom labels for each detection.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from PIL import Image
        >>> image = Image.fromarray(np.zeros((100, 100, 3), dtype=np.uint8))
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     confidence=np.array([0.9]),
        ...     class_id=np.array([0]),
        ...     data={'class_name': np.array(['person'])}
        ... )
        >>> labels = [
        ...     f"{class_name} {confidence:.2f}"
        ...     for class_name, confidence
        ...     in zip(detections['class_name'], detections.confidence)
        ... ]
        >>> rich_label_annotator = sv.RichLabelAnnotator()
        >>> annotated_frame = rich_label_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections,
        ...     labels=labels
        ... )

        ```
    """
    _validate_labels(labels, detections)

    draw = ImageDraw.Draw(scene)
    labels = get_labels_text(detections, labels)
    label_properties: npt.NDArray[np.float32] = self._get_label_properties(
        draw, detections, labels
    )

    if self.smart_position:
        scene_pil = cast(Image.Image, scene)
        label_properties = self._adjust_labels_in_frame(
            (scene_pil.width, scene_pil.height),
            labels,
            label_properties,
        )

    self._draw_labels(
        scene=cast(Image.Image, scene),
        draw=draw,
        labels=labels,
        label_properties=label_properties,
        detections=detections,
        custom_color_lookup=custom_color_lookup,
    )

    return scene

supervision.annotators.core.IconAnnotator

Bases: BaseAnnotator

A class for drawing an icon on an image, using provided detections.

Source code in src/supervision/annotators/core.py
class IconAnnotator(BaseAnnotator):
    """A class for drawing an icon on an image, using provided detections."""

    def __init__(
        self,
        icon_resolution_wh: tuple[int, int] = (64, 64),
        icon_position: Position = Position.TOP_CENTER,
        offset_xy: tuple[int, int] = (0, 0),
    ):
        """
        Args:
            icon_resolution_wh: The size of drawn icons.
                All icons will be resized to this resolution, keeping the aspect ratio.
            icon_position: The position of the icon.
            offset_xy: The offset to apply to the icon position,
                in pixels. Can be both positive and negative.
        """
        self.icon_resolution_wh = icon_resolution_wh
        self.position = icon_position
        self.offset_xy = offset_xy

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        icon_path: str | list[str] = "",
    ) -> ImageType:
        """Annotates the given scene with given icons.

        Args:
            scene: The image where labels will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            icon_path: The path to the PNG image to use as an
                icon. Must be a single path or a list of paths, one for each detection.
                Pass an empty string `""` to draw nothing.

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

        Example:
            ```python
            import numpy as np
            import supervision as sv

            image = ...
            detections = sv.Detections(...)

            available_icons = ["roboflow.png", "lenny.png"]
            icon_paths = [np.random.choice(available_icons) for _ in detections]

            icon_annotator = sv.IconAnnotator()
            annotated_frame = icon_annotator.annotate(
                scene=image.copy(),
                detections=detections,
                icon_path=icon_paths
            )
            ```

        ![icon-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/icon-annotator-example.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if isinstance(icon_path, list) and len(icon_path) != len(detections):
            raise ValueError(
                f"The number of icon paths provided ({len(icon_path)}) does not match "
                f"the number of detections ({len(detections)}). Either provide a single"
                f" icon path or one for each detection."
            )

        xy: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
            anchor=self.position
        ).astype(int)

        for detection_idx in range(len(detections)):
            current_path = (
                icon_path if isinstance(icon_path, str) else icon_path[detection_idx]
            )
            if current_path == "":
                continue
            icon = self._load_icon(current_path)
            icon_h, icon_w = icon.shape[:2]

            x = int(xy[detection_idx, 0] - icon_w / 2 + self.offset_xy[0])
            y = int(xy[detection_idx, 1] - icon_h / 2 + self.offset_xy[1])

            scene[:] = _overlay_image(scene, icon, (x, y))
        return scene

    def _load_icon(self, icon_path: str) -> npt.NDArray[np.uint8]:
        """Load an icon through the module-level cache shared by annotators."""
        return _load_icon_from_path(
            icon_path=icon_path, icon_resolution_wh=self.icon_resolution_wh
        )

Methods:

__init__(icon_resolution_wh: tuple[int, int] = (64, 64), icon_position: Position = Position.TOP_CENTER, offset_xy: tuple[int, int] = (0, 0))

Parameters:

Name Type Description Default
icon_resolution_wh
tuple[int, int]

The size of drawn icons. All icons will be resized to this resolution, keeping the aspect ratio.

(64, 64)
icon_position
Position

The position of the icon.

TOP_CENTER
offset_xy
tuple[int, int]

The offset to apply to the icon position, in pixels. Can be both positive and negative.

(0, 0)
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    icon_resolution_wh: tuple[int, int] = (64, 64),
    icon_position: Position = Position.TOP_CENTER,
    offset_xy: tuple[int, int] = (0, 0),
):
    """
    Args:
        icon_resolution_wh: The size of drawn icons.
            All icons will be resized to this resolution, keeping the aspect ratio.
        icon_position: The position of the icon.
        offset_xy: The offset to apply to the icon position,
            in pixels. Can be both positive and negative.
    """
    self.icon_resolution_wh = icon_resolution_wh
    self.position = icon_position
    self.offset_xy = offset_xy

annotate(scene: ImageType, detections: Detections, icon_path: str | list[str] = '') -> ImageType

Annotates the given scene with given icons.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required
icon_path
str | list[str]

The path to the PNG image to use as an icon. Must be a single path or a list of paths, one for each detection. Pass an empty string "" to draw nothing.

''

Returns:

Type Description
ImageType

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

Example
import numpy as np
import supervision as sv

image = ...
detections = sv.Detections(...)

available_icons = ["roboflow.png", "lenny.png"]
icon_paths = [np.random.choice(available_icons) for _ in detections]

icon_annotator = sv.IconAnnotator()
annotated_frame = icon_annotator.annotate(
    scene=image.copy(),
    detections=detections,
    icon_path=icon_paths
)

icon-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    icon_path: str | list[str] = "",
) -> ImageType:
    """Annotates the given scene with given icons.

    Args:
        scene: The image where labels will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        icon_path: The path to the PNG image to use as an
            icon. Must be a single path or a list of paths, one for each detection.
            Pass an empty string `""` to draw nothing.

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

    Example:
        ```python
        import numpy as np
        import supervision as sv

        image = ...
        detections = sv.Detections(...)

        available_icons = ["roboflow.png", "lenny.png"]
        icon_paths = [np.random.choice(available_icons) for _ in detections]

        icon_annotator = sv.IconAnnotator()
        annotated_frame = icon_annotator.annotate(
            scene=image.copy(),
            detections=detections,
            icon_path=icon_paths
        )
        ```

    ![icon-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/icon-annotator-example.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if isinstance(icon_path, list) and len(icon_path) != len(detections):
        raise ValueError(
            f"The number of icon paths provided ({len(icon_path)}) does not match "
            f"the number of detections ({len(detections)}). Either provide a single"
            f" icon path or one for each detection."
        )

    xy: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
        anchor=self.position
    ).astype(int)

    for detection_idx in range(len(detections)):
        current_path = (
            icon_path if isinstance(icon_path, str) else icon_path[detection_idx]
        )
        if current_path == "":
            continue
        icon = self._load_icon(current_path)
        icon_h, icon_w = icon.shape[:2]

        x = int(xy[detection_idx, 0] - icon_w / 2 + self.offset_xy[0])
        y = int(xy[detection_idx, 1] - icon_h / 2 + self.offset_xy[1])

        scene[:] = _overlay_image(scene, icon, (x, y))
    return scene

supervision.annotators.core.BlurAnnotator

Bases: BaseAnnotator

A class for blurring regions in an image using provided detections.

Source code in src/supervision/annotators/core.py
class BlurAnnotator(BaseAnnotator):
    """A class for blurring regions in an image using provided detections."""

    def __init__(self, kernel_size: int | None = None):
        """
        Args:
            kernel_size: The size of the average pooling kernel used for blurring.
                If not set, a dynamic size is computed as one-third of the shorter
                bounding-box dimension. Must be >= 1 when provided.
        """
        if kernel_size is not None and kernel_size < 1:
            raise ValueError(f"kernel_size must be >= 1, got {kernel_size}.")
        self.kernel_size: int | None = kernel_size

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
    ) -> ImageType:
        """Annotates the given scene by blurring regions based on the provided
        detections.

        Args:
            scene: The image where blurring will be applied.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
                or `(H, W, 1)`.
            detections: Object detections to annotate.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> blur_annotator = sv.BlurAnnotator()
            >>> annotated_frame = blur_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![blur-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/blur-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        image_height, image_width = scene.shape[:2]
        clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
            xyxy=detections.xyxy,
            resolution_wh=(image_width, image_height),
        ).astype(int)

        for x1, y1, x2, y2 in clipped_xyxy:
            if x2 <= x1 or y2 <= y1:
                continue
            roi = scene[y1:y2, x1:x2]
            kernel_size = (
                self.kernel_size
                if self.kernel_size is not None
                else calculate_dynamic_kernel_size(x1, y1, x2, y2)
            )
            blurred_roi = cast(
                npt.NDArray[np.uint8], cv2.blur(roi, (kernel_size, kernel_size))
            )
            # OpenCV drops a singleton channel axis; restore it before assignment.
            scene[y1:y2, x1:x2] = blurred_roi.reshape(roi.shape)

        return scene

Methods:

__init__(kernel_size: int | None = None)

Parameters:

Name Type Description Default
kernel_size
int | None

The size of the average pooling kernel used for blurring. If not set, a dynamic size is computed as one-third of the shorter bounding-box dimension. Must be >= 1 when provided.

None
Source code in src/supervision/annotators/core.py
def __init__(self, kernel_size: int | None = None):
    """
    Args:
        kernel_size: The size of the average pooling kernel used for blurring.
            If not set, a dynamic size is computed as one-third of the shorter
            bounding-box dimension. Must be >= 1 when provided.
    """
    if kernel_size is not None and kernel_size < 1:
        raise ValueError(f"kernel_size must be >= 1, got {kernel_size}.")
    self.kernel_size: int | None = kernel_size

annotate(scene: ImageType, detections: Detections) -> ImageType

Annotates the given scene by blurring regions based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

The image where blurring will be applied. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale arrays may have shape (H, W) or (H, W, 1).

required
detections
Detections

Object detections to annotate.

required

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> blur_annotator = sv.BlurAnnotator()
>>> annotated_frame = blur_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

blur-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
) -> ImageType:
    """Annotates the given scene by blurring regions based on the provided
    detections.

    Args:
        scene: The image where blurring will be applied.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
            or `(H, W, 1)`.
        detections: Object detections to annotate.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> blur_annotator = sv.BlurAnnotator()
        >>> annotated_frame = blur_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![blur-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/blur-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    image_height, image_width = scene.shape[:2]
    clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
        xyxy=detections.xyxy,
        resolution_wh=(image_width, image_height),
    ).astype(int)

    for x1, y1, x2, y2 in clipped_xyxy:
        if x2 <= x1 or y2 <= y1:
            continue
        roi = scene[y1:y2, x1:x2]
        kernel_size = (
            self.kernel_size
            if self.kernel_size is not None
            else calculate_dynamic_kernel_size(x1, y1, x2, y2)
        )
        blurred_roi = cast(
            npt.NDArray[np.uint8], cv2.blur(roi, (kernel_size, kernel_size))
        )
        # OpenCV drops a singleton channel axis; restore it before assignment.
        scene[y1:y2, x1:x2] = blurred_roi.reshape(roi.shape)

    return scene

supervision.annotators.core.PixelateAnnotator

Bases: BaseAnnotator

A class for pixelating regions in an image using provided detections.

Source code in src/supervision/annotators/core.py
class PixelateAnnotator(BaseAnnotator):
    """A class for pixelating regions in an image using provided detections."""

    def __init__(self, pixel_size: int | None = None):
        """
        Args:
            pixel_size: The size of the pixelation. If not set, a dynamic size is
                computed as one-half of the shorter bounding-box dimension. When set
                and the detection area is smaller than `pixel_size`, the region is
                filled with its average colour instead to avoid an OpenCV crash.
                Must be >= 1 when provided.
        """
        if pixel_size is not None and pixel_size < 1:
            raise ValueError(f"pixel_size must be >= 1, got {pixel_size}.")
        self.pixel_size: int | None = pixel_size

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
    ) -> ImageType:
        """Annotates the given scene by pixelating regions based on the provided
        detections.

        Args:
            scene: The image where pixelating will be applied.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
                or `(H, W, 1)`.
            detections: Object detections to annotate.

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

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0]),
            ... )
            >>> pixelate_annotator = sv.PixelateAnnotator()
            >>> annotated_frame = pixelate_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![pixelate-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/pixelate-annotator-example-10.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        image_height, image_width = scene.shape[:2]
        clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
            xyxy=detections.xyxy,
            resolution_wh=(image_width, image_height),
        ).astype(int)

        for x1, y1, x2, y2 in clipped_xyxy:
            if x2 <= x1 or y2 <= y1:
                continue
            roi = scene[y1:y2, x1:x2]

            pixel_size = (
                self.pixel_size
                if self.pixel_size is not None
                else calculate_dynamic_pixel_size(x1, y1, x2, y2)
            )
            if min(y2 - y1, x2 - x1) < pixel_size:
                if roi.ndim == 2 or (roi.ndim == 3 and roi.shape[2] == 1):
                    scene[y1:y2, x1:x2] = cv2.mean(roi)[0]
                else:
                    num_channels = scene.shape[2]
                    scene[y1:y2, x1:x2] = cv2.mean(roi)[:num_channels]
                continue

            scaled_up_roi = cv2.resize(
                src=roi, dsize=None, fx=1 / pixel_size, fy=1 / pixel_size
            )
            scaled_down_roi = cv2.resize(
                src=scaled_up_roi,
                dsize=(roi.shape[1], roi.shape[0]),
                interpolation=cv2.INTER_NEAREST,
            )

            # OpenCV drops a singleton channel axis; restore it before assignment.
            scene[y1:y2, x1:x2] = scaled_down_roi.reshape(roi.shape)

        return scene

Methods:

__init__(pixel_size: int | None = None)

Parameters:

Name Type Description Default
pixel_size
int | None

The size of the pixelation. If not set, a dynamic size is computed as one-half of the shorter bounding-box dimension. When set and the detection area is smaller than pixel_size, the region is filled with its average colour instead to avoid an OpenCV crash. Must be >= 1 when provided.

None
Source code in src/supervision/annotators/core.py
def __init__(self, pixel_size: int | None = None):
    """
    Args:
        pixel_size: The size of the pixelation. If not set, a dynamic size is
            computed as one-half of the shorter bounding-box dimension. When set
            and the detection area is smaller than `pixel_size`, the region is
            filled with its average colour instead to avoid an OpenCV crash.
            Must be >= 1 when provided.
    """
    if pixel_size is not None and pixel_size < 1:
        raise ValueError(f"pixel_size must be >= 1, got {pixel_size}.")
    self.pixel_size: int | None = pixel_size

annotate(scene: ImageType, detections: Detections) -> ImageType

Annotates the given scene by pixelating regions based on the provided detections.

Parameters:

Name Type Description Default
scene
ImageType

The image where pixelating will be applied. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale arrays may have shape (H, W) or (H, W, 1).

required
detections
Detections

Object detections to annotate.

required

Returns:

Type Description
ImageType

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

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0]),
... )
>>> pixelate_annotator = sv.PixelateAnnotator()
>>> annotated_frame = pixelate_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

pixelate-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
) -> ImageType:
    """Annotates the given scene by pixelating regions based on the provided
    detections.

    Args:
        scene: The image where pixelating will be applied.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
            or `(H, W, 1)`.
        detections: Object detections to annotate.

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

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0]),
        ... )
        >>> pixelate_annotator = sv.PixelateAnnotator()
        >>> annotated_frame = pixelate_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![pixelate-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/pixelate-annotator-example-10.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    image_height, image_width = scene.shape[:2]
    clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
        xyxy=detections.xyxy,
        resolution_wh=(image_width, image_height),
    ).astype(int)

    for x1, y1, x2, y2 in clipped_xyxy:
        if x2 <= x1 or y2 <= y1:
            continue
        roi = scene[y1:y2, x1:x2]

        pixel_size = (
            self.pixel_size
            if self.pixel_size is not None
            else calculate_dynamic_pixel_size(x1, y1, x2, y2)
        )
        if min(y2 - y1, x2 - x1) < pixel_size:
            if roi.ndim == 2 or (roi.ndim == 3 and roi.shape[2] == 1):
                scene[y1:y2, x1:x2] = cv2.mean(roi)[0]
            else:
                num_channels = scene.shape[2]
                scene[y1:y2, x1:x2] = cv2.mean(roi)[:num_channels]
            continue

        scaled_up_roi = cv2.resize(
            src=roi, dsize=None, fx=1 / pixel_size, fy=1 / pixel_size
        )
        scaled_down_roi = cv2.resize(
            src=scaled_up_roi,
            dsize=(roi.shape[1], roi.shape[0]),
            interpolation=cv2.INTER_NEAREST,
        )

        # OpenCV drops a singleton channel axis; restore it before assignment.
        scene[y1:y2, x1:x2] = scaled_down_roi.reshape(roi.shape)

    return scene

supervision.annotators.core.TraceAnnotator

Bases: BaseAnnotator

A class for drawing trace paths on an image based on detection coordinates.

Warning

This annotator uses the :class:~supervision.detection.core.Detections.tracker_id. Read here to learn how to plug tracking into your inference pipeline.

Source code in src/supervision/annotators/core.py
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
class TraceAnnotator(BaseAnnotator):
    """A class for drawing trace paths on an image based on detection coordinates.

    !!! warning

    This annotator uses the
    :class:`~supervision.detection.core.Detections`.tracker_id. Read [here](
    https://trackers.roboflow.com/latest/)
    to learn how to plug
    tracking into your inference pipeline.
    """

    def __init__(
        self,
        color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        position: Position = Position.CENTER,
        trace_length: int = 30,
        thickness: int = 2,
        smooth: bool = False,
        color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            color: The color to draw the trace, can be
                a single color or a color palette.
            position: The position of the trace.
                Defaults to `CENTER`.
            trace_length: The maximum length of the trace in terms of historical
                points. Defaults to `30`.
            thickness: The thickness of the trace lines. Defaults to `2`.
            smooth: If `True`, applies spline smoothing to trace lines using
                consecutive unique anchor points. Falls back to a raw polyline
                when fewer than 4 unique points are available (e.g. when a
                tracker is stationary).
            color_lookup: Strategy for mapping colors to annotations.
                Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.color: Color | ColorPalette = _normalize_color_input(color)
        self.trace = Trace(max_size=trace_length, anchor=position)
        self.thickness = thickness
        self.smooth = smooth
        self.color_lookup: ColorLookup = color_lookup

    def reset(self) -> None:
        """Clears the accumulated trace history so the annotator can be reused across
        independent streams without carrying over points from a previous stream.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((20, 20, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[1, 1, 10, 10]]),
            ...     class_id=np.array([0]),
            ...     tracker_id=np.array([1])
            ... )
            >>> trace_annotator = sv.TraceAnnotator()
            >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
            >>> trace_annotator.trace.xy.shape
            (1, 2)
            >>> trace_annotator.reset()
            >>> trace_annotator.trace.current_frame_id
            0
            >>> trace_annotator.trace.xy.shape
            (0, 2)

            ```
        """
        self.trace.reset()
        spline_cache = getattr(self, "_spline_cache", None)
        if spline_cache is not None:
            spline_cache.clear()

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Draws trace paths on the frame based on the detection coordinates provided.

        Args:
            scene: The image on which the traces will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: The detections which include coordinates for
                which the traces will be drawn. An empty
                :class:`~supervision.detection.core.Detections` batch is a no-op:
                `scene` is returned unmodified.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

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

        Raises:
            ValueError: If `detections` is non-empty and its `tracker_id` field is
                missing.

        Examples:
            ```python
            import supervision as sv
            from rfdetr import RFDETRMedium
            from trackers import ByteTrackTracker

            model = RFDETRMedium()
            trace_annotator = sv.TraceAnnotator()

            video_info = sv.VideoInfo.from_video_path(video_path='...')
            frames_generator = sv.get_video_frames_generator(source_path='...')
            tracker = ByteTrackTracker(
                track_activation_threshold=0.25, minimum_consecutive_frames=1
            )

            with sv.VideoSink(target_path='...', video_info=video_info) as sink:
               for frame in frames_generator:
                   detections = model.predict(frame[:, :, ::-1])
                   detections = tracker.update(detections)
                   detections = detections[detections.tracker_id != -1]
                   annotated_frame = trace_annotator.annotate(
                       scene=frame.copy(),
                       detections=detections)
                   sink.write_frame(frame=annotated_frame)
            ```

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> trace_annotator = sv.TraceAnnotator()
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[10, 10, 30, 30]]),
            ...     class_id=np.array([0]),
            ...     tracker_id=np.array([1]),
            ... )
            >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[70, 70, 90, 90]]),
            ...     class_id=np.array([0]),
            ...     tracker_id=np.array([1]),
            ... )
            >>> annotated_frame = trace_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )
            >>> bool(annotated_frame.any())
            True
            >>> annotated_frame = trace_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=sv.Detections.empty()
            ... )
            >>> np.array_equal(annotated_frame, image)
            True

            ```

        ![trace-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/trace-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene

        # A frame in which nothing was detected carries no `tracker_id` and is
        # not a missing-tracker mistake, so it must not raise. It still reaches
        # the trace: advancing the frame counter there keeps `trace_length` a
        # window over elapsed frames, so a track whose stored history had
        # already filled that window is not joined to its pre-gap trail when it
        # reappears after a longer gap.
        if len(detections) == 0:
            self.trace.put(detections)
            existing_cache: dict[int, tuple[bytes, npt.NDArray[np.int32]]] | None = (
                getattr(self, "_spline_cache", None)
            )
            if existing_cache:
                active_ids = set(self.trace.tracker_id.tolist())
                for stale_id in list(existing_cache):
                    if stale_id not in active_ids:
                        del existing_cache[stale_id]
            return scene

        if detections.tracker_id is None:
            raise ValueError(
                "The `tracker_id` field is missing in the provided detections."
                " See more: https://supervision.roboflow.com/latest/how_to/track_objects"
            )
        is_confirmed = detections.tracker_id != PENDING_TRACK_ID
        # Validate before filtering so an invalid lookup cannot happen to match only
        # the confirmed tracks. The matching lookup then drops pending-track entries.
        if custom_color_lookup is not None:
            if len(custom_color_lookup) != len(detections):
                raise ValueError(
                    f"Length of color lookup {len(custom_color_lookup)} "
                    f"does not match length of detections {len(detections)}"
                )
            custom_color_lookup = custom_color_lookup[is_confirmed]

        # Avoid slicing/copying dense masks that TraceAnnotator does not read
        # (only CENTER_OF_MASS anchors inspect `detections.mask`), while preserving
        # oriented-box coordinates so OBB anchors stay consistent with pending tracks.
        if is_confirmed.all():
            filtered_detections = detections
        elif self.trace.anchor == Position.CENTER_OF_MASS:
            filtered_detections = detections[is_confirmed]  # type: ignore
        else:
            confirmed_data: dict[str, npt.NDArray[Any] | list[Any]] = {}
            if ORIENTED_BOX_COORDINATES in detections.data:
                obb_raw = detections.data[ORIENTED_BOX_COORDINATES]
                if isinstance(obb_raw, np.ndarray):
                    confirmed_data[ORIENTED_BOX_COORDINATES] = obb_raw[is_confirmed]
                else:
                    confirmed_data[ORIENTED_BOX_COORDINATES] = [
                        item for item, keep in zip(obb_raw, is_confirmed) if keep
                    ]
            filtered_detections = Detections(
                xyxy=detections.xyxy[is_confirmed],
                mask=None,
                confidence=(
                    detections.confidence[is_confirmed]
                    if detections.confidence is not None
                    else None
                ),
                class_id=(
                    detections.class_id[is_confirmed]
                    if detections.class_id is not None
                    else None
                ),
                tracker_id=detections.tracker_id[is_confirmed],
                data=confirmed_data,
            )

        self.trace.put(filtered_detections)
        spline_cache: dict[int, tuple[bytes, npt.NDArray[np.int32]]] | None = None
        if self.smooth:
            spline_cache = getattr(self, "_spline_cache", None)
            if spline_cache is None:
                spline_cache = {}
                self._spline_cache = spline_cache
            elif spline_cache:
                active_ids = set(self.trace.tracker_id.tolist())
                for stale_id in list(spline_cache):
                    if stale_id not in active_ids:
                        del spline_cache[stale_id]

        for detection_idx in range(len(filtered_detections)):
            tracker_id_val = filtered_detections.tracker_id[detection_idx]  # type: ignore
            if tracker_id_val is None:
                continue
            tracker_id = int(tracker_id_val)
            color = _resolve_annotator_color(
                color=self.color,
                detections=filtered_detections,
                detection_idx=detection_idx,
                color_lookup=self.color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            xy = self.trace.get(tracker_id=tracker_id)
            spline_points: npt.NDArray[np.int32] = xy.astype(np.int32)

            if self.smooth and spline_cache is not None:
                xy_key = xy.tobytes()
                cached = spline_cache.get(tracker_id)
                if cached is not None and cached[0] == xy_key:
                    spline_points = cached[1]
                else:
                    unique_xy = xy[
                        np.concatenate(
                            ([True], np.any(np.diff(xy, axis=0) != 0, axis=1))
                        )
                    ]
                    if len(unique_xy) > 3:
                        try:
                            x, y = unique_xy[:, 0], unique_xy[:, 1]
                            tck, _u = splprep([x, y], s=20)
                            x_new, y_new = splev(
                                np.linspace(0, 1, 100),
                                cast(
                                    tuple[
                                        npt.NDArray[np.float64],
                                        npt.NDArray[np.float64],
                                        int,
                                    ],
                                    tck,
                                ),
                            )
                            spline_points = np.stack((x_new, y_new), axis=1).astype(
                                np.int32
                            )
                        except ValueError:
                            spline_points = unique_xy.astype(np.int32)
                    else:
                        spline_points = unique_xy.astype(np.int32)
                    spline_cache[tracker_id] = (xy_key, spline_points)

            if len(xy) > 1:
                cv2.polylines(
                    scene,
                    [spline_points],
                    False,
                    color=_color_for_canvas(color.as_bgr(), scene),
                    thickness=self.thickness,
                )
        return scene

Methods:

__init__(color: Color | ColorPalette | str = ColorPalette.DEFAULT, position: Position = Position.CENTER, trace_length: int = 30, thickness: int = 2, smooth: bool = False, color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
color
Color | ColorPalette | str

The color to draw the trace, can be a single color or a color palette.

DEFAULT
position
Position

The position of the trace. Defaults to CENTER.

CENTER
trace_length
int

The maximum length of the trace in terms of historical points. Defaults to 30.

30
thickness
int

The thickness of the trace lines. Defaults to 2.

2
smooth
bool

If True, applies spline smoothing to trace lines using consecutive unique anchor points. Falls back to a raw polyline when fewer than 4 unique points are available (e.g. when a tracker is stationary).

False
color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    position: Position = Position.CENTER,
    trace_length: int = 30,
    thickness: int = 2,
    smooth: bool = False,
    color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        color: The color to draw the trace, can be
            a single color or a color palette.
        position: The position of the trace.
            Defaults to `CENTER`.
        trace_length: The maximum length of the trace in terms of historical
            points. Defaults to `30`.
        thickness: The thickness of the trace lines. Defaults to `2`.
        smooth: If `True`, applies spline smoothing to trace lines using
            consecutive unique anchor points. Falls back to a raw polyline
            when fewer than 4 unique points are available (e.g. when a
            tracker is stationary).
        color_lookup: Strategy for mapping colors to annotations.
            Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.color: Color | ColorPalette = _normalize_color_input(color)
    self.trace = Trace(max_size=trace_length, anchor=position)
    self.thickness = thickness
    self.smooth = smooth
    self.color_lookup: ColorLookup = color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Draws trace paths on the frame based on the detection coordinates provided.

Parameters:

Name Type Description Default
scene
ImageType

The image on which the traces will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
detections
Detections

The detections which include coordinates for which the traces will be drawn. An empty :class:~supervision.detection.core.Detections batch is a no-op: scene is returned unmodified.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

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

Raises:

Type Description
ValueError

If detections is non-empty and its tracker_id field is missing.

Examples:

import supervision as sv
from rfdetr import RFDETRMedium
from trackers import ByteTrackTracker

model = RFDETRMedium()
trace_annotator = sv.TraceAnnotator()

video_info = sv.VideoInfo.from_video_path(video_path='...')
frames_generator = sv.get_video_frames_generator(source_path='...')
tracker = ByteTrackTracker(
    track_activation_threshold=0.25, minimum_consecutive_frames=1
)

with sv.VideoSink(target_path='...', video_info=video_info) as sink:
   for frame in frames_generator:
       detections = model.predict(frame[:, :, ::-1])
       detections = tracker.update(detections)
       detections = detections[detections.tracker_id != -1]
       annotated_frame = trace_annotator.annotate(
           scene=frame.copy(),
           detections=detections)
       sink.write_frame(frame=annotated_frame)
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> trace_annotator = sv.TraceAnnotator()
>>> detections = sv.Detections(
...     xyxy=np.array([[10, 10, 30, 30]]),
...     class_id=np.array([0]),
...     tracker_id=np.array([1]),
... )
>>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
>>> detections = sv.Detections(
...     xyxy=np.array([[70, 70, 90, 90]]),
...     class_id=np.array([0]),
...     tracker_id=np.array([1]),
... )
>>> annotated_frame = trace_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )
>>> bool(annotated_frame.any())
True
>>> annotated_frame = trace_annotator.annotate(
...     scene=image.copy(),
...     detections=sv.Detections.empty()
... )
>>> np.array_equal(annotated_frame, image)
True

trace-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Draws trace paths on the frame based on the detection coordinates provided.

    Args:
        scene: The image on which the traces will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: The detections which include coordinates for
            which the traces will be drawn. An empty
            :class:`~supervision.detection.core.Detections` batch is a no-op:
            `scene` is returned unmodified.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

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

    Raises:
        ValueError: If `detections` is non-empty and its `tracker_id` field is
            missing.

    Examples:
        ```python
        import supervision as sv
        from rfdetr import RFDETRMedium
        from trackers import ByteTrackTracker

        model = RFDETRMedium()
        trace_annotator = sv.TraceAnnotator()

        video_info = sv.VideoInfo.from_video_path(video_path='...')
        frames_generator = sv.get_video_frames_generator(source_path='...')
        tracker = ByteTrackTracker(
            track_activation_threshold=0.25, minimum_consecutive_frames=1
        )

        with sv.VideoSink(target_path='...', video_info=video_info) as sink:
           for frame in frames_generator:
               detections = model.predict(frame[:, :, ::-1])
               detections = tracker.update(detections)
               detections = detections[detections.tracker_id != -1]
               annotated_frame = trace_annotator.annotate(
                   scene=frame.copy(),
                   detections=detections)
               sink.write_frame(frame=annotated_frame)
        ```

        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> trace_annotator = sv.TraceAnnotator()
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[10, 10, 30, 30]]),
        ...     class_id=np.array([0]),
        ...     tracker_id=np.array([1]),
        ... )
        >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[70, 70, 90, 90]]),
        ...     class_id=np.array([0]),
        ...     tracker_id=np.array([1]),
        ... )
        >>> annotated_frame = trace_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )
        >>> bool(annotated_frame.any())
        True
        >>> annotated_frame = trace_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=sv.Detections.empty()
        ... )
        >>> np.array_equal(annotated_frame, image)
        True

        ```

    ![trace-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/trace-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene

    # A frame in which nothing was detected carries no `tracker_id` and is
    # not a missing-tracker mistake, so it must not raise. It still reaches
    # the trace: advancing the frame counter there keeps `trace_length` a
    # window over elapsed frames, so a track whose stored history had
    # already filled that window is not joined to its pre-gap trail when it
    # reappears after a longer gap.
    if len(detections) == 0:
        self.trace.put(detections)
        existing_cache: dict[int, tuple[bytes, npt.NDArray[np.int32]]] | None = (
            getattr(self, "_spline_cache", None)
        )
        if existing_cache:
            active_ids = set(self.trace.tracker_id.tolist())
            for stale_id in list(existing_cache):
                if stale_id not in active_ids:
                    del existing_cache[stale_id]
        return scene

    if detections.tracker_id is None:
        raise ValueError(
            "The `tracker_id` field is missing in the provided detections."
            " See more: https://supervision.roboflow.com/latest/how_to/track_objects"
        )
    is_confirmed = detections.tracker_id != PENDING_TRACK_ID
    # Validate before filtering so an invalid lookup cannot happen to match only
    # the confirmed tracks. The matching lookup then drops pending-track entries.
    if custom_color_lookup is not None:
        if len(custom_color_lookup) != len(detections):
            raise ValueError(
                f"Length of color lookup {len(custom_color_lookup)} "
                f"does not match length of detections {len(detections)}"
            )
        custom_color_lookup = custom_color_lookup[is_confirmed]

    # Avoid slicing/copying dense masks that TraceAnnotator does not read
    # (only CENTER_OF_MASS anchors inspect `detections.mask`), while preserving
    # oriented-box coordinates so OBB anchors stay consistent with pending tracks.
    if is_confirmed.all():
        filtered_detections = detections
    elif self.trace.anchor == Position.CENTER_OF_MASS:
        filtered_detections = detections[is_confirmed]  # type: ignore
    else:
        confirmed_data: dict[str, npt.NDArray[Any] | list[Any]] = {}
        if ORIENTED_BOX_COORDINATES in detections.data:
            obb_raw = detections.data[ORIENTED_BOX_COORDINATES]
            if isinstance(obb_raw, np.ndarray):
                confirmed_data[ORIENTED_BOX_COORDINATES] = obb_raw[is_confirmed]
            else:
                confirmed_data[ORIENTED_BOX_COORDINATES] = [
                    item for item, keep in zip(obb_raw, is_confirmed) if keep
                ]
        filtered_detections = Detections(
            xyxy=detections.xyxy[is_confirmed],
            mask=None,
            confidence=(
                detections.confidence[is_confirmed]
                if detections.confidence is not None
                else None
            ),
            class_id=(
                detections.class_id[is_confirmed]
                if detections.class_id is not None
                else None
            ),
            tracker_id=detections.tracker_id[is_confirmed],
            data=confirmed_data,
        )

    self.trace.put(filtered_detections)
    spline_cache: dict[int, tuple[bytes, npt.NDArray[np.int32]]] | None = None
    if self.smooth:
        spline_cache = getattr(self, "_spline_cache", None)
        if spline_cache is None:
            spline_cache = {}
            self._spline_cache = spline_cache
        elif spline_cache:
            active_ids = set(self.trace.tracker_id.tolist())
            for stale_id in list(spline_cache):
                if stale_id not in active_ids:
                    del spline_cache[stale_id]

    for detection_idx in range(len(filtered_detections)):
        tracker_id_val = filtered_detections.tracker_id[detection_idx]  # type: ignore
        if tracker_id_val is None:
            continue
        tracker_id = int(tracker_id_val)
        color = _resolve_annotator_color(
            color=self.color,
            detections=filtered_detections,
            detection_idx=detection_idx,
            color_lookup=self.color_lookup,
            custom_color_lookup=custom_color_lookup,
        )
        xy = self.trace.get(tracker_id=tracker_id)
        spline_points: npt.NDArray[np.int32] = xy.astype(np.int32)

        if self.smooth and spline_cache is not None:
            xy_key = xy.tobytes()
            cached = spline_cache.get(tracker_id)
            if cached is not None and cached[0] == xy_key:
                spline_points = cached[1]
            else:
                unique_xy = xy[
                    np.concatenate(
                        ([True], np.any(np.diff(xy, axis=0) != 0, axis=1))
                    )
                ]
                if len(unique_xy) > 3:
                    try:
                        x, y = unique_xy[:, 0], unique_xy[:, 1]
                        tck, _u = splprep([x, y], s=20)
                        x_new, y_new = splev(
                            np.linspace(0, 1, 100),
                            cast(
                                tuple[
                                    npt.NDArray[np.float64],
                                    npt.NDArray[np.float64],
                                    int,
                                ],
                                tck,
                            ),
                        )
                        spline_points = np.stack((x_new, y_new), axis=1).astype(
                            np.int32
                        )
                    except ValueError:
                        spline_points = unique_xy.astype(np.int32)
                else:
                    spline_points = unique_xy.astype(np.int32)
                spline_cache[tracker_id] = (xy_key, spline_points)

        if len(xy) > 1:
            cv2.polylines(
                scene,
                [spline_points],
                False,
                color=_color_for_canvas(color.as_bgr(), scene),
                thickness=self.thickness,
            )
    return scene

reset() -> None

Clears the accumulated trace history so the annotator can be reused across independent streams without carrying over points from a previous stream.

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((20, 20, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[1, 1, 10, 10]]),
...     class_id=np.array([0]),
...     tracker_id=np.array([1])
... )
>>> trace_annotator = sv.TraceAnnotator()
>>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
>>> trace_annotator.trace.xy.shape
(1, 2)
>>> trace_annotator.reset()
>>> trace_annotator.trace.current_frame_id
0
>>> trace_annotator.trace.xy.shape
(0, 2)
Source code in src/supervision/annotators/core.py
def reset(self) -> None:
    """Clears the accumulated trace history so the annotator can be reused across
    independent streams without carrying over points from a previous stream.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((20, 20, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[1, 1, 10, 10]]),
        ...     class_id=np.array([0]),
        ...     tracker_id=np.array([1])
        ... )
        >>> trace_annotator = sv.TraceAnnotator()
        >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections)
        >>> trace_annotator.trace.xy.shape
        (1, 2)
        >>> trace_annotator.reset()
        >>> trace_annotator.trace.current_frame_id
        0
        >>> trace_annotator.trace.xy.shape
        (0, 2)

        ```
    """
    self.trace.reset()
    spline_cache = getattr(self, "_spline_cache", None)
    if spline_cache is not None:
        spline_cache.clear()

supervision.annotators.core.CropAnnotator

Bases: BaseAnnotator

A class for drawing scaled up crops of detections on the scene.

Source code in src/supervision/annotators/core.py
class CropAnnotator(BaseAnnotator):
    """A class for drawing scaled up crops of detections on the scene."""

    def __init__(
        self,
        position: Position = Position.TOP_CENTER,
        scale_factor: float = 2.0,
        border_color: Color | ColorPalette | str = ColorPalette.DEFAULT,
        border_thickness: int = 2,
        border_color_lookup: ColorLookup = ColorLookup.CLASS,
    ):
        """
        Args:
            position: The anchor position for placing the cropped and scaled
                part of the detection in the scene.
            scale_factor: The factor by which to scale the cropped image part. A
                factor of 2, for example, would double the size of the cropped area,
                allowing for a closer view of the detection.
            border_color: The color or color palette to
                use for annotating border around the cropped area.
            border_thickness: The thickness of the border around the cropped area.
            border_color_lookup: Strategy for mapping colors to
                annotations. Options are `INDEX`, `CLASS`, `TRACK`.
        """
        self.position: Position = position
        self.scale_factor: float = scale_factor
        self.border_color: Color | ColorPalette = _normalize_color_input(border_color)
        self.border_thickness: int = border_thickness
        self.border_color_lookup: ColorLookup = border_color_lookup

    @ensure_cv2_image_for_class_method
    def annotate(
        self,
        scene: ImageType,
        detections: Detections,
        custom_color_lookup: npt.NDArray[np.int_] | None = None,
    ) -> ImageType:
        """Annotates the provided scene with scaled and cropped parts of the image based
        on the provided detections. Each detection is cropped from the original scene
        and scaled according to the annotator's scale factor before being placed back
        onto the scene at the specified position.

        Args:
            scene: The image where cropped detection will be placed.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.
            custom_color_lookup: Custom color lookup array.
                Allows to override the default color mapping strategy.

        Returns:
            The annotated image.

        Note:
            Detections whose bounding boxes extend partially outside `scene` are
            clipped to scene bounds before cropping. Detections fully outside the
            scene collapse to zero area after clipping and are skipped without
            raising an error.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> crop_annotator = sv.CropAnnotator()
            >>> annotated_frame = crop_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![crop-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/crop-annotator-example.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        image_height, image_width = scene.shape[:2]
        clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
            xyxy=detections.xyxy,
            resolution_wh=(image_width, image_height),
        ).astype(np.int32)
        anchors: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
            anchor=self.position
        ).astype(np.int32)
        # Snapshot before the loop so later crops are taken from the original image,
        # not a scene already annotated by earlier iterations (overlapping-box case).
        source_scene = scene.copy()

        for idx, (xyxy, anchor) in enumerate(zip(clipped_xyxy, anchors)):
            crop_x1, crop_y1, crop_x2, crop_y2 = xyxy
            if crop_x2 <= crop_x1 or crop_y2 <= crop_y1:
                continue
            crop = crop_image(image=source_scene, xyxy=xyxy)
            resized_crop = scale_image(image=crop, scale_factor=self.scale_factor)
            crop_wh = resized_crop.shape[1], resized_crop.shape[0]
            (x1, y1), (x2, y2) = self.calculate_crop_coordinates(
                anchor=anchor, crop_wh=crop_wh, position=self.position
            )
            scene = _overlay_image(image=scene, overlay=resized_crop, anchor=(x1, y1))
            color = _resolve_annotator_color(
                color=self.border_color,
                detections=detections,
                detection_idx=idx,
                color_lookup=self.border_color_lookup,
                custom_color_lookup=custom_color_lookup,
            )
            border_color: tuple[int, ...] = color.as_bgr()
            if scene.ndim == 3 and scene.shape[2] == 4:
                border_color = (*border_color, 255)
            cv2.rectangle(
                img=scene,
                pt1=(x1, y1),
                pt2=(x2, y2),
                color=border_color,
                thickness=self.border_thickness,
            )

        return scene

    @staticmethod
    def calculate_crop_coordinates(
        anchor: tuple[int, int], crop_wh: tuple[int, int], position: Position
    ) -> tuple[tuple[int, int], tuple[int, int]]:
        """Compute the crop coordinates for a given anchor position."""
        anchor_x, anchor_y = anchor
        width, height = crop_wh

        if position == Position.TOP_LEFT:
            return (anchor_x - width, anchor_y - height), (anchor_x, anchor_y)
        elif position == Position.TOP_CENTER:
            return (
                (anchor_x - width // 2, anchor_y - height),
                (anchor_x + width // 2, anchor_y),
            )
        elif position == Position.TOP_RIGHT:
            return (anchor_x, anchor_y - height), (anchor_x + width, anchor_y)
        elif position == Position.CENTER_LEFT:
            return (
                (anchor_x - width, anchor_y - height // 2),
                (anchor_x, anchor_y + height // 2),
            )
        elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
            return (
                (anchor_x - width // 2, anchor_y - height // 2),
                (anchor_x + width // 2, anchor_y + height // 2),
            )
        elif position == Position.CENTER_RIGHT:
            return (
                (anchor_x, anchor_y - height // 2),
                (anchor_x + width, anchor_y + height // 2),
            )
        elif position == Position.BOTTOM_LEFT:
            return (anchor_x - width, anchor_y), (anchor_x, anchor_y + height)
        elif position == Position.BOTTOM_CENTER:
            return (
                (anchor_x - width // 2, anchor_y),
                (anchor_x + width // 2, anchor_y + height),
            )
        elif position == Position.BOTTOM_RIGHT:
            return (anchor_x, anchor_y), (anchor_x + width, anchor_y + height)
        raise ValueError(f"Unsupported position: {position}")

Methods:

__init__(position: Position = Position.TOP_CENTER, scale_factor: float = 2.0, border_color: Color | ColorPalette | str = ColorPalette.DEFAULT, border_thickness: int = 2, border_color_lookup: ColorLookup = ColorLookup.CLASS)

Parameters:

Name Type Description Default
position
Position

The anchor position for placing the cropped and scaled part of the detection in the scene.

TOP_CENTER
scale_factor
float

The factor by which to scale the cropped image part. A factor of 2, for example, would double the size of the cropped area, allowing for a closer view of the detection.

2.0
border_color
Color | ColorPalette | str

The color or color palette to use for annotating border around the cropped area.

DEFAULT
border_thickness
int

The thickness of the border around the cropped area.

2
border_color_lookup
ColorLookup

Strategy for mapping colors to annotations. Options are INDEX, CLASS, TRACK.

CLASS
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    position: Position = Position.TOP_CENTER,
    scale_factor: float = 2.0,
    border_color: Color | ColorPalette | str = ColorPalette.DEFAULT,
    border_thickness: int = 2,
    border_color_lookup: ColorLookup = ColorLookup.CLASS,
):
    """
    Args:
        position: The anchor position for placing the cropped and scaled
            part of the detection in the scene.
        scale_factor: The factor by which to scale the cropped image part. A
            factor of 2, for example, would double the size of the cropped area,
            allowing for a closer view of the detection.
        border_color: The color or color palette to
            use for annotating border around the cropped area.
        border_thickness: The thickness of the border around the cropped area.
        border_color_lookup: Strategy for mapping colors to
            annotations. Options are `INDEX`, `CLASS`, `TRACK`.
    """
    self.position: Position = position
    self.scale_factor: float = scale_factor
    self.border_color: Color | ColorPalette = _normalize_color_input(border_color)
    self.border_thickness: int = border_thickness
    self.border_color_lookup: ColorLookup = border_color_lookup

annotate(scene: ImageType, detections: Detections, custom_color_lookup: npt.NDArray[np.int_] | None = None) -> ImageType

Annotates the provided scene with scaled and cropped parts of the image based on the provided detections. Each detection is cropped from the original scene and scaled according to the annotator's scale factor before being placed back onto the scene at the specified position.

Parameters:

Name Type Description Default
scene
ImageType

The image where cropped detection will be placed. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image.

required
detections
Detections

Object detections to annotate.

required
custom_color_lookup
NDArray[int_] | None

Custom color lookup array. Allows to override the default color mapping strategy.

None

Returns:

Type Description
ImageType

The annotated image.

Note

Detections whose bounding boxes extend partially outside scene are clipped to scene bounds before cropping. Detections fully outside the scene collapse to zero area after clipping and are skipped without raising an error.

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> crop_annotator = sv.CropAnnotator()
>>> annotated_frame = crop_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

crop-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self,
    scene: ImageType,
    detections: Detections,
    custom_color_lookup: npt.NDArray[np.int_] | None = None,
) -> ImageType:
    """Annotates the provided scene with scaled and cropped parts of the image based
    on the provided detections. Each detection is cropped from the original scene
    and scaled according to the annotator's scale factor before being placed back
    onto the scene at the specified position.

    Args:
        scene: The image where cropped detection will be placed.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.
        custom_color_lookup: Custom color lookup array.
            Allows to override the default color mapping strategy.

    Returns:
        The annotated image.

    Note:
        Detections whose bounding boxes extend partially outside `scene` are
        clipped to scene bounds before cropping. Detections fully outside the
        scene collapse to zero area after clipping and are skipped without
        raising an error.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> crop_annotator = sv.CropAnnotator()
        >>> annotated_frame = crop_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![crop-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/crop-annotator-example.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    image_height, image_width = scene.shape[:2]
    clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
        xyxy=detections.xyxy,
        resolution_wh=(image_width, image_height),
    ).astype(np.int32)
    anchors: npt.NDArray[np.int32] = detections.get_anchors_coordinates(
        anchor=self.position
    ).astype(np.int32)
    # Snapshot before the loop so later crops are taken from the original image,
    # not a scene already annotated by earlier iterations (overlapping-box case).
    source_scene = scene.copy()

    for idx, (xyxy, anchor) in enumerate(zip(clipped_xyxy, anchors)):
        crop_x1, crop_y1, crop_x2, crop_y2 = xyxy
        if crop_x2 <= crop_x1 or crop_y2 <= crop_y1:
            continue
        crop = crop_image(image=source_scene, xyxy=xyxy)
        resized_crop = scale_image(image=crop, scale_factor=self.scale_factor)
        crop_wh = resized_crop.shape[1], resized_crop.shape[0]
        (x1, y1), (x2, y2) = self.calculate_crop_coordinates(
            anchor=anchor, crop_wh=crop_wh, position=self.position
        )
        scene = _overlay_image(image=scene, overlay=resized_crop, anchor=(x1, y1))
        color = _resolve_annotator_color(
            color=self.border_color,
            detections=detections,
            detection_idx=idx,
            color_lookup=self.border_color_lookup,
            custom_color_lookup=custom_color_lookup,
        )
        border_color: tuple[int, ...] = color.as_bgr()
        if scene.ndim == 3 and scene.shape[2] == 4:
            border_color = (*border_color, 255)
        cv2.rectangle(
            img=scene,
            pt1=(x1, y1),
            pt2=(x2, y2),
            color=border_color,
            thickness=self.border_thickness,
        )

    return scene

calculate_crop_coordinates(anchor: tuple[int, int], crop_wh: tuple[int, int], position: Position) -> tuple[tuple[int, int], tuple[int, int]] staticmethod

Compute the crop coordinates for a given anchor position.

Source code in src/supervision/annotators/core.py
@staticmethod
def calculate_crop_coordinates(
    anchor: tuple[int, int], crop_wh: tuple[int, int], position: Position
) -> tuple[tuple[int, int], tuple[int, int]]:
    """Compute the crop coordinates for a given anchor position."""
    anchor_x, anchor_y = anchor
    width, height = crop_wh

    if position == Position.TOP_LEFT:
        return (anchor_x - width, anchor_y - height), (anchor_x, anchor_y)
    elif position == Position.TOP_CENTER:
        return (
            (anchor_x - width // 2, anchor_y - height),
            (anchor_x + width // 2, anchor_y),
        )
    elif position == Position.TOP_RIGHT:
        return (anchor_x, anchor_y - height), (anchor_x + width, anchor_y)
    elif position == Position.CENTER_LEFT:
        return (
            (anchor_x - width, anchor_y - height // 2),
            (anchor_x, anchor_y + height // 2),
        )
    elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
        return (
            (anchor_x - width // 2, anchor_y - height // 2),
            (anchor_x + width // 2, anchor_y + height // 2),
        )
    elif position == Position.CENTER_RIGHT:
        return (
            (anchor_x, anchor_y - height // 2),
            (anchor_x + width, anchor_y + height // 2),
        )
    elif position == Position.BOTTOM_LEFT:
        return (anchor_x - width, anchor_y), (anchor_x, anchor_y + height)
    elif position == Position.BOTTOM_CENTER:
        return (
            (anchor_x - width // 2, anchor_y),
            (anchor_x + width // 2, anchor_y + height),
        )
    elif position == Position.BOTTOM_RIGHT:
        return (anchor_x, anchor_y), (anchor_x + width, anchor_y + height)
    raise ValueError(f"Unsupported position: {position}")

supervision.annotators.core.BackgroundOverlayAnnotator

Bases: BaseAnnotator

A class for drawing a colored overlay on the background of an image outside the region of detections.

If masks are provided, the background is colored outside the masks. If masks are not provided, the background is colored outside the bounding boxes.

You can use the force_box parameter to force the annotator to use bounding boxes.

Warning

This annotator uses :class:~supervision.detection.core.Detections.mask.

Source code in src/supervision/annotators/core.py
class BackgroundOverlayAnnotator(BaseAnnotator):
    """A class for drawing a colored overlay on the background of an image outside the
    region of detections.

    If masks are provided, the background is colored outside the masks. If masks are not
    provided, the background is colored outside the bounding boxes.

    You can use the `force_box` parameter to force the annotator to use bounding boxes.

    !!! warning

    This annotator uses
    :class:`~supervision.detection.core.Detections`.mask.
    """

    def __init__(
        self,
        color: Color = Color.BLACK,
        opacity: float = 0.5,
        force_box: bool = False,
    ):
        """
        Args:
            color: The color to use for annotating detections.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            force_box: If `True`, forces the annotator to use bounding boxes when
                masks are provided in the supplied
                :class:`~supervision.detection.core.Detections`.
        """
        self.color: Color = color
        self.opacity = opacity
        self.force_box = force_box

    @ensure_cv2_image_for_class_method
    def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
        """Applies a colored overlay to the scene outside of the detected regions.

        Args:
            scene: The image where masks will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`.
            detections: Object detections to annotate.

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

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[20, 20, 80, 80]]),
            ...     class_id=np.array([0])
            ... )
            >>> background_overlay_annotator = sv.BackgroundOverlayAnnotator()
            >>> annotated_frame = background_overlay_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections=detections
            ... )

            ```

        ![background-overlay-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/background-color-annotator-example-purple.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        colored_mask = np.full_like(
            scene, _color_for_canvas(self.color.as_bgr(), scene), dtype=np.uint8
        )

        if scene.ndim == 3 and scene.shape[2] == 4:
            alpha = np.full((*scene.shape[:2], 1), self.opacity, dtype=np.float32)
            colored_mask = _composite_over_bgra(scene, colored_mask[..., :3], alpha)
        else:
            cv2.addWeighted(
                scene, 1 - self.opacity, colored_mask, self.opacity, 0, dst=colored_mask
            )

        if detections.mask is None or self.force_box:
            image_height, image_width = scene.shape[:2]
            clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
                xyxy=detections.xyxy,
                resolution_wh=(image_width, image_height),
            ).astype(np.int32)
            for x1, y1, x2, y2 in clipped_xyxy:
                colored_mask[y1:y2, x1:x2] = scene[y1:y2, x1:x2]
        else:
            for mask in detections.mask:
                mask_bool = np.asarray(mask, dtype=bool)
                colored_mask[mask_bool] = scene[mask_bool]

        np.copyto(scene, colored_mask)
        return scene

Methods:

__init__(color: Color = Color.BLACK, opacity: float = 0.5, force_box: bool = False)

Parameters:

Name Type Description Default
color
Color

The color to use for annotating detections.

BLACK
opacity
float

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

0.5
force_box
bool

If True, forces the annotator to use bounding boxes when masks are provided in the supplied :class:~supervision.detection.core.Detections.

False
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color: Color = Color.BLACK,
    opacity: float = 0.5,
    force_box: bool = False,
):
    """
    Args:
        color: The color to use for annotating detections.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        force_box: If `True`, forces the annotator to use bounding boxes when
            masks are provided in the supplied
            :class:`~supervision.detection.core.Detections`.
    """
    self.color: Color = color
    self.opacity = opacity
    self.force_box = force_box

annotate(scene: ImageType, detections: Detections) -> ImageType

Applies a colored overlay to the scene outside of the detected regions.

Parameters:

Name Type Description Default
scene
ImageType

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

required
detections
Detections

Object detections to annotate.

required

Returns:

Type Description
ImageType

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

Examples:

>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections = sv.Detections(
...     xyxy=np.array([[20, 20, 80, 80]]),
...     class_id=np.array([0])
... )
>>> background_overlay_annotator = sv.BackgroundOverlayAnnotator()
>>> annotated_frame = background_overlay_annotator.annotate(
...     scene=image.copy(),
...     detections=detections
... )

background-overlay-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
    """Applies a colored overlay to the scene outside of the detected regions.

    Args:
        scene: The image where masks will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`.
        detections: Object detections to annotate.

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

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[20, 20, 80, 80]]),
        ...     class_id=np.array([0])
        ... )
        >>> background_overlay_annotator = sv.BackgroundOverlayAnnotator()
        >>> annotated_frame = background_overlay_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections=detections
        ... )

        ```

    ![background-overlay-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/background-color-annotator-example-purple.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    colored_mask = np.full_like(
        scene, _color_for_canvas(self.color.as_bgr(), scene), dtype=np.uint8
    )

    if scene.ndim == 3 and scene.shape[2] == 4:
        alpha = np.full((*scene.shape[:2], 1), self.opacity, dtype=np.float32)
        colored_mask = _composite_over_bgra(scene, colored_mask[..., :3], alpha)
    else:
        cv2.addWeighted(
            scene, 1 - self.opacity, colored_mask, self.opacity, 0, dst=colored_mask
        )

    if detections.mask is None or self.force_box:
        image_height, image_width = scene.shape[:2]
        clipped_xyxy: npt.NDArray[np.int32] = clip_boxes(
            xyxy=detections.xyxy,
            resolution_wh=(image_width, image_height),
        ).astype(np.int32)
        for x1, y1, x2, y2 in clipped_xyxy:
            colored_mask[y1:y2, x1:x2] = scene[y1:y2, x1:x2]
    else:
        for mask in detections.mask:
            mask_bool = np.asarray(mask, dtype=bool)
            colored_mask[mask_bool] = scene[mask_bool]

    np.copyto(scene, colored_mask)
    return scene

supervision.annotators.core.ComparisonAnnotator

Highlights the differences between two sets of detections.

Useful for comparing results from two different models, or the difference between a ground truth and a prediction.

If present, uses the oriented bounding box data. Otherwise, if present, uses a mask. Otherwise, uses the bounding box data.

Source code in src/supervision/annotators/core.py
class ComparisonAnnotator:
    """Highlights the differences between two sets of detections.

    Useful for comparing results from two different models, or the difference between a
    ground truth and a prediction.

    If present, uses the oriented bounding box data. Otherwise, if present, uses a mask.
    Otherwise, uses the bounding box data.
    """

    # Not a BaseAnnotator subclass — duck-typing callers can still check requires_mask
    requires_mask: ClassVar[bool] = False

    def __init__(
        self,
        color_1: Color = Color.RED,
        color_2: Color = Color.GREEN,
        color_overlap: Color = Color.BLUE,
        *,
        opacity: float = 0.75,
        label_1: str = "",
        label_2: str = "",
        label_overlap: str = "",
        label_scale: float = 1.0,
    ):
        """
        Args:
            color_1: Color of areas only present in the first set of
                detections.
            color_2: Color of areas only present in the second set of
                detections.
            color_overlap: Color of areas present in both sets of detections.
            opacity: Opacity of the overlay mask. Must be between `0` and `1`.
            label_1: Label for the first set of detections.
            label_2: Label for the second set of detections.
            label_overlap: Label for areas present in both sets of detections.
            label_scale: Controls how large the labels are.
        """
        self.color_1 = color_1
        self.color_2 = color_2
        self.color_overlap = color_overlap

        self.opacity = opacity
        self.label_1 = label_1
        self.label_2 = label_2
        self.label_overlap = label_overlap
        self.label_scale = label_scale
        self.text_thickness = int(self.label_scale + 1.2)

    @ensure_cv2_image_for_class_method
    def annotate(
        self, scene: ImageType, detections_1: Detections, detections_2: Detections
    ) -> ImageType:
        """Highlights the differences between two sets of detections.

        Args:
            scene: The image where detections will be drawn.
                `ImageType` is a flexible type, accepting either `numpy.ndarray`
                or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
                or `(H, W, 1)`; regions are blended with the first (blue) channel
                of their color, as OpenCV draws boxes and polygons.
            detections_1: The first set of detections or predictions.
            detections_2: The second set of detections to compare or
                ground truth.

        Returns:
            The annotated image.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
            >>> detections_1 = sv.Detections(
            ...     xyxy=np.array([[10, 10, 50, 50]]),
            ...     class_id=np.array([0]),
            ... )
            >>> detections_2 = sv.Detections(
            ...     xyxy=np.array([[40, 40, 90, 90]]),
            ...     class_id=np.array([0]),
            ... )
            >>> comparison_annotator = sv.ComparisonAnnotator()
            >>> annotated_frame = comparison_annotator.annotate(
            ...     scene=image.copy(),
            ...     detections_1=detections_1,
            ...     detections_2=detections_2
            ... )

            ```

        ![comparison-annotator-example](https://media.roboflow.com/
        supervision-annotator-examples/comparison-annotator-example.png)
        """
        if not isinstance(scene, np.ndarray):
            return scene
        if detections_1.is_empty() and detections_2.is_empty():
            return scene

        use_obb = self._use_obb(detections_1, detections_2)
        use_mask = self._use_mask(detections_1, detections_2)

        if use_obb:
            mask_1 = self._mask_from_obb(scene, detections_1)
            mask_2 = self._mask_from_obb(scene, detections_2)

        elif use_mask:
            mask_1 = self._mask_from_mask(scene, detections_1)
            mask_2 = self._mask_from_mask(scene, detections_2)

        else:
            mask_1 = self._mask_from_xyxy(scene, detections_1)
            mask_2 = self._mask_from_xyxy(scene, detections_2)

        mask_overlap = mask_1 & mask_2
        mask_1 = mask_1 & ~mask_overlap
        mask_2 = mask_2 & ~mask_overlap

        color_layer = np.zeros_like(scene, dtype=np.uint8)
        color_layer[mask_overlap] = _color_for_canvas(
            self.color_overlap.as_bgr(), scene
        )
        color_layer[mask_1] = _color_for_canvas(self.color_1.as_bgr(), scene)
        color_layer[mask_2] = _color_for_canvas(self.color_2.as_bgr(), scene)

        if scene.ndim == 3 and scene.shape[2] == 4:
            union = mask_overlap | mask_1 | mask_2
            alpha = union[..., np.newaxis].astype(np.float32) * self.opacity
            blended = _composite_over_bgra(scene, color_layer[..., :3], alpha)
            # Match the original integer truncation for fully opaque scenes.
            opaque = union & (scene[..., 3] == 255)
            blended[opaque, :3] = (1 - self.opacity) * scene[
                opaque, :3
            ] + self.opacity * color_layer[opaque, :3]
            scene[:] = blended
        else:
            scene[mask_overlap] = (1 - self.opacity) * scene[
                mask_overlap
            ] + self.opacity * color_layer[mask_overlap]
            scene[mask_1] = (1 - self.opacity) * scene[
                mask_1
            ] + self.opacity * color_layer[mask_1]
            scene[mask_2] = (1 - self.opacity) * scene[
                mask_2
            ] + self.opacity * color_layer[mask_2]

        self._draw_labels(scene)

        return scene

    @staticmethod
    def _use_obb(detections_1: Detections, detections_2: Detections) -> bool:
        assert not detections_1.is_empty() or not detections_2.is_empty()
        is_obb_1 = ORIENTED_BOX_COORDINATES in detections_1.data
        is_obb_2 = ORIENTED_BOX_COORDINATES in detections_2.data
        return (
            (is_obb_1 and is_obb_2)
            or (is_obb_1 and detections_2.is_empty())
            or (detections_1.is_empty() and is_obb_2)
        )

    @staticmethod
    def _use_mask(detections_1: Detections, detections_2: Detections) -> bool:
        assert not detections_1.is_empty() or not detections_2.is_empty()
        is_mask_1 = detections_1.mask is not None
        is_mask_2 = detections_2.mask is not None
        return (
            (is_mask_1 and is_mask_2)
            or (is_mask_1 and detections_2.is_empty())
            or (detections_1.is_empty() and is_mask_2)
        )

    @staticmethod
    def _mask_from_xyxy(
        scene: npt.NDArray[np.uint8], detections: Detections
    ) -> npt.NDArray[np.bool_]:
        mask = np.zeros(scene.shape[:2], dtype=np.bool_)
        if detections.is_empty():
            return mask

        resolution_wh = scene.shape[1], scene.shape[0]
        polygons = xyxy_to_polygons(detections.xyxy)

        for polygon in polygons:
            polygon_mask = polygon_to_mask(polygon, resolution_wh=resolution_wh)
            mask |= polygon_mask.astype(np.bool_)
        return mask

    @staticmethod
    def _mask_from_obb(
        scene: npt.NDArray[np.uint8], detections: Detections
    ) -> npt.NDArray[np.bool_]:
        mask = np.zeros(scene.shape[:2], dtype=np.bool_)
        if detections.is_empty():
            return mask

        resolution_wh = scene.shape[1], scene.shape[0]

        for polygon in detections.data[ORIENTED_BOX_COORDINATES]:
            polygon_mask = polygon_to_mask(polygon, resolution_wh=resolution_wh)
            mask |= polygon_mask.astype(np.bool_)
        return mask

    @staticmethod
    def _mask_from_mask(
        scene: npt.NDArray[np.uint8], detections: Detections
    ) -> npt.NDArray[np.bool_]:
        """Return the union of detection masks without materializing CompactMask."""
        if detections.is_empty():
            return np.zeros(scene.shape[:2], dtype=np.bool_)
        assert detections.mask is not None

        if isinstance(detections.mask, CompactMask):
            mask = np.zeros(scene.shape[:2], dtype=np.bool_)
            scene_height, scene_width = scene.shape[:2]
            # Decode each CompactMask crop so this union never allocates (N, H, W).
            for detection_idx, (x1, y1) in enumerate(detections.mask.offsets):
                crop = detections.mask.crop(detection_idx)
                crop_height, crop_width = crop.shape
                x1_int, y1_int = int(x1), int(y1)
                x2 = min(x1_int + crop_width, scene_width)
                y2 = min(y1_int + crop_height, scene_height)
                if x2 > x1_int and y2 > y1_int:
                    mask[y1_int:y2, x1_int:x2] |= crop[: y2 - y1_int, : x2 - x1_int]
            return mask

        return cast(npt.NDArray[np.bool_], np.any(detections.mask, axis=0))

    def _draw_labels(self, scene: npt.NDArray[np.uint8]) -> None:
        """Draw the labels, explaining what each color represents, with automatically
        computed positions.

        Args:
            scene: The image where the labels will be drawn.
        """
        margin = int(50 * self.label_scale)
        gap = int(40 * self.label_scale)
        y0 = int(50 * self.label_scale)
        height = int(50 * self.label_scale)

        marker_size = int(20 * self.label_scale)
        padding = int(10 * self.label_scale)
        text_box_corner_radius = int(10 * self.label_scale)
        marker_corner_radius = int(4 * self.label_scale)
        text_scale = self.label_scale

        label_color_pairs = [
            (self.label_1, self.color_1),
            (self.label_2, self.color_2),
            (self.label_overlap, self.color_overlap),
        ]

        x0 = margin
        for text, color in label_color_pairs:
            if not text:
                continue

            (text_w, _) = cv2.getTextSize(
                text=text,
                fontFace=CV2_FONT,
                fontScale=self.label_scale,
                thickness=self.text_thickness,
            )[0]

            width = text_w + marker_size + padding * 4
            center_x = x0 + width // 2
            center_y = y0 + height // 2

            draw_rounded_rectangle(
                scene=scene,
                rect=Rect(x=x0, y=y0, width=width, height=height),
                color=Color.WHITE,
                border_radius=text_box_corner_radius,
            )

            draw_rounded_rectangle(
                scene=scene,
                rect=Rect(
                    x=x0 + padding,
                    y=center_y - marker_size / 2,
                    width=marker_size,
                    height=marker_size,
                ),
                color=color,
                border_radius=marker_corner_radius,
            )

            draw_text(
                scene,
                text,
                text_anchor=Point(x=center_x + marker_size, y=center_y),
                text_scale=text_scale,
                text_thickness=self.text_thickness,
            )

            x0 += width + gap

Methods:

__init__(color_1: Color = Color.RED, color_2: Color = Color.GREEN, color_overlap: Color = Color.BLUE, *, opacity: float = 0.75, label_1: str = '', label_2: str = '', label_overlap: str = '', label_scale: float = 1.0)

Parameters:

Name Type Description Default
color_1
Color

Color of areas only present in the first set of detections.

RED
color_2
Color

Color of areas only present in the second set of detections.

GREEN
color_overlap
Color

Color of areas present in both sets of detections.

BLUE
opacity
float

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

0.75
label_1
str

Label for the first set of detections.

''
label_2
str

Label for the second set of detections.

''
label_overlap
str

Label for areas present in both sets of detections.

''
label_scale
float

Controls how large the labels are.

1.0
Source code in src/supervision/annotators/core.py
def __init__(
    self,
    color_1: Color = Color.RED,
    color_2: Color = Color.GREEN,
    color_overlap: Color = Color.BLUE,
    *,
    opacity: float = 0.75,
    label_1: str = "",
    label_2: str = "",
    label_overlap: str = "",
    label_scale: float = 1.0,
):
    """
    Args:
        color_1: Color of areas only present in the first set of
            detections.
        color_2: Color of areas only present in the second set of
            detections.
        color_overlap: Color of areas present in both sets of detections.
        opacity: Opacity of the overlay mask. Must be between `0` and `1`.
        label_1: Label for the first set of detections.
        label_2: Label for the second set of detections.
        label_overlap: Label for areas present in both sets of detections.
        label_scale: Controls how large the labels are.
    """
    self.color_1 = color_1
    self.color_2 = color_2
    self.color_overlap = color_overlap

    self.opacity = opacity
    self.label_1 = label_1
    self.label_2 = label_2
    self.label_overlap = label_overlap
    self.label_scale = label_scale
    self.text_thickness = int(self.label_scale + 1.2)

annotate(scene: ImageType, detections_1: Detections, detections_2: Detections) -> ImageType

Highlights the differences between two sets of detections.

Parameters:

Name Type Description Default
scene
ImageType

The image where detections will be drawn. ImageType is a flexible type, accepting either numpy.ndarray or PIL.Image.Image. Grayscale arrays may have shape (H, W) or (H, W, 1); regions are blended with the first (blue) channel of their color, as OpenCV draws boxes and polygons.

required
detections_1
Detections

The first set of detections or predictions.

required
detections_2
Detections

The second set of detections to compare or ground truth.

required

Returns:

Type Description
ImageType

The annotated image.

Example
>>> import numpy as np
>>> import supervision as sv
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> detections_1 = sv.Detections(
...     xyxy=np.array([[10, 10, 50, 50]]),
...     class_id=np.array([0]),
... )
>>> detections_2 = sv.Detections(
...     xyxy=np.array([[40, 40, 90, 90]]),
...     class_id=np.array([0]),
... )
>>> comparison_annotator = sv.ComparisonAnnotator()
>>> annotated_frame = comparison_annotator.annotate(
...     scene=image.copy(),
...     detections_1=detections_1,
...     detections_2=detections_2
... )

comparison-annotator-example

Source code in src/supervision/annotators/core.py
@ensure_cv2_image_for_class_method
def annotate(
    self, scene: ImageType, detections_1: Detections, detections_2: Detections
) -> ImageType:
    """Highlights the differences between two sets of detections.

    Args:
        scene: The image where detections will be drawn.
            `ImageType` is a flexible type, accepting either `numpy.ndarray`
            or `PIL.Image.Image`. Grayscale arrays may have shape `(H, W)`
            or `(H, W, 1)`; regions are blended with the first (blue) channel
            of their color, as OpenCV draws boxes and polygons.
        detections_1: The first set of detections or predictions.
        detections_2: The second set of detections to compare or
            ground truth.

    Returns:
        The annotated image.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> detections_1 = sv.Detections(
        ...     xyxy=np.array([[10, 10, 50, 50]]),
        ...     class_id=np.array([0]),
        ... )
        >>> detections_2 = sv.Detections(
        ...     xyxy=np.array([[40, 40, 90, 90]]),
        ...     class_id=np.array([0]),
        ... )
        >>> comparison_annotator = sv.ComparisonAnnotator()
        >>> annotated_frame = comparison_annotator.annotate(
        ...     scene=image.copy(),
        ...     detections_1=detections_1,
        ...     detections_2=detections_2
        ... )

        ```

    ![comparison-annotator-example](https://media.roboflow.com/
    supervision-annotator-examples/comparison-annotator-example.png)
    """
    if not isinstance(scene, np.ndarray):
        return scene
    if detections_1.is_empty() and detections_2.is_empty():
        return scene

    use_obb = self._use_obb(detections_1, detections_2)
    use_mask = self._use_mask(detections_1, detections_2)

    if use_obb:
        mask_1 = self._mask_from_obb(scene, detections_1)
        mask_2 = self._mask_from_obb(scene, detections_2)

    elif use_mask:
        mask_1 = self._mask_from_mask(scene, detections_1)
        mask_2 = self._mask_from_mask(scene, detections_2)

    else:
        mask_1 = self._mask_from_xyxy(scene, detections_1)
        mask_2 = self._mask_from_xyxy(scene, detections_2)

    mask_overlap = mask_1 & mask_2
    mask_1 = mask_1 & ~mask_overlap
    mask_2 = mask_2 & ~mask_overlap

    color_layer = np.zeros_like(scene, dtype=np.uint8)
    color_layer[mask_overlap] = _color_for_canvas(
        self.color_overlap.as_bgr(), scene
    )
    color_layer[mask_1] = _color_for_canvas(self.color_1.as_bgr(), scene)
    color_layer[mask_2] = _color_for_canvas(self.color_2.as_bgr(), scene)

    if scene.ndim == 3 and scene.shape[2] == 4:
        union = mask_overlap | mask_1 | mask_2
        alpha = union[..., np.newaxis].astype(np.float32) * self.opacity
        blended = _composite_over_bgra(scene, color_layer[..., :3], alpha)
        # Match the original integer truncation for fully opaque scenes.
        opaque = union & (scene[..., 3] == 255)
        blended[opaque, :3] = (1 - self.opacity) * scene[
            opaque, :3
        ] + self.opacity * color_layer[opaque, :3]
        scene[:] = blended
    else:
        scene[mask_overlap] = (1 - self.opacity) * scene[
            mask_overlap
        ] + self.opacity * color_layer[mask_overlap]
        scene[mask_1] = (1 - self.opacity) * scene[
            mask_1
        ] + self.opacity * color_layer[mask_1]
        scene[mask_2] = (1 - self.opacity) * scene[
            mask_2
        ] + self.opacity * color_layer[mask_2]

    self._draw_labels(scene)

    return scene

supervision.annotators.utils.ColorLookup

Bases: Enum

Enumeration class to define strategies for mapping colors to annotations.

This enum supports four different lookup strategies
  • INDEX: Colors are determined by the index of the detection within the scene.
  • CLASS: Colors are determined by the class label of the detected object.
  • TRACK: Colors are determined by the tracking identifier of the object.
  • KEYPOINT: Colors are determined by the keypoint index within each skeleton. Only valid for keypoint annotators.
Source code in src/supervision/annotators/utils.py
class ColorLookup(Enum):
    """Enumeration class to define strategies for mapping colors to annotations.

    This enum supports four different lookup strategies:
        - `INDEX`: Colors are determined by the index of the detection within the scene.
        - `CLASS`: Colors are determined by the class label of the detected object.
        - `TRACK`: Colors are determined by the tracking identifier of the object.
        - `KEYPOINT`: Colors are determined by the keypoint index within each skeleton.
            Only valid for keypoint annotators.
    """

    INDEX = "index"
    CLASS = "class"
    TRACK = "track"
    KEYPOINT = "keypoint"

    @classmethod
    def list(cls) -> list[str]:
        return list(map(lambda c: c.value, cls))

Comments