diff --git a/supervision/__init__.py b/supervision/__init__.py index 28d29813..eb04df36 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -1,11 +1,6 @@ __version__ = "0.11.1" -from supervision.annotators.composable import ( - DetectionAnnotator, - SegmentationAnnotator, - TrackAnnotator, - TrackedDetectionAnnotator, -) +from supervision.annotators.composable import DetectionAnnotator, SegmentationAnnotator from supervision.annotators.core import ( BoxAnnotator, BoxMaskAnnotator, @@ -14,7 +9,7 @@ from supervision.annotators.core import ( LabelAnnotator, MaskAnnotator, PillowLabelAnnotator, - TrackAnnotator, + build_label_formatter, ) from supervision.classification.core import Classifications from supervision.dataset.core import ( @@ -25,7 +20,6 @@ from supervision.dataset.core import ( from supervision.detection.core import Detections from supervision.detection.line_counter import LineZone, LineZoneAnnotator from supervision.detection.tools.polygon_zone import PolygonZone, PolygonZoneAnnotator -from supervision.detection.track import TrackStorage from supervision.detection.utils import ( box_iou_batch, filter_polygons_by_area, diff --git a/supervision/annotators/composable.py b/supervision/annotators/composable.py index a3db9e7c..5ee3cd31 100644 --- a/supervision/annotators/composable.py +++ b/supervision/annotators/composable.py @@ -3,14 +3,8 @@ from typing import List, Optional import numpy as np -from supervision.annotators.core import ( - BoxAnnotator, - LabelAnnotator, - MaskAnnotator, - TrackAnnotator, -) +from supervision.annotators.core import BoxAnnotator, LabelAnnotator, MaskAnnotator from supervision.detection.core import Detections -from supervision.detection.track import TrackStorage class ComposableAnnotator(ABC): @@ -32,8 +26,6 @@ class ComposableAnnotator(ABC): detections=detections, labels=labels, ) - elif isinstance(annotator, TrackAnnotator): - scene = annotator.annotate(scene=scene) else: scene = annotator.annotate(scene=scene, detections=detections) return scene @@ -100,38 +92,3 @@ class SegmentationAnnotator(ComposableAnnotator): ] if not skip_label: self.annotators.append(LabelAnnotator(color_by_track=color_by_track)) - - -class TrackedDetectionAnnotator(ComposableAnnotator): - """ - A class for drawing object trajectories, bounding box and tracker ids on an image using provided detections. - User have freedom to choose color based on class_ids or tracker_ids - Example: - ```python - >>> import supervision as sv - - >>> classes = ['person', ...] - >>> image = ... - >>> detections = sv.Detections(...) - - >>> tracked_detection_annotator = sv.TrackedDetectionAnnotator() - >>> annotated_frame = tracked_detection_annotator.annotate( - ... scene=image.copy(), - ... detections=detections - ... ) - ``` - """ - - def __init__( - self, - tracks: TrackStorage, - color_by_track: bool = False, - skip_label: bool = False, - ): - super().__init__() - self.annotators = [ - BoxAnnotator(color_by_track=color_by_track), - TrackAnnotator(tracks=tracks, color_by_track=color_by_track), - ] - if not skip_label: - self.annotators.append(LabelAnnotator(color_by_track=color_by_track)) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 0305c67a..1231bf07 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -1,13 +1,12 @@ import os.path from abc import ABC, abstractmethod -from typing import List, Optional, Union +from typing import Callable, List, Optional, Union import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont from supervision.detection.core import Detections -from supervision.detection.track import TrackStorage from supervision.draw.color import Color, ColorPalette @@ -172,6 +171,19 @@ class MaskAnnotator(BaseAnnotator): return scene +def default_label_formatter( + detections: Detections, +) -> List[str]: + return [str(class_id) for class_id in detections.class_id] + + +def build_label_formatter(classes: List[str]) -> Callable[[Detections], List[str]]: + def default_label_formatter(detections: Detections) -> List[str]: + return [classes[class_id] for class_id in detections.class_id] + + return default_label_formatter + + class LabelAnnotator(BaseAnnotator): """ A class for putting text on an image using provided detections. @@ -189,20 +201,30 @@ class LabelAnnotator(BaseAnnotator): text_thickness: int = 1, text_padding: int = 10, color_by_track: bool = False, + classes: Optional[List[str]] = None, + label_formatter: Optional[ + Callable[[Detections], List[str]] + ] = default_label_formatter, ): + """ + Args: + color_by_track: pick color by tracker id + classes: Optional list of class name + label_formatter: Optional callback function for label generator, avoided if classes is provided + """ self.color: Union[Color, ColorPalette] = color - self.thickness: int = thickness self.text_color: Color = text_color self.text_scale: float = text_scale self.text_thickness: int = text_thickness self.text_padding: int = text_padding self.color_by_track = color_by_track + self.classes = classes + self.label_formatter = label_formatter def annotate( self, scene: np.ndarray, detections: Detections, - labels: Optional[List[str]] = None, ) -> np.ndarray: """ Draws text on the frame using the detections provided and label. @@ -210,7 +232,6 @@ class LabelAnnotator(BaseAnnotator): Args: scene (np.ndarray): The image on which the bounding boxes will be drawn detections (Detections): The detections for which the bounding boxes will be drawn - labels (Optional[List[str]]): An optional list of labels corresponding to each detection. If `labels` are not provided, corresponding `class_id` will be used as label. Returns: np.ndarray: The image with the bounding boxes drawn on it @@ -231,12 +252,18 @@ class LabelAnnotator(BaseAnnotator): >>> annotated_frame = label_annotator.annotate( ... scene=image.copy(), ... detections=detections, - ... labels=labels ... ) ``` """ font = cv2.FONT_HERSHEY_SIMPLEX + labels = None + if self.classes: + label_formatter = build_label_formatter(self.classes) + labels = label_formatter(detections) + else: + labels = self.label_formatter(detections=detections) + for i in range(len(detections)): x1, y1, x2, y2 = detections.xyxy[i].astype(int) if self.color_by_track: @@ -374,85 +401,8 @@ class BoxMaskAnnotator(BaseAnnotator): return scene -class TrackAnnotator(BaseAnnotator): - """ - Initialize TrackAnnotator - """ - - def __init__( - self, - tracks: TrackStorage, - color: Union[Color, ColorPalette] = ColorPalette.default(), - thickness: int = 2, - color_by_track: bool = False, - ): - self.track_storage = tracks - self.color: Union[Color, ColorPalette] = color - self.thickness: int = thickness - self.boundry_tolerance = 20 - self.color_by_track = color_by_track - - def annotate( - self, - scene: np.ndarray, - ) -> np.ndarray: - """ - Draws the object trajectory on the frame using the trace provided. - Attributes: - scene (np.ndarray): The image on which the object trajectories will be drawn. - tracks (TrackStorage): The track storage that will be used to draw the previous and current position. - - Returns: - np.ndarray: The image with the object trajectories on it. - ```python - >>> import supervision as sv - >>> track_storage = sv.TrackStorage() - >>> track_annotator = sv.TrackAnnotator(track_storage) - >>> for frame in sv.get_video_frames_generator(source_path='source_video.mp4'): - >>> detections = sv.Detections(...) - >>> tracked_objects = tracker(...) - >>> tracked_detections = sv.Detections(tracked_objects) - >>> track_storage.update(tracked_detections) - >>> track_annotator.annotate(scene) - """ - img_h, img_w, _ = scene.shape - unique_ids = np.unique(self.track_storage.tracker_id) - for unique_id in unique_ids: - valid = np.where(self.track_storage.tracker_id == unique_id)[0] - if valid.shape[0] == 0: - continue - frames = self.track_storage.frame_id[valid] - latest_frame = np.argmax(frames) - points_to_draw = self.track_storage.xy[valid] - - n_pts = points_to_draw.shape[0] - headx, heady = int(points_to_draw[latest_frame][0]), int( - points_to_draw[latest_frame][1] - ) - - if headx > self.boundry_tolerance and heady > self.boundry_tolerance: - idx = None - if not self.color_by_track and self.track_storage.class_id.shape[0] > 0: - class_id = self.track_storage.class_id[valid][0] - idx = int(class_id) - if self.color_by_track or idx is None: - idx = int(unique_id) - color = ( - self.color.by_idx(idx) - if isinstance(self.color, ColorPalette) - else self.color - ) - - for i in range(n_pts - 1): - px, py = int(points_to_draw[i][0]), int(points_to_draw[i][1]) - qx, qy = int(points_to_draw[i + 1][0]), int( - points_to_draw[i + 1][1] - ) - cv2.line(scene, (px, py), (qx, qy), color.as_bgr(), self.thickness) - scene = cv2.circle( - scene, (headx, heady), int(10), color.as_bgr(), thickness=-1 - ) - return scene +def default_label_formatter(detections: Detections) -> List[str]: + return [str(class_id) for class_id in detections.class_id] class PillowLabelAnnotator(BaseAnnotator): diff --git a/supervision/detection/track.py b/supervision/detection/track.py deleted file mode 100644 index 8027c34b..00000000 --- a/supervision/detection/track.py +++ /dev/null @@ -1,86 +0,0 @@ -from typing import Optional, Tuple - -import numpy as np - -from supervision.detection.core import Detections -from supervision.geometry.core import Position - - -class TrackStorage: - """ - Trace the object trajectory with Detections with tracker id - """ - - def __init__( - self, - position: Position = Position.CENTER, - max_length: int = 10, - ): - """ - Initialize the track storage to store tracked detections from tracker - Args: - position [sv.Position]: Trace position whethere mid-point or bottom center point - max_length [int]: Length of previous detections to annotate - Detections objects are stored as numpy ndarray with #counter, x, y, class, track_id - - Example: - ```python - >>> import supervision as sv - >>> track_storage = sv.TrackStorage() - >>> for frame in sv.get_video_frames_generator(source_path='source_video.mp4'): - >>> detections = sv.Detections(...) - >>> tracked_objects = tracker(...) - >>> tracked_detections = sv.Detections(tracked_objects) - >>> track_storage.update(tracked_detections) - """ - self.position = position - self.max_length = max_length - self.frame_counter = 0 - - self.xy = np.zeros((0, 2)) - self.confidence = np.zeros(0) - self.class_id = np.zeros(0) - self.tracker_id = np.zeros(0) - self.frame_id = np.zeros(0) - - def update(self, frame_counter: int, detections: Detections) -> None: - n_dets = detections.xyxy.shape[0] - if n_dets > 0 and detections.tracker_id.shape[0] > 0: - xy = detections.get_anchor_coordinates(anchor=self.position) - - self.tracker_id = np.append(self.tracker_id, detections.tracker_id, axis=0) - - self.xy = np.append(self.xy, xy, axis=0) - if detections.class_id is not None: - self.class_id = np.append(self.class_id, detections.class_id, axis=0) - if detections.confidence is not None: - self.confidence = np.append( - self.confidence, detections.confidence, axis=0 - ) - self.frame_id = np.append( - self.frame_id, np.full((n_dets), fill_value=frame_counter), axis=0 - ) - self.frame_counter = frame_counter - self._remove_lost(tracker_ids=detections.tracker_id) - self._remove_previous() - - def _remove_previous(self) -> None: - to_remove_frames = self.frame_counter - self.max_length - if self.frame_id.shape[0] > 0: - valid = self.frame_id > to_remove_frames - self._remove(valid) - - def _remove_lost(self, tracker_ids) -> None: - if self.tracker_id.shape[0] > 0: - valid = np.isin(self.tracker_id, tracker_ids) - self._remove(valid) - - def _remove(self, valid: Optional[Tuple]) -> None: - if valid.size > 0: - self.xy = self.xy[valid] - self.frame_id = self.frame_id[valid] - self.tracker_id = self.tracker_id[valid] - if self.confidence.shape[0] > 0: - self.confidence = self.confidence[valid] - if self.class_id.shape[0] > 0: - self.class_id = self.class_id[valid]