Skip to content

Commit

Permalink
make black happy 🖤
Browse files Browse the repository at this point in the history
  • Loading branch information
SkalskiP committed Mar 1, 2023
1 parent a27377a commit 8e72283
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 22 deletions.
4 changes: 2 additions & 2 deletions supervision/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
__version__ = "0.2.1"
__version__ = "0.3.0"

from supervision.detection.core import BoxAnnotator, Detections
from supervision.detection.polygon_zone import PolygonZone, PolygonZoneAnnotator
from supervision.detection.line_counter import LineZone, LineZoneAnnotator
from supervision.detection.polygon_zone import PolygonZone, PolygonZoneAnnotator
from supervision.detection.utils import generate_2d_mask
from supervision.draw.color import Color, ColorPalette
from supervision.draw.utils import draw_filled_rectangle, draw_polygon, draw_text
Expand Down
43 changes: 27 additions & 16 deletions supervision/detection/core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import List, Optional, Union, Iterator, Tuple
from typing import Iterator, List, Optional, Tuple, Union

import cv2
import numpy as np
Expand Down Expand Up @@ -33,11 +33,13 @@ def __post_init__(self):
validators = [
(isinstance(self.xyxy, np.ndarray) and self.xyxy.shape == (n, 4)),
(isinstance(self.class_id, np.ndarray) and self.class_id.shape == (n,)),
self.confidence is None or (
isinstance(self.confidence, np.ndarray)
and self.confidence.shape == (n,)
self.confidence is None
or (
isinstance(self.confidence, np.ndarray)
and self.confidence.shape == (n,)
),
self.tracker_id is None or (
self.tracker_id is None
or (
isinstance(self.tracker_id, np.ndarray)
and self.tracker_id.shape == (n,)
),
Expand All @@ -56,7 +58,9 @@ def __len__(self):
"""
return len(self.xyxy)

def __iter__(self) -> Iterator[Tuple[np.ndarray, Optional[float], int, Optional[Union[str, int]]]]:
def __iter__(
self,
) -> Iterator[Tuple[np.ndarray, Optional[float], int, Optional[Union[str, int]]]]:
"""
Iterates over the Detections object and yield a tuple of `(xyxy, confidence, class_id, tracker_id)` for each detection.
"""
Expand All @@ -75,14 +79,14 @@ def __eq__(self, other: Detections):
any(
[
self.confidence is None and other.confidence is None,
np.array_equal(self.confidence, other.confidence)
np.array_equal(self.confidence, other.confidence),
]
),
np.array_equal(self.class_id, other.class_id),
any(
[
self.tracker_id is None and other.tracker_id is None,
np.array_equal(self.tracker_id, other.tracker_id)
np.array_equal(self.tracker_id, other.tracker_id),
]
),
]
Expand Down Expand Up @@ -144,27 +148,30 @@ def from_yolov8(cls, yolov8_results):
@classmethod
def from_transformers(cls, transformers_results: dict):
return cls(
xyxy=transformers_results['boxes'].cpu().numpy(),
confidence=transformers_results['scores'].cpu().numpy(),
class_id=transformers_results['labels'].cpu().numpy().astype(int),
xyxy=transformers_results["boxes"].cpu().numpy(),
confidence=transformers_results["scores"].cpu().numpy(),
class_id=transformers_results["labels"].cpu().numpy().astype(int),
)

@classmethod
def from_detectron2(cls, detectron2_results):
return cls(
xyxy=detectron2_results["instances"].pred_boxes.tensor.cpu().numpy(),
confidence=detectron2_results["instances"].scores.cpu().numpy(),
class_id=detectron2_results["instances"].pred_classes.cpu().numpy().astype(int)
class_id=detectron2_results["instances"]
.pred_classes.cpu()
.numpy()
.astype(int),
)

@classmethod
def from_coco_annotations(cls, coco_annotation: dict):
xyxy, class_id = [], []

for annotation in coco_annotation:
x_min, y_min, width, height = annotation['bbox']
x_min, y_min, width, height = annotation["bbox"]
xyxy.append([x_min, y_min, x_min + width, y_min + height])
class_id.append(annotation['category_id'])
class_id.append(annotation["category_id"])

return cls(xyxy=np.array(xyxy), class_id=np.array(class_id))

Expand Down Expand Up @@ -222,7 +229,9 @@ def get_anchor_coordinates(self, anchor: Position) -> np.ndarray:
raise ValueError(f"{anchor} is not supported.")

def __getitem__(self, index: np.ndarray) -> Detections:
if isinstance(index, np.ndarray) and (index.dtype == bool or index.dtype == int):
if isinstance(index, np.ndarray) and (
index.dtype == bool or index.dtype == int
):
return Detections(
xyxy=self.xyxy[index],
confidence=self.confidence[index],
Expand All @@ -240,7 +249,9 @@ def area(self) -> np.ndarray:
return (self.xyxy[:, 3] - self.xyxy[:, 1]) * (self.xyxy[:, 2] - self.xyxy[:, 0])

def with_nms(self, threshold: float = 0.5) -> Detections:
assert self.confidence is not None, f"Detections confidence must be given for NMS to be executed."
assert (
self.confidence is not None
), f"Detections confidence must be given for NMS to be executed."
indices = non_max_suppression(self.xyxy, self.confidence, threshold=threshold)
return self[indices]

Expand Down
8 changes: 4 additions & 4 deletions supervision/detection/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ def non_max_suppression(boxes: np.ndarray, scores: np.ndarray, threshold: float)
boxes_keep_index.append(index)
if not len(scores_indexes):
break
iou = compute_iou(boxes[index], boxes[scores_indexes], areas[index],
areas[scores_indexes])
iou = compute_iou(
boxes[index], boxes[scores_indexes], areas[index], areas[scores_indexes]
)
filtered_indexes = set((iou > threshold).nonzero()[0])
scores_indexes = [
v for (i, v) in enumerate(scores_indexes)
if i not in filtered_indexes
v for (i, v) in enumerate(scores_indexes) if i not in filtered_indexes
]
return np.array(boxes_keep_index)

Expand Down

0 comments on commit 8e72283

Please sign in to comment.