diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 84345f0e..eee18767 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,6 +40,8 @@ repos: rev: v2.25.0 hooks: - id: pyproject-fmt + additional_dependencies: + - "tomli>=2.0.1" - repo: https://github.com/abravalheri/validate-pyproject rev: v0.25 diff --git a/src/supervision/detection/core.py b/src/supervision/detection/core.py index 23d6edbe..a131b6c9 100644 --- a/src/supervision/detection/core.py +++ b/src/supervision/detection/core.py @@ -19,7 +19,11 @@ from supervision.detection.tools.transformers import ( process_transformers_v4_segmentation_result, process_transformers_v5_segmentation_result, ) -from supervision.detection.utils._typing import _DetectionDataType, _MetadataType +from supervision.detection.utils._typing import ( + _DetectionDataType, + _DetectionDataValueType, + _MetadataType, +) from supervision.detection.utils.boxes import obb_polygon_area, xyxyxyxy_to_xyxy from supervision.detection.utils.converters import ( mask_to_xyxy, @@ -2297,8 +2301,76 @@ class Detections: raise ValueError(f"{anchor} is not supported.") + def get_data(self, key: str) -> _DetectionDataValueType | None: + """Get a value from the detection data dictionary. + + Args: + key: Data field name. + + Returns: + The stored data value, or `None` when the key is absent. + + Example: + >>> import numpy as np + >>> from supervision import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 1, 1]]), + ... data={"class_name": np.array(["cat"])}, + ... ) + >>> detections.get_data("class_name").tolist() + ['cat'] + """ + return self.data.get(key) + + def select( + self, + index: int | np.integer[Any] | slice | list[int] | npt.NDArray[np.generic], + ) -> Detections: + """Get a subset of the Detections object. + + Args: + index: Row index, indices, slice, or boolean mask selecting detections. + + Returns: + A `Detections` instance containing the selected rows. Empty detections + are returned unchanged. + + Example: + >>> import numpy as np + >>> from supervision import Detections + >>> detections = Detections(xyxy=np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) + >>> detections.select([1]).xyxy.tolist() + [[1, 1, 2, 2]] + """ + if len(self) == 0: + return self + if isinstance(index, (int, np.integer)): + index = [int(index)] + array_index = cast( + slice | list[int] | npt.NDArray[np.integer | np.bool_], index + ) + return Detections( + xyxy=self.xyxy[array_index], + mask=self.mask[cast(Any, array_index)] if self.mask is not None else None, + confidence=( + self.confidence[array_index] if self.confidence is not None else None + ), + class_id=self.class_id[array_index] if self.class_id is not None else None, + tracker_id=( + self.tracker_id[array_index] if self.tracker_id is not None else None + ), + data=get_data_item(self.data, array_index), + metadata=self.metadata, + ) + def __getitem__( - self, index: int | slice | list[int] | npt.NDArray[np.generic] | str + self, + index: int + | np.integer[Any] + | slice + | list[int] + | npt.NDArray[np.generic] + | str, ) -> Detections | list[Any] | npt.NDArray[np.generic] | None: """ Get a subset of the Detections object or access an item from its data field. @@ -2331,27 +2403,8 @@ class Detections: ``` """ if isinstance(index, str): - return self.data.get(index) - if len(self) == 0: - return self - if isinstance(index, int): - index = [index] - array_index = cast( - slice | list[int] | npt.NDArray[np.integer | np.bool_], index - ) - return Detections( - xyxy=self.xyxy[array_index], - mask=self.mask[cast(Any, array_index)] if self.mask is not None else None, - confidence=( - self.confidence[array_index] if self.confidence is not None else None - ), - class_id=self.class_id[array_index] if self.class_id is not None else None, - tracker_id=( - self.tracker_id[array_index] if self.tracker_id is not None else None - ), - data=get_data_item(self.data, array_index), - metadata=self.metadata, - ) + return self.get_data(index) + return self.select(index) def __setitem__(self, key: str, value: npt.NDArray[np.generic] | list[Any]) -> None: """ @@ -2568,7 +2621,7 @@ class Detections: overlap_metric=overlap_metric, ) - return cast(Detections, self[indices]) + return self.select(indices) def with_nmm( self, @@ -2665,7 +2718,7 @@ class Detections: result: list[Detections] = [] for merge_group in merge_groups: - group = [cast(Detections, self[i]) for i in merge_group] + group = [self.select(i) for i in merge_group] result.append(_merge_detection_group(group)) return Detections.merge(result) diff --git a/src/supervision/detection/tools/smoother.py b/src/supervision/detection/tools/smoother.py index 77305e29..a504c18f 100644 --- a/src/supervision/detection/tools/smoother.py +++ b/src/supervision/detection/tools/smoother.py @@ -1,7 +1,6 @@ import warnings from collections import defaultdict, deque from copy import deepcopy -from typing import cast import numpy as np @@ -116,7 +115,7 @@ class DetectionsSmoother: tracker_id_value = detections.tracker_id[detection_idx] tracker_id = int(tracker_id_value) - self.tracks[tracker_id].append(cast(Detections, detections[detection_idx])) + self.tracks[tracker_id].append(detections.select(detection_idx)) for track_id in self.tracks.keys(): if track_id not in detections.tracker_id: @@ -152,7 +151,7 @@ class DetectionsSmoother: return None ret = deepcopy(valid[0]) - ret.xyxy = np.mean([d.xyxy for d in valid], axis=0) + ret.xyxy = np.mean(np.stack([d.xyxy for d in valid], axis=0), axis=0) # Average confidence only over frames that carry it; frames with # confidence=None contribute nothing to the mean. Retain None when # no frame in the window carries confidence. diff --git a/src/supervision/key_points/core.py b/src/supervision/key_points/core.py index f0b10a0c..c3337986 100644 --- a/src/supervision/key_points/core.py +++ b/src/supervision/key_points/core.py @@ -10,7 +10,10 @@ import numpy.typing as npt from supervision.config import CLASS_NAME_DATA_FIELD from supervision.detection.core import Detections -from supervision.detection.utils._typing import _DetectionDataType +from supervision.detection.utils._typing import ( + _DetectionDataType, + _DetectionDataValueType, +) from supervision.detection.utils.internal import get_data_item, is_data_equal from supervision.detection.utils.iou_and_nms import ( OverlapMetric, @@ -908,51 +911,49 @@ class KeyPoints: data=data_selected, ) - def __getitem__( - self, - index: Index1D | Index2D | str, - ) -> KeyPoints | npt.NDArray[np.generic] | list[Any] | None: - """ - Get a subset of the KeyPoints object or access an item from its data field. - - Supports detection-level (skeleton) filtering, keypoint-level (anchor) - filtering, combined tuple indexing, and data field access by string key. + def get_data(self, key: str) -> _DetectionDataValueType | None: + """Get a value from the keypoint data dictionary. Args: - index: The index, indices, or key to access a subset of the KeyPoints - or an item from the data. + key: Data field name. Returns: - A subset of the KeyPoints object or an item from the data field. + The stored data value, or `None` when the key is absent. - Examples: - ```python - import supervision as sv - - key_points = sv.KeyPoints(...) - - # detection-level filtering (returns KeyPoints) - high_conf = key_points[key_points.detection_confidence > 0.5] - class_0 = key_points[key_points.class_id == 0] - - # keypoint-level filtering (returns KeyPoints) - visible = key_points[key_points.keypoint_confidence > 0.3] - - # indexing - first = key_points[0] - first_two = key_points[0:2] - subset = key_points[[0, 2]] - - # anchor selection (uniform across all skeletons) - nose_and_eyes = key_points[:, [0, 1, 2]] - - # data field access - class_names = key_points['class_name'] - ``` + Example: + >>> import numpy as np + >>> from supervision import KeyPoints + >>> key_points = KeyPoints( + ... xy=np.array([[[0, 0]]]), + ... data={"class_name": np.array(["person"])}, + ... ) + >>> key_points.get_data("class_name").tolist() + ['person'] """ - if isinstance(index, str): - return self.data.get(index) + return self.data.get(key) + def select( + self, + index: Index1D | Index2D, + ) -> KeyPoints: + """Get a subset of the KeyPoints object. + + Supports detection-level (skeleton) filtering, keypoint-level (anchor) + filtering, and combined tuple indexing. + + Args: + index: Index, indices, slice, or boolean mask selecting key points. + + Returns: + A new `KeyPoints` instance containing the selected rows or anchors. + + Example: + >>> import numpy as np + >>> from supervision import KeyPoints + >>> key_points = KeyPoints(xy=np.array([[[0, 1]], [[2, 3]]])) + >>> key_points.select([1]).xy.tolist() + [[[2, 3]]] + """ if isinstance(index, np.ndarray) and index.ndim == 2 and index.dtype == bool: return self._get_by_2d_bool_mask(cast(npt.NDArray[np.bool_], index)) @@ -1045,6 +1046,52 @@ class KeyPoints: data=data_selected, ) + def __getitem__( + self, + index: Index1D | Index2D | str, + ) -> KeyPoints | npt.NDArray[np.generic] | list[Any] | None: + """ + Get a subset of the KeyPoints object or access an item from its data field. + + Supports detection-level (skeleton) filtering, keypoint-level (anchor) + filtering, combined tuple indexing, and data field access by string key. + + Args: + index: The index, indices, or key to access a subset of the KeyPoints + or an item from the data. + + Returns: + A subset of the KeyPoints object or an item from the data field. + + Examples: + ```python + import supervision as sv + + key_points = sv.KeyPoints(...) + + # detection-level filtering (returns KeyPoints) + high_conf = key_points[key_points.detection_confidence > 0.5] + class_0 = key_points[key_points.class_id == 0] + + # keypoint-level filtering (returns KeyPoints) + visible = key_points[key_points.keypoint_confidence > 0.3] + + # indexing + first = key_points[0] + first_two = key_points[0:2] + subset = key_points[[0, 2]] + + # anchor selection (uniform across all skeletons) + nose_and_eyes = key_points[:, [0, 1, 2]] + + # data field access + class_names = key_points['class_name'] + ``` + """ + if isinstance(index, str): + return self.get_data(index) + return self.select(index) + def __setitem__(self, key: str, value: npt.NDArray[np.generic] | list[Any]) -> None: """ Set a value in the data dictionary of the `sv.KeyPoints` object. @@ -1205,7 +1252,7 @@ class KeyPoints: overlap_metric=overlap_metric, ) - return cast(KeyPoints, self[keep]) + return self.select(keep) def as_detections( self, selected_keypoint_indices: Iterable[int] | None = None @@ -1275,6 +1322,6 @@ class KeyPoints: detections = Detections(xyxy=xyxy, confidence=confidence) detections.class_id = self.class_id detections.data = self.data - detections = cast(Detections, detections[cast(Any, detections.area) > 0]) + detections = detections.select(cast(Any, detections.area) > 0) return detections diff --git a/src/supervision/metrics/detection.py b/src/supervision/metrics/detection.py index 558ceecd..4821b730 100644 --- a/src/supervision/metrics/detection.py +++ b/src/supervision/metrics/detection.py @@ -239,9 +239,8 @@ def _split_detections_by_outcome( filtered_predictions = predictions else: prediction_confidence = np.asarray(predictions.confidence, dtype=np.float32) - filtered_predictions = cast( - Detections, - predictions[prediction_confidence >= conf_threshold], + filtered_predictions = predictions.select( + prediction_confidence >= conf_threshold ) filtered_prediction_class_ids = filtered_predictions.class_id @@ -258,17 +257,17 @@ def _split_detections_by_outcome( if prediction_count == 0: fn_indices = list(range(target_count)) return ( - cast(Detections, filtered_predictions[tp_indices]), - cast(Detections, filtered_predictions[fp_indices]), - cast(Detections, targets[fn_indices]), + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), ) if target_count == 0: fp_indices = list(range(prediction_count)) return ( - cast(Detections, filtered_predictions[tp_indices]), - cast(Detections, filtered_predictions[fp_indices]), - cast(Detections, targets[fn_indices]), + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), ) # IoU computation mirrors evaluate_detection_batch — keep in sync if either changes. @@ -341,9 +340,9 @@ def _split_detections_by_outcome( fn_indices.extend(cross_class_target_indices) return ( - cast(Detections, filtered_predictions[tp_indices]), - cast(Detections, filtered_predictions[fp_indices]), - cast(Detections, targets[fn_indices]), + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), ) @@ -483,7 +482,8 @@ def _annotate_detection_panel( title_thickness, cv2.LINE_AA, ) - return cast(npt.NDArray[np.uint8], panel) + panel_array: npt.NDArray[np.uint8] = panel + return panel_array def _save_detection_validation_visualization( diff --git a/src/supervision/tracker/byte_tracker/core.py b/src/supervision/tracker/byte_tracker/core.py index 5b174c73..249bc6c3 100644 --- a/src/supervision/tracker/byte_tracker/core.py +++ b/src/supervision/tracker/byte_tracker/core.py @@ -1,5 +1,3 @@ -from typing import cast - import numpy as np import numpy.typing as npt from deprecate import ( # type: ignore[import-untyped,unused-ignore] @@ -146,8 +144,7 @@ class ByteTrack: tracks[i_track].external_track_id ) - filtered = detections[detections.tracker_id != -1] - return cast(Detections, filtered) + return detections.select(detections.tracker_id != -1) else: detections = Detections.empty() diff --git a/tests/detection/test_core.py b/tests/detection/test_core.py index 8070613d..d4033337 100644 --- a/tests/detection/test_core.py +++ b/tests/detection/test_core.py @@ -249,6 +249,16 @@ def test_detections_non_bool_mask_warns_with_migration_path() -> None: ), DoesNotRaise(), ), + # Scenario: Select a single detection using a NumPy integer index. + # Expected: A Detections object containing only that element. + ( + DETECTIONS, + np.int64(0), + _create_detections( + xyxy=[[2254, 906, 2447, 1353]], confidence=[0.90538], class_id=[0] + ), + DoesNotRaise(), + ), # Scenario: Select a range of detections using a slice. # Expected: Detections within the slice range are returned. ( @@ -296,7 +306,7 @@ def test_detections_non_bool_mask_warns_with_migration_path() -> None: ) def test_getitem( detections: Detections, - index: int | slice | list[int] | np.ndarray, + index: int | np.integer | slice | list[int] | np.ndarray, expected_result: Detections | None, exception: Exception, ) -> None: @@ -310,6 +320,28 @@ def test_getitem( assert result == expected_result +def test_select_returns_detection_subset() -> None: + """Select returns a typed Detections subset for row indexes.""" + result = TEST_DET_1.select([0, 2]) + + assert result == Detections( + xyxy=np.array([[10, 10, 20, 20], [50, 50, 60, 60]]), + mask=np.array([TEST_MASK, TEST_MASK]), + confidence=np.array([0.1, 0.3]), + class_id=np.array([1, 3]), + tracker_id=np.array([1, 3]), + data={"some_key": [1, 3], "other_key": [["1", "2"], ["5", "6"]]}, + ) + + +def test_get_data_returns_detection_data_value() -> None: + """Get data returns the stored data value or None.""" + result = TEST_DET_1.get_data("some_key") + + assert result == [1, 2, 3] + assert TEST_DET_1.get_data("missing") is None + + @pytest.mark.parametrize( ("detections_list", "expected_result", "exception"), [ diff --git a/tests/key_points/test_core.py b/tests/key_points/test_core.py index e1848064..2e86e03f 100644 --- a/tests/key_points/test_core.py +++ b/tests/key_points/test_core.py @@ -374,6 +374,36 @@ def test_key_points_getitem(key_points, index, expected_result, exception): assert result == expected_result +def test_key_points_select_returns_subset() -> None: + """Select returns a typed KeyPoints subset for row indexes.""" + result = KEY_POINTS.select([0, 2]) + + assert result == _create_key_points( + xy=[ + [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]], + [[20, 21], [22, 23], [24, 25], [26, 27], [28, 29]], + ], + confidence=[ + [0.8, 0.2, 0.6, 0.1, 0.5], + [0.1, 0.6, 0.8, 0.2, 0.7], + ], + class_id=[0, 2], + ) + + +def test_key_points_get_data_returns_data_value() -> None: + """Get data returns the stored data value or None.""" + key_points = _create_key_points( + xy=[[[0, 1], [2, 3]]], + confidence=[[0.8, 0.2]], + class_id=[0], + ) + key_points["custom_data"] = ["value1"] + + assert key_points.get_data("custom_data") == ["value1"] + assert key_points.get_data("missing") is None + + KEY_POINTS_WITH_DET_CONF = _create_key_points( xy=[ [[0, 1], [2, 3], [4, 5]],