supervision metrics module

This commit is contained in:
LinasKo
2024-08-27 14:48:17 +03:00
parent c31d96dabe
commit fe27e44081
9 changed files with 971 additions and 920 deletions
+6 -6
View File
@@ -1,9 +1,4 @@
from supervision.metrics.core import (
CLASS_ID_NONE,
Metric,
MetricTarget,
UnsupportedMetricTargetError,
)
from supervision.metrics.core import CLASS_ID_NONE, Metric, MetricTarget
from supervision.metrics.intersection_over_union import (
IntersectionOverUnion,
IntersectionOverUnionResult,
@@ -12,3 +7,8 @@ from supervision.metrics.mean_average_precision import (
MeanAveragePrecision,
MeanAveragePrecisionResult,
)
from supervision.metrics.utils.object_size import (
ObjectSizeCategory,
get_detection_size_category,
get_object_size_category,
)
+1 -204
View File
@@ -2,17 +2,9 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, Iterator, Set, Tuple
import numpy as np
import numpy.typing as npt
from supervision import config
from supervision.detection.core import Detections
from supervision.metrics.utils import pad_mask
from typing import Any
CLASS_ID_NONE = -1
CONFIDENCE_NONE = -1
"""Used by metrics module as class ID, when none is present"""
@@ -43,16 +35,6 @@ class Metric(ABC):
"""
raise NotImplementedError
def _ensure_pandas_installed(self):
try:
import pandas # noqa
except ImportError:
raise ImportError(
"Function `to_pandas` requires the `metrics` extra to be installed."
" Run `pip install 'supervision[metrics]'` or"
" `poetry add supervision -E metrics`."
)
class MetricTarget(Enum):
"""
@@ -66,188 +48,3 @@ class MetricTarget(Enum):
BOXES = "boxes"
MASKS = "masks"
ORIENTED_BOUNDING_BOXES = "obb"
class UnsupportedMetricTargetError(Exception):
"""
Raised when a metric does not support the specified target. (and never will!)
If the support might be added in the future, raise `NotImplementedError` instead.
"""
def __init__(self, metric: Metric, target: MetricTarget):
super().__init__(f"Metric {metric} does not support target {target}")
class MetricData:
"""
A container for detection contents, decouple from Detections.
While a np.ndarray work for xyxy and obb, this approach solves
the mask concatenation problem.
"""
def __init__(self, metric_target: MetricTarget, class_agnostic: bool = False):
self._metric_target = metric_target
self._class_agnostic = class_agnostic
self.confidence = np.array([], dtype=np.float32)
self.class_id = np.array([], dtype=int)
self.data: npt.NDArray = self._get_empty_data()
def update(self, detections: Detections):
"""Add new detections to the store."""
new_data = self._get_content(detections)
self._validate_shape(new_data)
if self._metric_target == MetricTarget.BOXES:
self._append_boxes(new_data)
elif self._metric_target == MetricTarget.MASKS:
self._append_mask(new_data)
elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
self.data = np.vstack((self.data, new_data))
confidence = self._get_confidence(detections)
self._append_confidence(confidence)
class_id = self._get_class_id(detections)
self._append_class_id(class_id)
if len(self.class_id) != len(self.confidence) or len(self.class_id) != len(
self.data
):
raise ValueError(
f"Inconsistent data length: class_id={len(class_id)},"
f" confidence={len(confidence)}, data={len(new_data)}"
)
def get_classes(self) -> Set[int]:
"""Return all class IDs."""
return set(self.class_id)
def get_subset_by_class(self, class_id: int) -> MetricData:
"""Return data, confidence and class_id for a specific class."""
mask = self.class_id == class_id
new_data_obj = MetricData(self._metric_target)
new_data_obj.data = self.data[mask]
new_data_obj.confidence = self.confidence[mask]
new_data_obj.class_id = self.class_id[mask]
return new_data_obj
def __len__(self) -> int:
return len(self.data)
def _get_content(self, detections: Detections) -> npt.NDArray:
"""Return boxes, masks or oriented bounding boxes from the data."""
if self._metric_target == MetricTarget.BOXES:
return detections.xyxy
if self._metric_target == MetricTarget.MASKS:
return (
detections.mask
if detections.mask is not None
else self._get_empty_data()
)
if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
obb = detections.data.get(
config.ORIENTED_BOX_COORDINATES, self._get_empty_data()
)
return np.ndarray(obb, dtype=np.float32)
raise ValueError(f"Invalid metric target: {self._metric_target}")
def _get_class_id(self, detections: Detections) -> npt.NDArray[np.int_]:
if self._class_agnostic or detections.class_id is None:
return np.array([CLASS_ID_NONE] * len(detections), dtype=int)
return detections.class_id
def _get_confidence(self, detections: Detections) -> npt.NDArray[np.float32]:
if detections.confidence is None:
return np.full(len(detections), -1, dtype=np.float32)
return detections.confidence
def _append_class_id(self, new_class_id: npt.NDArray[np.int_]) -> None:
self.class_id = np.hstack((self.class_id, new_class_id))
def _append_confidence(self, new_confidence: npt.NDArray[np.float32]) -> None:
self.confidence = np.hstack((self.confidence, new_confidence))
def _append_boxes(self, new_boxes: npt.NDArray[np.float32]) -> None:
"""Stack new xyxy or obb boxes on top of stored boxes."""
if self._metric_target not in [
MetricTarget.BOXES,
MetricTarget.ORIENTED_BOUNDING_BOXES,
]:
raise ValueError("This method is only for box data.")
self.data = np.vstack((self.data, new_boxes))
def _append_mask(self, new_mask: npt.NDArray[np.bool_]) -> None:
"""Stack new mask onto stored masks. Expand the shapes if necessary."""
if self._metric_target != MetricTarget.MASKS:
raise ValueError("This method is only for mask data.")
self._validate_mask_shape(new_mask)
new_width = max(self.data.shape[1], new_mask.shape[1])
new_height = max(self.data.shape[2], new_mask.shape[2])
data = pad_mask(self.data, (new_width, new_height))
new_mask = pad_mask(new_mask, (new_width, new_height))
self.data = np.vstack((data, new_mask))
def _get_empty_data(self) -> npt.NDArray:
if self._metric_target == MetricTarget.BOXES:
return np.empty((0, 4), dtype=np.float32)
if self._metric_target == MetricTarget.MASKS:
return np.empty((0, 0, 0), dtype=bool)
if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
return np.empty((0, 8), dtype=np.float32)
raise ValueError(f"Invalid metric target: {self._metric_target}")
def _validate_shape(self, data: npt.NDArray) -> None:
if self._metric_target == MetricTarget.BOXES:
if len(data.shape) != 2 or data.shape[1] != 4:
raise ValueError(f"Invalid xyxy shape: {data.shape}. Expected: (N, 4)")
elif self._metric_target == MetricTarget.MASKS:
if len(data.shape) != 3:
raise ValueError(
f"Invalid mask shape: {data.shape}. Expected: (N, H, W)"
)
elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
if len(data.shape) != 2 or data.shape[1] != 8:
raise ValueError(f"Invalid obb shape: {data.shape}. Expected: (N, 8)")
else:
raise ValueError(f"Invalid metric target: {self._metric_target}")
class InternalMetricDataStore:
"""
Stores internal data for metrics.
Provides a class-agnostic way to access it.
"""
def __init__(self, metric_target: MetricTarget, class_agnostic: bool = False):
self._metric_target = metric_target
self._class_agnostic = class_agnostic
self._data_1: MetricData
self._data_2: MetricData
self.reset()
def reset(self) -> None:
self._data_1 = MetricData(self._metric_target, self._class_agnostic)
self._data_2 = MetricData(self._metric_target, self._class_agnostic)
def update(self, data_1: Detections, data_2: Detections) -> None:
"""
Add new data to the store.
Use sv.Detections.empty() if only one set of data is available.
"""
self._data_1.update(data_1)
self._data_2.update(data_2)
def __getitem__(self, class_id: int) -> Tuple[MetricData, MetricData]:
return (
self._data_1.get_subset_by_class(class_id),
self._data_2.get_subset_by_class(class_id),
)
def __iter__(self) -> Iterator[Tuple[int, MetricData, MetricData]]:
for class_id in self._data_1.get_classes():
yield class_id, *self[class_id]
+80 -29
View File
@@ -4,14 +4,16 @@ from dataclasses import dataclass
from itertools import zip_longest
from typing import TYPE_CHECKING, Dict, List, Optional, Union
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt # noqa
import numpy as np
import numpy.typing as npt
from matplotlib.colors import LinearSegmentedColormap
from supervision.detection.core import Detections
from supervision.detection.utils import box_iou_batch
from supervision.metrics.core import InternalMetricDataStore, Metric, MetricTarget
from supervision.metrics.utils import ensure_pandas_installed
from supervision.detection.utils import box_iou_batch, mask_iou_batch
from supervision.metrics.core import Metric, MetricTarget
from supervision.metrics.utils.internal_data_store import MetricDataStore
from supervision.metrics.utils.utils import ensure_pandas_installed
if TYPE_CHECKING:
import pandas as pd
@@ -22,7 +24,7 @@ class IntersectionOverUnion(Metric):
self,
metric_target: MetricTarget = MetricTarget.BOXES,
class_agnostic: bool = False,
shared_data_store: Optional[InternalMetricDataStore] = None,
shared_data_store: Optional[MetricDataStore] = None,
):
"""
Initialize the Intersection over Union metric.
@@ -31,12 +33,12 @@ class IntersectionOverUnion(Metric):
metric_target (MetricTarget): The type of detection data to use.
class_agnostic (bool): Whether to treat all data as a single class.
Defaults to `False`.
shared_data_store (Optional[InternalMetricDataStore]): If you have
shared_data_store (Optional[MetricDataStore]): If you have
a hierarchy of metrics, you can pass a data store to share it
between them, saving memory. The responsibility of updating
the store falls on the parent metric (that contain this one).
"""
if metric_target != MetricTarget.BOXES:
if metric_target not in [MetricTarget.BOXES, MetricTarget.MASKS]:
raise NotImplementedError(
f"Intersection over union is not implemented for {metric_target}."
)
@@ -49,7 +51,7 @@ class IntersectionOverUnion(Metric):
self._store = shared_data_store
else:
self._is_store_shared = False
self._store = InternalMetricDataStore(metric_target, class_agnostic)
self._store = MetricDataStore(metric_target, class_agnostic)
def reset(self) -> None:
if self._is_store_shared:
@@ -106,31 +108,58 @@ class IntersectionOverUnion(Metric):
are (N, M) arrays where N is the number of predictions and M is the number
of targets.
"""
ious = {}
for class_id, data_1, data_2 in self._store:
iou = box_iou_batch(data_1.data, data_2.data).transpose()
ious[class_id] = iou
return IntersectionOverUnionResult(ious, self._metric_target)
ious_by_class = {}
for class_id in self._store.get_classes():
if self._metric_target == MetricTarget.BOXES:
(data_array_1, _, _), (data_array_2, _, _) = self._store.get(
class_id=class_id
)
ious_by_class[class_id] = box_iou_batch(
data_array_1, data_array_2
).transpose()
elif self._metric_target == MetricTarget.MASKS:
(data_array_1, _, _), (data_array_2, _, _) = self._store.get(
class_id=class_id
)
ious_by_class[class_id] = mask_iou_batch(
data_array_1, data_array_2
).transpose()
else:
raise NotImplementedError(
f"Intersection over union is not implemented"
f" for {self._metric_target}."
)
return IntersectionOverUnionResult(ious_by_class, self._metric_target)
@dataclass
class IntersectionOverUnionResult:
ious: Dict[int, npt.NDArray[np.float32]]
ious_by_class: Dict[int, npt.NDArray[np.float32]]
metric_target: MetricTarget
@property
def class_ids(self) -> List[int]:
return list(self.ious.keys())
return list(self.ious_by_class.keys())
def __getitem__(self, class_id: int) -> npt.NDArray[np.float32]:
return self.ious[class_id]
return self.ious_by_class[class_id]
def __iter__(self):
return iter(self.ious.items())
return iter(self.ious_by_class.items())
def __str__(self) -> str:
out_str = f"{self.__class__.__name__}:\n"
for class_id, iou in self.ious_by_class.items():
out_str += f"IoUs for class {class_id}:\n{str(iou)}\n"
return out_str
def to_pandas(self) -> Dict[int, "pd.DataFrame"]:
ensure_pandas_installed()
return {class_id: pd.DataFrame(iou) for class_id, iou in self.ious.items()}
import pandas as pd
return {
class_id: pd.DataFrame(iou) for class_id, iou in self.ious_by_class.items()
}
def plot(self, class_id=None):
"""
@@ -143,7 +172,7 @@ class IntersectionOverUnionResult:
if class_id:
self._plot_class(class_id)
else:
for cls in self.ious:
for cls in self.ious_by_class:
self._plot_class(cls)
def _plot_class(self, class_id):
@@ -154,7 +183,7 @@ class IntersectionOverUnionResult:
Args:
class_id (int): The class ID to plot.
"""
iou_matrix = self.ious[class_id]
iou_matrix = self.ious_by_class[class_id]
if iou_matrix.size == 0:
print(
@@ -162,23 +191,45 @@ class IntersectionOverUnionResult:
f" {iou_matrix.shape}. Skipping plot."
)
else:
plt.rcParams["font.family"] = "monospace"
colors = [
(0, "#4D049A"),
(0.3, "#E6194B"),
(0.6, "#FFE119"),
(1, "#4CFB12"),
]
custom_colormap = LinearSegmentedColormap.from_list("roboflow_cmap", colors)
row_count, col_count = iou_matrix.shape
font_size = int(5 + (25 / (max(row_count, col_count) + 1e-6)))
plt.figure(figsize=(6, 6))
plt.matshow(iou_matrix, cmap="viridis", fignum=1)
plt.title(f"Class {class_id} IoU Matrix", pad=20)
plt.gca().xaxis.set_ticks_position("bottom")
plt.xlabel("Target Bounding Boxes")
plt.ylabel("Predicted Bounding Boxes")
plt.matshow(iou_matrix, cmap=custom_colormap, fignum=1)
plt.title(f"Class {class_id} IoU Matrix", pad=50, fontweight="bold")
plt.gca().xaxis.set_label_position("top")
plt.gca().xaxis.tick_top()
plt.xlabel("Prediction index", fontweight="bold")
plt.ylabel("Target index", fontweight="bold")
plt.colorbar()
for (i, j), val in np.ndenumerate(iou_matrix):
for (i, j), iou_value in np.ndenumerate(iou_matrix):
if iou_value < 0.1:
continue
formatted_value = f"{iou_value:.2f}".lstrip("0")
is_black = iou_value > 0.3
plt.text(
j,
i,
f"{val:.2f}",
formatted_value,
ha="center",
va="center",
fontsize=8,
color="white" if val < 0.5 else "black",
fontsize=font_size,
color="black" if is_black else "white",
)
plt.rcParams["font.family"] = "sans-serif"
plt.show()
+402 -132
View File
@@ -2,19 +2,21 @@ from __future__ import annotations
from dataclasses import dataclass
from itertools import zip_longest
from typing import Dict, List, Union
from typing import TYPE_CHECKING, List, Optional, Union
import numpy as np
import numpy.typing as npt
from matplotlib import pyplot as plt
from supervision.detection.core import Detections
from supervision.metrics.core import (
InternalMetricDataStore,
Metric,
MetricData,
MetricTarget,
)
from supervision.metrics.intersection_over_union import IntersectionOverUnion
from supervision.detection.utils import box_iou_batch, mask_iou_batch
from supervision.draw.color import LEGACY_COLOR_PALETTE
from supervision.metrics.core import Metric, MetricTarget
from supervision.metrics.utils.internal_data_store import MetricDataStore
from supervision.metrics.utils.object_size import ObjectSizeCategory
from supervision.metrics.utils.utils import ensure_pandas_installed
if TYPE_CHECKING:
import pandas as pd
class MeanAveragePrecision(Metric):
@@ -22,141 +24,287 @@ class MeanAveragePrecision(Metric):
self,
metric_target: MetricTarget = MetricTarget.BOXES,
class_agnostic: bool = False,
iou_threshold: float = 0.25,
):
"""
Initialize the Mean Average Precision metric.
Args:
metric_target (MetricTarget): The type of detection data to use.
class_agnostic (bool): Whether to treat all data as a single class.
"""
self._metric_target = metric_target
if self._metric_target != MetricTarget.BOXES:
if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
raise NotImplementedError(
f"mAP is not implemented for {self._metric_target}."
"Mean Average Precision is not implemented for oriented bounding boxes."
)
self._class_agnostic = class_agnostic
self._iou_threshold = iou_threshold
self._store = InternalMetricDataStore(metric_target, class_agnostic)
self._iou_metric = IntersectionOverUnion(metric_target, class_agnostic)
self._store = MetricDataStore(metric_target, class_agnostic)
self.reset()
def reset(self) -> None:
self._iou_metric.reset()
self._store.reset()
return self._store.reset()
def update(
self,
predictions: Union[Detections, List[Detections]],
targets: Union[Detections, List[Detections]],
data_1: Union[Detections, List[Detections]],
data_2: Union[Detections, List[Detections]],
) -> MeanAveragePrecision:
if not isinstance(predictions, list):
predictions = [predictions]
if not isinstance(targets, list):
targets = [targets]
if not isinstance(data_1, list):
data_1 = [data_1]
if not isinstance(data_2, list):
data_2 = [data_2]
for d1, d2 in zip_longest(predictions, targets, fillvalue=Detections.empty()):
for d1, d2 in zip_longest(data_1, data_2, fillvalue=Detections.empty()):
self._update(d1, d2)
return self
def _update(self, predictions: Detections, targets: Detections) -> None:
self._store.update(predictions, targets)
self._iou_metric.update(predictions, targets)
def compute(self) -> MeanAveragePrecisionResult:
ious = self._iou_metric.compute()
iou_thresholds = np.linspace(0.5, 0.95, 10)
average_precisions: Dict[int, npt.NDArray] = {}
for class_id, prediction_data, target_data in self._store:
if len(target_data) == 0:
continue
if len(prediction_data) == 0:
stats = (
np.zeros((0, iou_thresholds.size), dtype=bool),
np.array([], dtype=np.float32),
np.array([], dtype=np.float32),
target_data.class_id,
)
else:
ious_of_class = ious[class_id]
matches = self._match_predictions_to_targets(
prediction_data, target_data, ious_of_class, iou_thresholds
)
stats = (
matches,
prediction_data.confidence,
prediction_data.class_id,
target_data.class_id,
)
to_concat = [np.expand_dims(item, 0) for item in stats]
for x in to_concat:
print(x.shape)
# print(to_concat)
# TODO: class_id size mismatch
# (1, 9, 10)
# (1, 9)
# (1, 9)
# (1, 12)
concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)]
average_precisions[class_id] = self._average_precisions_per_class(
*concatenated_stats
)
return MeanAveragePrecisionResult(average_precisions)
def _match_predictions_to_targets(
def _update(
self,
prediction_data: MetricData,
target_data: MetricData,
predictions_iou: npt.NDArray[np.float32],
iou_thresholds: npt.NDArray[np.float32],
) -> npt.NDArray[np.bool_]:
"""
Match predictions to targets based on IoU.
data_1: Detections,
data_2: Detections,
) -> None:
self._store.update(data_1, data_2)
Given N predictions, M targets and T IoU thresholds,
returns a boolean array (N, T), where each element is True
if the prediction is a true positive at the given IoU threshold.
Assumes that predictions were already filtered by class.
def compute(
self,
) -> MeanAveragePrecisionResult:
"""
if set(prediction_data.class_id) != set(target_data.class_id):
raise ValueError(
f"Class IDs of predictions and targets"
f" do not match: {prediction_data.class_id}, {target_data.class_id}"
Calculate Mean Average Precision based on predicted and ground-truth
detections at different threshold.
Args:
predictions (List[np.ndarray]): Each element of the list describes
a single image and has `shape = (M, 6)` where `M` is
the number of detected objects. Each row is expected to be
in `(x_min, y_min, x_max, y_max, class, conf)` format.
targets (List[np.ndarray]): Each element of the list describes a single
image and has `shape = (N, 5)` where `N` is the
number of ground-truth objects. Each row is expected to be in
`(x_min, y_min, x_max, y_max, class)` format.
Returns:
MeanAveragePrecision: New instance of MeanAveragePrecision.
Example:
```python
import supervision as sv
import numpy as np
targets = (
[
np.array(
[
[0.0, 0.0, 3.0, 3.0, 1],
[2.0, 2.0, 5.0, 5.0, 1],
[6.0, 1.0, 8.0, 3.0, 2],
]
),
np.array([[1.0, 1.0, 2.0, 2.0, 2]]),
]
)
correct = np.zeros((len(prediction_data), len(iou_thresholds)), dtype=bool)
predictions = [
np.array(
[
[0.0, 0.0, 3.0, 3.0, 1, 0.9],
[0.1, 0.1, 3.0, 3.0, 0, 0.9],
[6.0, 1.0, 8.0, 3.0, 1, 0.8],
[1.0, 6.0, 2.0, 7.0, 1, 0.8],
]
),
np.array([[1.0, 1.0, 2.0, 2.0, 2, 0.8]])
]
mean_average_precison = sv.MeanAveragePrecision.from_tensors(
predictions=predictions,
targets=targets,
)
print(mean_average_precison.map50_95)
# 0.6649
```
"""
(
(predictions, prediction_classes, prediction_confidence),
(targets, target_classes, _),
) = self._store.get()
result = self._compute(
predictions,
prediction_classes,
prediction_confidence,
targets,
target_classes,
)
(
(predictions, prediction_classes, prediction_confidence),
(targets, target_classes, _),
) = self._store.get(size_category=ObjectSizeCategory.SMALL)
small_result = self._compute(
predictions,
prediction_classes,
prediction_confidence,
targets,
target_classes,
)
result.small_objects = small_result
(
(predictions, prediction_classes, prediction_confidence),
(targets, target_classes, _),
) = self._store.get(size_category=ObjectSizeCategory.MEDIUM)
medium_result = self._compute(
predictions,
prediction_classes,
prediction_confidence,
targets,
target_classes,
)
result.medium_objects = medium_result
(
(predictions, prediction_classes, prediction_confidence),
(targets, target_classes, _),
) = self._store.get(size_category=ObjectSizeCategory.LARGE)
large_result = self._compute(
predictions,
prediction_classes,
prediction_confidence,
targets,
target_classes,
)
result.large_objects = large_result
return result
def _compute(
self,
predictions: np.ndarray,
prediction_classes: np.ndarray,
prediction_confidence: np.ndarray,
targets: np.ndarray,
target_classes: np.ndarray,
) -> MeanAveragePrecisionResult:
iou_thresholds = np.linspace(0.5, 0.95, 10)
stats = []
if targets.shape[0] > 0:
if predictions.shape[0] == 0:
stats.append(
(
np.zeros((0, iou_thresholds.size), dtype=bool),
np.zeros((0,), dtype=np.float32),
np.zeros((0,), dtype=int),
target_classes,
)
)
else:
if self._metric_target == MetricTarget.BOXES:
iou = box_iou_batch(targets, predictions)
elif self._metric_target == MetricTarget.MASKS:
iou = mask_iou_batch(targets, predictions)
else:
raise NotImplementedError(
"Unsupported metric target for IoU calculation"
)
matches = self._match_detection_batch(
prediction_classes, target_classes, iou, iou_thresholds
)
stats.append(
(
matches,
prediction_confidence,
prediction_classes,
target_classes,
)
)
# Compute average precisions if any matches exist
if stats:
concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)]
average_precisions = self._average_precisions_per_class(*concatenated_stats)
map50 = average_precisions[:, 0].mean()
map75 = average_precisions[:, 5].mean()
map50_95 = average_precisions.mean()
else:
map50, map75, map50_95 = 0, 0, 0
average_precisions = np.empty((0, len(iou_thresholds)), dtype=np.float32)
return MeanAveragePrecisionResult(
iou_thresholds=iou_thresholds,
map50_95=map50_95,
map50=map50,
map75=map75,
per_class_ap50_95=average_precisions,
)
@staticmethod
def compute_average_precision(recall: np.ndarray, precision: np.ndarray) -> float:
"""
Compute the average precision using 101-point interpolation (COCO), given
the recall and precision curves.
Args:
recall (np.ndarray): The recall curve.
precision (np.ndarray): The precision curve.
Returns:
float: Average precision.
"""
extended_recall = np.concatenate(([0.0], recall, [1.0]))
extended_precision = np.concatenate(([1.0], precision, [0.0]))
max_accumulated_precision = np.flip(
np.maximum.accumulate(np.flip(extended_precision))
)
interpolated_recall_levels = np.linspace(0, 1, 101)
interpolated_precision = np.interp(
interpolated_recall_levels, extended_recall, max_accumulated_precision
)
average_precision = np.trapz(interpolated_precision, interpolated_recall_levels)
return average_precision
@staticmethod
def _match_detection_batch(
predictions_classes: np.ndarray,
target_classes: np.ndarray,
iou: np.ndarray,
iou_thresholds: np.ndarray,
) -> np.ndarray:
num_predictions, num_iou_levels = (
predictions_classes.shape[0],
iou_thresholds.shape[0],
)
correct = np.zeros((num_predictions, num_iou_levels), dtype=bool)
correct_class = target_classes[:, None] == predictions_classes
for i, iou_level in enumerate(iou_thresholds):
matched_indices = np.where((predictions_iou >= iou_level))
matched_indices = np.where((iou >= iou_level) & correct_class)
if matched_indices[0].shape[0]:
combined_indices = np.stack(matched_indices, axis=1)
iou_values = predictions_iou[matched_indices][:, None]
iou_values = iou[matched_indices][:, None]
matches = np.hstack([combined_indices, iou_values])
if matched_indices[0].shape[0] > 1:
matches = matches[matches[:, 2].argsort()[::-1]]
_, unique_pred_idx = np.unique(matches[:, 1], return_index=True)
matches = matches[unique_pred_idx]
_, unique_target_idx = np.unique(matches[:, 0], return_index=True)
matches = matches[unique_target_idx]
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
correct[matches[:, 1].astype(int), i] = True
return correct
@staticmethod
def _average_precisions_per_class(
self,
matches: np.ndarray,
prediction_confidence: np.ndarray,
prediction_class_ids: np.ndarray,
true_class_ids: np.ndarray,
eps: float = 1e-16,
) -> np.ndarray:
"""
Compute the average precision, given the recall and precision curves.
@@ -172,6 +320,8 @@ class MeanAveragePrecision(Metric):
Returns:
np.ndarray: Average precision for different IoU levels.
"""
eps = 1e-16
sorted_indices = np.argsort(-prediction_confidence)
matches = matches[sorted_indices]
prediction_class_ids = prediction_class_ids[sorted_indices]
@@ -191,47 +341,167 @@ class MeanAveragePrecision(Metric):
false_positives = (1 - matches[is_class]).cumsum(0)
true_positives = matches[is_class].cumsum(0)
recall = true_positives / (total_true + eps)
true_negatives = total_true - true_positives
recall = true_positives / (true_positives + true_negatives + eps)
precision = true_positives / (true_positives + false_positives)
for iou_level_idx in range(matches.shape[1]):
average_precisions[class_idx, iou_level_idx] = (
self._compute_average_precision(
MeanAveragePrecision.compute_average_precision(
recall[:, iou_level_idx], precision[:, iou_level_idx]
)
)
return average_precisions
@staticmethod
def _compute_average_precision(recall: np.ndarray, precision: np.ndarray) -> float:
"""
Compute the average precision using 101-point interpolation (COCO), given
the recall and precision curves.
Args:
recall (np.ndarray): The recall curve.
precision (np.ndarray): The precision curve.
Returns:
float: Average precision.
"""
assert len(recall) == len(precision)
extended_recall = np.concatenate(([0.0], recall, [1.0]))
extended_precision = np.concatenate(([1.0], precision, [0.0]))
max_accumulated_precision = np.flip(
np.maximum.accumulate(np.flip(extended_precision))
)
interpolated_recall_levels = np.linspace(0, 1, 101)
interpolated_precision = np.interp(
interpolated_recall_levels, extended_recall, max_accumulated_precision
)
average_precision = np.trapz(interpolated_precision, interpolated_recall_levels)
return average_precision
@dataclass
class MeanAveragePrecisionResult:
# TODO: continue here
average_precisions: Dict[int, npt.NDArray]
iou_thresholds: np.ndarray
map50_95: float
map50: float
map75: float
per_class_ap50_95: np.ndarray
small_objects: Optional[MeanAveragePrecisionResult] = None
medium_objects: Optional[MeanAveragePrecisionResult] = None
large_objects: Optional[MeanAveragePrecisionResult] = None
def __str__(self) -> str:
out_str = (
f"{self.__class__.__name__}:\n"
f"iou_thresholds: {self.iou_thresholds}\n"
f"map50_95: {self.map50_95}\n"
f"map50: {self.map50}\n"
f"map75: {self.map75}\n"
f"per_class_ap50_95:"
)
for class_id, ap in enumerate(self.per_class_ap50_95):
out_str += f"\n {class_id}: {ap}"
indent = " "
if self.small_objects is not None:
indented_str = indent + str(self.small_objects).replace("\n", f"\n{indent}")
out_str += f"\nSmall objects:\n{indented_str}"
if self.medium_objects is not None:
indented_str = indent + str(self.medium_objects).replace(
"\n", f"\n{indent}"
)
out_str += f"\nMedium objects:\n{indented_str}"
if self.large_objects is not None:
indented_str = indent + str(self.large_objects).replace("\n", f"\n{indent}")
out_str += f"\nLarge objects:\n{indented_str}"
return out_str
def to_pandas(self) -> "pd.DataFrame":
"""
Convert the result to a pandas DataFrame.
Returns:
pd.DataFrame: The result as a DataFrame.
"""
ensure_pandas_installed()
import pandas as pd
pandas_data = {
"mAP_50_95": self.map50_95,
"mAP_50": self.map50,
"mAP_75": self.map75,
}
if self.small_objects is not None:
small_objects_df = self.small_objects.to_pandas()
for key, value in small_objects_df.items():
pandas_data[f"small_objects_{key}"] = value
if self.medium_objects is not None:
medium_objects_df = self.medium_objects.to_pandas()
for key, value in medium_objects_df.items():
pandas_data[f"medium_objects_{key}"] = value
if self.large_objects is not None:
large_objects_df = self.large_objects.to_pandas()
for key, value in large_objects_df.items():
pandas_data[f"large_objects_{key}"] = value
# Average precisions are currently not included in the DataFrame.
return pd.DataFrame(
pandas_data,
index=[0],
)
def plot(self):
"""
Plot the mAP results.
"""
labels = ["mAP_50_95", "mAP_50", "mAP_75"]
values = [self.map50_95, self.map50, self.map75]
colors = [LEGACY_COLOR_PALETTE[0]] * 3
if self.small_objects is not None:
labels += [
"small_objects_mAP_50_95",
"small_objects_mAP_50",
"small_objects_mAP_75",
]
values += [
self.small_objects.map50_95,
self.small_objects.map50,
self.small_objects.map75,
]
colors += [LEGACY_COLOR_PALETTE[3]] * 3
if self.medium_objects is not None:
labels += [
"medium_objects_mAP_50_95",
"medium_objects_mAP_50",
"medium_objects_mAP_75",
]
values += [
self.medium_objects.map50_95,
self.medium_objects.map50,
self.medium_objects.map75,
]
colors += [LEGACY_COLOR_PALETTE[2]] * 3
if self.large_objects is not None:
labels += [
"large_objects_mAP_50_95",
"large_objects_mAP_50",
"large_objects_mAP_75",
]
values += [
self.large_objects.map50_95,
self.large_objects.map50,
self.large_objects.map75,
]
colors += [LEGACY_COLOR_PALETTE[4]] * 3
plt.rcParams["font.family"] = "monospace"
_, ax = plt.subplots(figsize=(10, 6))
ax.set_ylim(0, 1)
ax.set_ylabel("Value", fontweight="bold")
ax.set_title("Mean Average Precision", fontweight="bold")
x_positions = range(len(labels))
bars = ax.bar(x_positions, values, color=colors, align="center")
ax.set_xticks(x_positions)
ax.set_xticklabels(labels, rotation=45, ha="right")
for bar in bars:
y_value = bar.get_height()
ax.text(
bar.get_x() + bar.get_width() / 2,
y_value + 0.02,
f"{y_value:.2f}",
ha="center",
va="bottom",
)
plt.rcParams["font.family"] = "sans-serif"
plt.tight_layout()
plt.show()
@@ -0,0 +1,298 @@
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Set, Tuple
import numpy as np
import numpy.typing as npt
from supervision.config import ORIENTED_BOX_COORDINATES
from supervision.metrics.core import CLASS_ID_NONE, MetricTarget
from supervision.metrics.utils.object_size import (
ObjectSizeCategory,
get_object_size_category,
)
from supervision.metrics.utils.utils import unify_pad_masks_shape
if TYPE_CHECKING:
from supervision.detection.core import Detections
class MetricData:
"""
A container for detection contents, decouple from `Detections`.
"""
def __init__(self, metric_target: MetricTarget, class_agnostic: bool = False):
self._metric_target = metric_target
self._class_agnostic = class_agnostic
self._content_list: List[npt.NDArray] = []
self._confidence_list: List[npt.NDArray[np.float32]] = []
self._class_id_list: List[npt.NDArray[np.int_]] = []
def update(self, detections: Detections):
"""Add new detections to the store."""
if detections.is_empty() or len(detections) == 0:
return
# Relies on Detections to ensure that member vars are equal in length
# or None/empty.
self._validate_new_entry(detections)
new_content = self._detections_content(detections)
self._validate_shape(new_content)
self._content_list.append(new_content)
if detections.confidence is not None:
self._confidence_list.append(detections.confidence)
if detections.class_id is not None:
if self._class_agnostic:
self._class_id_list.append(
np.full(len(detections.class_id), CLASS_ID_NONE, dtype=int)
)
else:
self._class_id_list.append(detections.class_id)
def get_classes(self) -> Set[int]:
"""Return all class IDs."""
if self._class_agnostic:
return {CLASS_ID_NONE}
return set.union(*[set(class_id) for class_id in self._class_id_list])
def get(
self, class_id: Optional[int] = None, size_category=ObjectSizeCategory.ANY
) -> Tuple[npt.NDArray, npt.NDArray, npt.NDArray]:
"""
Get the contents, class_ids and confidences, optionally filtered by
class_id and/or size.
Args:
class_id (Optional[int]): The class ID for the data to retrieve
size_category (ObjectSizeCategory): The size of the objects to retrieve.
Returns:
(np.ndarray): Boxes, masks or obb, all stacked in a single array.
"""
if self._metric_target in [
MetricTarget.BOXES,
MetricTarget.ORIENTED_BOUNDING_BOXES,
]:
self._merge_boxes()
if len(self._content_list) == 0:
content = self._make_empty_content()
else:
content = self._content_list[0]
elif self._metric_target == MetricTarget.MASKS:
self._merge_masks()
if len(self._content_list) == 0:
content = self._make_empty_content()
else:
content = self._content_list[0]
size_mask = np.full(len(content), True)
if size_category != ObjectSizeCategory.ANY:
sizes = get_object_size_category(content, self._metric_target)
size_mask = sizes == size_category.value
class_mask = np.full(len(content), True)
if class_id is not None:
self._merge_class_id()
class_ids = self._class_id_list[0]
class_mask = class_ids == class_id
content = content[(size_mask & class_mask)]
self._merge_class_id()
if len(self._class_id_list) == 0:
class_ids = np.array([], dtype=int)
else:
class_ids = self._class_id_list[0]
class_ids = class_ids[(size_mask & class_mask)]
self._merge_confidence()
if len(self._confidence_list) == 0:
confidences = np.array([], dtype=float)
else:
confidences = self._confidence_list[0]
confidences = confidences[(size_mask & class_mask)]
return content, class_ids, confidences
def get_class_id(self) -> npt.NDArray[np.int_]:
self._merge_class_id()
if len(self._class_id_list) == 0:
return np.array([], dtype=int)
return self._class_id_list[0]
def get_confidence(self) -> npt.NDArray[np.float32]:
self._merge_confidence()
if len(self._confidence_list) == 0:
return np.array([], dtype=float)
return self._confidence_list[0]
def _detections_content(self, detections: Detections) -> npt.NDArray:
"""Return boxes, masks or oriented bounding boxes from detections."""
if self._metric_target == MetricTarget.BOXES:
return detections.xyxy
if self._metric_target == MetricTarget.MASKS:
return (
detections.mask
if detections.mask is not None
else self._make_empty_content()
)
if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
if obb := detections.data.get(ORIENTED_BOX_COORDINATES):
return np.ndarray(obb, dtype=np.float32)
return self._make_empty_content()
raise ValueError(f"Invalid metric target: {self._metric_target}")
def _make_empty_content(self) -> npt.NDArray:
if self._metric_target == MetricTarget.BOXES:
return np.empty((0, 4), dtype=np.float32)
if self._metric_target == MetricTarget.MASKS:
return np.empty((0, 0, 0), dtype=bool)
if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
return np.empty((0, 8), dtype=np.float32)
raise ValueError(f"Invalid metric target: {self._metric_target}")
def _validate_new_entry(self, detections: Detections) -> None:
if (
len(self._content_list) == 0
or detections.is_empty()
or len(detections) == 0
):
return
is_self_class_empty = len(self._class_id_list) == 0
is_self_confidence_empty = len(self._confidence_list) == 0
is_detection_class_empty = (
detections.class_id is None or len(detections.class_id) == 0
)
is_detection_confidence_empty = (
detections.confidence is None or len(detections.confidence) == 0
)
if is_self_confidence_empty and not is_detection_confidence_empty:
raise ValueError(
"Previously stored detections without confidence,"
" but new detections have it."
)
if is_self_class_empty and not is_detection_class_empty:
raise ValueError(
"Previously stored detections without class ID,"
" but new detections have it."
)
if not is_self_class_empty and is_detection_class_empty:
raise ValueError(
"Started storing detections with class ID, but"
" new detections do not have it."
)
if not is_self_confidence_empty and is_detection_confidence_empty:
raise ValueError(
"Started storing detections with confidence,"
" but new detections do not have it."
)
def _validate_shape(self, data: npt.NDArray) -> None:
if self._metric_target == MetricTarget.BOXES:
if len(data.shape) != 2 or data.shape[1] != 4:
raise ValueError(f"Invalid xyxy shape: {data.shape}. Expected: (N, 4)")
elif self._metric_target == MetricTarget.MASKS:
if len(data.shape) != 3:
raise ValueError(
f"Invalid mask shape: {data.shape}. Expected: (N, H, W)"
)
elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
if len(data.shape) != 2 or data.shape[1] != 8:
raise ValueError(f"Invalid obb shape: {data.shape}. Expected: (N, 8)")
else:
raise ValueError(f"Invalid metric target: {self._metric_target}")
def _merge_boxes(self):
"""Merge all boxes into a single array."""
if self._metric_target not in (
MetricTarget.BOXES,
MetricTarget.ORIENTED_BOUNDING_BOXES,
):
raise ValueError("Invalid metric target for merging boxes")
if len(self._content_list) < 2:
return
self._content_list = [np.vstack(self._content_list)]
def _merge_masks(self):
"""Merge all masks into a single array."""
if self._metric_target != MetricTarget.MASKS:
raise ValueError("Invalid metric target for merging masks")
if len(self._content_list) < 2:
return
mew_mask_list = unify_pad_masks_shape(*self._content_list)
self._content_list = [np.vstack(mew_mask_list)]
def _merge_class_id(self):
"""Merge all class IDs into a single array."""
if len(self._class_id_list) < 2:
return
self._class_id_list = [np.vstack(self._class_id_list)]
def _merge_confidence(self):
"""Merge all confidences into a single array."""
if len(self._confidence_list) < 2:
return
self._confidence_list = [np.vstack(self._confidence_list)]
class MetricDataStore:
"""
Stores internal data for metrics.
Provides a class-agnostic way to access it.
"""
def __init__(self, metric_target: MetricTarget, class_agnostic: bool = False):
self._metric_target = metric_target
self._class_agnostic = class_agnostic
self._data_1: MetricData
self._data_2: MetricData
self.reset()
def reset(self) -> None:
self._data_1 = MetricData(self._metric_target, self._class_agnostic)
self._data_2 = MetricData(self._metric_target, self._class_agnostic)
def update(self, data_1: Detections, data_2: Detections) -> None:
"""
Add new data to the store.
Use sv.Detections.empty() if only one set of data is available.
"""
self._data_1.update(data_1)
self._data_2.update(data_2)
def get(
self,
class_id: Optional[int] = None,
size_category: ObjectSizeCategory = ObjectSizeCategory.ANY,
) -> Tuple[
Tuple[npt.NDArray, npt.NDArray, npt.NDArray],
Tuple[npt.NDArray, npt.NDArray, npt.NDArray],
]:
"""
Get the data for both sets, optionally filtered by class_id and/or size.
"""
data_1, class_id_1, confidence_1 = self._data_1.get(class_id, size_category)
data_2, class_id_2, confidence_2 = self._data_2.get(class_id, size_category)
if self._metric_target == MetricTarget.MASKS:
data_1, data_2 = unify_pad_masks_shape(data_1, data_2)
return (
(data_1, class_id_1, confidence_1),
(data_2, class_id_2, confidence_2),
)
def get_classes(self) -> Set[int]:
"""Return all class IDs."""
return self._data_1.get_classes() | self._data_2.get_classes()
+152
View File
@@ -0,0 +1,152 @@
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
import numpy as np
import numpy.typing as npt
from supervision.config import ORIENTED_BOX_COORDINATES
from supervision.metrics.core import MetricTarget
if TYPE_CHECKING:
from supervision.detection.core import Detections
SIZE_THRESHOLDS = [32**2, 96**2]
class ObjectSizeCategory(Enum):
ANY = -1
SMALL = 1
MEDIUM = 2
LARGE = 3
def get_object_size_category(
data: npt.NDArray, metric_target: MetricTarget
) -> npt.NDArray[np.int_]:
"""
Get the size category of an object. Distinguish based on the metric target.
Args:
data (np.ndarray): The object data, shaped (N, ...).
metric_target (MetricTarget): Determines whether boxes, masks or
oriented bounding boxes are used.
Returns:
(np.ndarray) The size category of each object, matching
the enum values of ObjectSizeCategory. Shaped (N,).
"""
if metric_target == MetricTarget.BOXES:
return get_bbox_size_category(data)
if metric_target == MetricTarget.MASKS:
return get_mask_size_category(data)
if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
return get_obb_size_category(data)
raise ValueError("Invalid metric type")
def get_bbox_size_category(xyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.int_]:
"""
Get the size category of a bounding boxes array.
Args:
xyxy (np.ndarray): The bounding boxes array shaped (N, 4).
Returns:
(np.ndarray) The size category of each bounding box, matching
the enum values of ObjectSizeCategory. Shaped (N,).
"""
if len(xyxy.shape) != 2 or xyxy.shape[1] != 4:
raise ValueError("Bounding boxes must be shaped (N, 4)")
width = xyxy[:, 2] - xyxy[:, 0]
height = xyxy[:, 3] - xyxy[:, 1]
areas = width * height
result = np.full(areas.shape, ObjectSizeCategory.ANY.value)
result[areas < SIZE_THRESHOLDS[0]] = ObjectSizeCategory.SMALL.value
result[areas < SIZE_THRESHOLDS[1]] = ObjectSizeCategory.MEDIUM.value
result[areas >= SIZE_THRESHOLDS[1]] = ObjectSizeCategory.LARGE.value
return result
def get_mask_size_category(mask: npt.NDArray[np.bool_]) -> npt.NDArray[np.int_]:
"""
Get the size category of detection masks.
Args:
mask (np.ndarray): The mask array shaped (N, H, W).
Returns:
(np.ndarray) The size category of each mask, matching
the enum values of ObjectSizeCategory. Shaped (N,).
"""
if len(mask.shape) != 3:
raise ValueError("Masks must be shaped (N, H, W)")
areas = np.sum(mask, axis=(1, 2))
result = np.full(areas.shape, ObjectSizeCategory.ANY.value)
result[areas < SIZE_THRESHOLDS[0]] = ObjectSizeCategory.SMALL.value
result[areas < SIZE_THRESHOLDS[1]] = ObjectSizeCategory.MEDIUM.value
result[areas >= SIZE_THRESHOLDS[1]] = ObjectSizeCategory.LARGE.value
return result
def get_obb_size_category(xyxyxyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.int_]:
"""
Get the size category of a oriented bounding boxes array.
Args:
xyxyxyxy (np.ndarray): The bounding boxes array shaped (N, 8).
Returns:
(np.ndarray) The size category of each bounding box, matching
the enum values of ObjectSizeCategory. Shaped (N,).
"""
if len(xyxyxyxy.shape) != 2 or xyxyxyxy.shape[1] != 8:
raise ValueError("Oriented bounding boxes must be shaped (N, 8)")
# Shoelace formula
x1, y1, x2, y2, x3, y3, x4, y4 = xyxyxyxy.T
areas = 0.5 * np.abs(
(x1 * y2 + x2 * y3 + x3 * y4 + x4 * y1)
- (x2 * y1 + x3 * y2 + x4 * y3 + x1 * y4)
)
result = np.full(areas.shape, ObjectSizeCategory.ANY.value)
result[areas < SIZE_THRESHOLDS[0]] = ObjectSizeCategory.SMALL.value
result[areas < SIZE_THRESHOLDS[1]] = ObjectSizeCategory.MEDIUM.value
result[areas >= SIZE_THRESHOLDS[1]] = ObjectSizeCategory.LARGE.value
return result
def get_detection_size_category(
detections: Detections, metric_target: MetricTarget = MetricTarget.BOXES
) -> npt.NDArray[np.int_]:
"""
Get the size category of a detections object.
Args:
xyxyxyxy (np.ndarray): The bounding boxes array shaped (N, 8).
metric_target (MetricTarget): Determines whether boxes, masks or
oriented bounding boxes are used.
Returns:
(np.ndarray) The size category of each bounding box, matching
the enum values of ObjectSizeCategory. Shaped (N,).
"""
if metric_target == MetricTarget.BOXES:
return get_bbox_size_category(detections.xyxy)
if metric_target == MetricTarget.MASKS:
if detections.mask is None:
raise ValueError("Detections mask is not available")
return get_mask_size_category(detections.mask)
if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
if detections.data.get(ORIENTED_BOX_COORDINATES) is None:
raise ValueError("Detections oriented bounding boxes are not available")
return get_obb_size_category(
np.array(detections.data[ORIENTED_BOX_COORDINATES])
)
raise ValueError("Invalid metric type")
@@ -1,4 +1,4 @@
from typing import Tuple
from typing import List, Tuple
import numpy as np
import numpy.typing as npt
@@ -34,6 +34,37 @@ def pad_mask(mask: npt.NDArray, new_shape: Tuple[int, int]) -> npt.NDArray:
return new_mask
def unify_pad_masks_shape(
*masks: npt.NDArray[np.bool_],
) -> List[npt.NDArray[np.bool_]]:
"""
Given any number of (N, H, W) mask objects, return copies of the
same (H, W), padded to the largest dimensions.
Args:
*masks (np.ndarray): The mask arrays to unify. Each shaped (_, H, W),
Returns:
List[np.ndarray]: The masks, padded to the largest dimensions.
Each list element shaped (_, H_max, W_max)
"""
new_h = 0
new_w = 0
for mask in masks:
if len(mask.shape) != 3:
raise ValueError(f"Invalid mask shape: {mask.shape}. Expected: (N, H, W)")
_, h, w = mask.shape
new_h = max(new_h, h)
new_w = max(new_w, w)
results = []
for mask in masks:
results.append(pad_mask(mask, (new_h, new_w)))
return results
def len0_like(data: npt.NDArray) -> npt.NDArray:
"""Create an empty array with the same shape as input, but with 0 rows."""
return np.empty((0, *data.shape[1:]), dtype=data.dtype)
-548
View File
@@ -1,548 +0,0 @@
from contextlib import AbstractContextManager as PytestExceptionType
from contextlib import ExitStack as DoesNotRaise
from typing import List, Optional, Tuple, Union
import numpy as np
import numpy.typing as npt
import pytest
from supervision.detection.core import Detections
from supervision.metrics.core import (
CLASS_ID_NONE,
InternalMetricDataStore,
MetricTarget,
)
class TestError(Exception):
__test__ = False
def mock_xyxy(*box_index: int, box_width=10) -> npt.NDArray[np.float32]:
"""
Quickly generate a list of boxes.
For each index in `box_index`, a box is generated with the top-left corner at
(i, i) and the bottom-right corner at (i + box_width, i + box_width).
"""
if len(box_index) == 0:
return np.zeros((0, 4), dtype=np.float32)
box_list = []
for i in box_index:
x0 = y0 = i
x1 = y1 = i + box_width
box_list.append([x0, y0, x1, y1])
return np.array(box_list, dtype=np.float32)
def mock_mask(*box_index: int, box_width=10, image_size=20) -> np.ndarray:
if len(box_index) == 0:
return np.zeros((0, image_size, image_size), dtype=bool)
if image_size < max(box_index) + box_width:
raise TestError(
f"image_size is too small. It should be at least"
f" {max(box_index) + box_width}"
)
mask_list = []
xyxy = mock_xyxy(*box_index, box_width=box_width).astype(int)
for box in xyxy:
mask = np.zeros((image_size, image_size), dtype=bool)
mask[box[0] : box[2], box[1] : box[3]] = True
mask_list.append(mask)
return np.array(mask_list, dtype=bool)
def mock_detections(
*box_indices: int, class_id: Optional[List[int]] = None, with_mask=False
):
"""Mock detections with xyxy and class_ids"""
if len(box_indices) == 0:
if class_id is not None and len(class_id) > 0:
raise TestError("class_id should be None or empty if box_indices is empty")
return Detections.empty()
mask = None
if with_mask:
mask = mock_mask(*box_indices)
return Detections(
xyxy=mock_xyxy(*box_indices),
class_id=None if class_id is None else np.array(class_id, dtype=int),
mask=mask,
)
def helper_test_store(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
class_agnostic: bool,
metric_target: MetricTarget,
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
):
store = InternalMetricDataStore(metric_target, class_agnostic=class_agnostic)
store.update(data_1, data_2)
result = [result for result in store]
assert len(result) == len(expected_result)
for (class_id, content_1, content_2), (
expected_class_id,
expected_content_1,
expected_content_2,
) in zip(result, expected_result):
assert class_id == expected_class_id
assert (content_1 is None and expected_content_1 is None) or np.array_equal(
content_1, expected_content_1
)
assert (content_2 is None and expected_content_2 is None) or np.array_equal(
content_2, expected_content_2
)
# Boxes
@pytest.mark.parametrize(
"data_1, data_2, expected_result, exception",
[
# Empty
(mock_detections(), mock_detections(), [], DoesNotRaise()),
(mock_xyxy(), mock_xyxy(), [], DoesNotRaise()),
(mock_detections(), mock_xyxy(), [], DoesNotRaise()),
(mock_xyxy(), mock_detections(), [], DoesNotRaise()),
# Exactly 1 box
(
mock_detections(1),
mock_detections(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(1),
mock_xyxy(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_xyxy(1),
mock_detections(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_xyxy(1),
mock_xyxy(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(),
mock_detections(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_detections(),
mock_xyxy(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_xyxy(),
mock_detections(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_xyxy(),
mock_xyxy(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
# More boxes
(
mock_detections(1, 2),
mock_detections(),
[
(
CLASS_ID_NONE,
mock_xyxy(1, 2),
mock_xyxy(),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2),
mock_detections(3, 4),
[
(
CLASS_ID_NONE,
mock_xyxy(1, 2),
mock_xyxy(3, 4),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2),
mock_xyxy(3, 4),
[(CLASS_ID_NONE, mock_xyxy(1, 2), mock_xyxy(3, 4))],
DoesNotRaise(),
),
# With classes (that are ignored)
(
mock_detections(1, 2, class_id=[1, 2]),
mock_detections(),
[(CLASS_ID_NONE, mock_xyxy(1, 2), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(1, 2, class_id=[1, 2]),
mock_xyxy(3, 4),
[(CLASS_ID_NONE, mock_xyxy(1, 2), mock_xyxy(3, 4))],
DoesNotRaise(),
),
],
)
def test_store_boxes_class_agnostic(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
exception: PytestExceptionType,
) -> None:
with exception:
helper_test_store(
data_1,
data_2,
class_agnostic=True,
metric_target=MetricTarget.BOXES,
expected_result=expected_result,
)
@pytest.mark.parametrize(
"data_1, data_2, expected_result, exception",
[
# Empty
(mock_detections(), mock_detections(), [], DoesNotRaise()),
(mock_xyxy(), mock_xyxy(), [], DoesNotRaise()),
(mock_detections(), mock_xyxy(), [], DoesNotRaise()),
(mock_xyxy(), mock_detections(), [], DoesNotRaise()),
# Exactly 1 box
(
mock_detections(1),
mock_detections(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(1),
mock_xyxy(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_xyxy(1),
mock_detections(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_xyxy(1),
mock_xyxy(),
[(CLASS_ID_NONE, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(),
mock_detections(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_detections(),
mock_xyxy(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_xyxy(),
mock_detections(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
(
mock_xyxy(),
mock_xyxy(1),
[(CLASS_ID_NONE, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
# More boxes
(
mock_detections(1, 2),
mock_detections(),
[
(
CLASS_ID_NONE,
mock_xyxy(1, 2),
mock_xyxy(),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2),
mock_detections(3, 4),
[
(
CLASS_ID_NONE,
mock_xyxy(1, 2),
mock_xyxy(3, 4),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2),
mock_xyxy(3, 4),
[(CLASS_ID_NONE, mock_xyxy(1, 2), mock_xyxy(3, 4))],
DoesNotRaise(),
),
],
)
def test_store_boxes_by_class_regression(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
exception: PytestExceptionType,
) -> None:
"""Behaves exactly like class_agnostic if no classes are specified"""
with exception:
helper_test_store(
data_1,
data_2,
class_agnostic=False,
metric_target=MetricTarget.BOXES,
expected_result=expected_result,
)
@pytest.mark.parametrize(
"data_1, data_2, expected_result, exception",
[
# Single box + Empty
(
mock_detections(1, class_id=[1]),
mock_detections(),
[(1, mock_xyxy(1), mock_xyxy())],
DoesNotRaise(),
),
(
mock_detections(),
mock_detections(1, class_id=[1]),
[(1, mock_xyxy(), mock_xyxy(1))],
DoesNotRaise(),
),
# Multiple classes
(
mock_detections(1, 2, class_id=[1, 2]),
mock_detections(),
[
(1, mock_xyxy(1), mock_xyxy()),
(2, mock_xyxy(2), mock_xyxy()),
],
DoesNotRaise(),
),
(
mock_detections(1, 2, class_id=[1, 2]),
mock_detections(3, 4, 5, class_id=[2, 3, 3]),
[
(1, mock_xyxy(1), mock_xyxy()),
(
2,
mock_xyxy(2),
mock_xyxy(3),
),
(3, mock_xyxy(), mock_xyxy(4, 5)),
],
DoesNotRaise(),
),
],
)
def test_store_boxes_by_class(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
exception: PytestExceptionType,
) -> None:
with exception:
helper_test_store(
data_1,
data_2,
class_agnostic=False,
metric_target=MetricTarget.BOXES,
expected_result=expected_result,
)
@pytest.mark.parametrize(
"data_1, data_2, expected_result, exception",
[
# Single box + Empty
(
[],
mock_detections(),
[(1, mock_xyxy(), mock_xyxy())],
pytest.raises(ValueError),
),
(
mock_detections(),
[],
[(1, mock_xyxy(), mock_xyxy())],
pytest.raises(ValueError),
),
],
)
def test_store_boxes_invalid_args(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
exception: PytestExceptionType,
) -> None:
with exception:
helper_test_store(
data_1,
data_2,
class_agnostic=False,
metric_target=MetricTarget.BOXES,
expected_result=expected_result,
)
# Masks
@pytest.mark.parametrize(
"data_1, data_2, expected_result, exception",
[
# Empty
(
mock_detections(with_mask=True),
mock_detections(with_mask=True),
[],
DoesNotRaise(),
),
(mock_mask(), mock_mask(), [], DoesNotRaise()),
(mock_detections(with_mask=True), mock_mask(), [], DoesNotRaise()),
(mock_mask(), mock_detections(with_mask=True), [], DoesNotRaise()),
# Exactly 1 box
(
mock_detections(1, with_mask=True),
mock_detections(with_mask=True),
[(CLASS_ID_NONE, mock_mask(1), mock_mask())],
DoesNotRaise(),
),
(
mock_detections(1, with_mask=True),
mock_mask(),
[(CLASS_ID_NONE, mock_mask(1), mock_mask())],
DoesNotRaise(),
),
(
mock_mask(1),
mock_detections(with_mask=True),
[(CLASS_ID_NONE, mock_mask(1), mock_mask())],
DoesNotRaise(),
),
(
mock_mask(1),
mock_mask(),
[(CLASS_ID_NONE, mock_mask(1), mock_mask())],
DoesNotRaise(),
),
(
mock_detections(with_mask=True),
mock_detections(1, with_mask=True),
[(CLASS_ID_NONE, mock_mask(), mock_mask(1))],
DoesNotRaise(),
),
(
mock_detections(with_mask=True),
mock_mask(1),
[(CLASS_ID_NONE, mock_mask(), mock_mask(1))],
DoesNotRaise(),
),
(
mock_mask(),
mock_detections(1, with_mask=True),
[(CLASS_ID_NONE, mock_mask(), mock_mask(1))],
DoesNotRaise(),
),
(
mock_mask(),
mock_mask(1),
[(CLASS_ID_NONE, mock_mask(), mock_mask(1))],
DoesNotRaise(),
),
# More masks
(
mock_detections(1, 2, with_mask=True),
mock_detections(with_mask=True),
[
(
CLASS_ID_NONE,
mock_mask(1, 2),
mock_mask(),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2, with_mask=True),
mock_detections(3, 4, with_mask=True),
[
(
CLASS_ID_NONE,
mock_mask(1, 2),
mock_mask(3, 4),
)
],
DoesNotRaise(),
),
(
mock_detections(1, 2, with_mask=True),
mock_mask(3, 4),
[(CLASS_ID_NONE, mock_mask(1, 2), mock_mask(3, 4))],
DoesNotRaise(),
),
# With classes (that are ignored)
(
mock_detections(1, 2, class_id=[1, 2], with_mask=True),
mock_detections(with_mask=True),
[(CLASS_ID_NONE, mock_mask(1, 2), mock_mask())],
DoesNotRaise(),
),
(
mock_detections(1, 2, class_id=[1, 2], with_mask=True),
mock_mask(3, 4),
[(CLASS_ID_NONE, mock_mask(1, 2), mock_mask(3, 4))],
DoesNotRaise(),
),
],
)
def test_store_masks_class_agnostic(
data_1: Union[npt.NDArray, Detections],
data_2: Union[npt.NDArray, Detections],
expected_result: List[Tuple[int, Optional[npt.NDArray], Optional[npt.NDArray]]],
exception: PytestExceptionType,
) -> None:
with exception:
helper_test_store(
data_1,
data_2,
class_agnostic=True,
metric_target=MetricTarget.MASKS,
expected_result=expected_result,
)