From ba732330a5b0fcea73819696910fa84393efaa9a Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 11:43:01 +0100 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=AB=B5=20allow=20integer=20array=20in?= =?UTF-8?q?dexing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/detection/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index cef6c577..6793ad65 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -186,7 +186,7 @@ class Detections: raise ValueError(f"{anchor} is not supported.") def __getitem__(self, index: np.ndarray) -> Detections: - if isinstance(index, np.ndarray) and index.dtype == bool: + if isinstance(index, np.ndarray) and (index.dtype == bool or index.dtype == int): return Detections( xyxy=self.xyxy[index], confidence=self.confidence[index], From 95b44db2bdeef973483875d75b607154fcdec4ce Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 11:50:17 +0100 Subject: [PATCH 2/8] from_transformers added --- supervision/detection/core.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 6793ad65..29448d12 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -132,6 +132,22 @@ class Detections: class_id=yolov8_results.boxes.cls.cpu().numpy().astype(int), ) + @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), + ) + + @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) + ) + def filter(self, mask: np.ndarray, inplace: bool = False) -> Optional[Detections]: """ Filter the detections by applying a mask. From 1c2d946527684681a222828329fd871c5b1e1b87 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 12:35:07 +0100 Subject: [PATCH 3/8] nms support --- supervision/detection/core.py | 5 +++++ supervision/detection/utils.py | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 29448d12..2d6c6f88 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -6,6 +6,7 @@ from typing import List, Optional, Union import cv2 import numpy as np +from supervision.detection.utils import non_max_suppression from supervision.draw.color import Color, ColorPalette from supervision.geometry.core import Position @@ -215,6 +216,10 @@ class Detections: f"Detections.__getitem__ not supported for index of type {type(index)}." ) + def with_nms(self, threshold: float = 0.5) -> Detections: + indices = non_max_suppression(self.xyxy, self.confidence, threshold=threshold) + return self[indices] + class BoxAnnotator: def __init__( diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index a3a33490..3658f1d9 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -18,3 +18,40 @@ def generate_2d_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np. mask = np.zeros((height, width), dtype=np.uint8) cv2.fillPoly(mask, [polygon], color=1) return mask + + +def non_max_suppression(boxes: np.ndarray, scores: np.ndarray, threshold: float): + assert boxes.shape[0] == scores.shape[0] + ys1 = boxes[:, 0] + xs1 = boxes[:, 1] + ys2 = boxes[:, 2] + xs2 = boxes[:, 3] + + areas = (ys2 - ys1) * (xs2 - xs1) + scores_indexes = scores.argsort().tolist() + boxes_keep_index = [] + while len(scores_indexes): + index = scores_indexes.pop() + boxes_keep_index.append(index) + if not len(scores_indexes): + break + 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 + ] + return np.array(boxes_keep_index) + + +def compute_iou(box, boxes, box_area, boxes_area): + assert boxes.shape[0] == boxes_area.shape[0] + ys1 = np.maximum(box[0], boxes[:, 0]) + xs1 = np.maximum(box[1], boxes[:, 1]) + ys2 = np.minimum(box[2], boxes[:, 2]) + xs2 = np.minimum(box[3], boxes[:, 3]) + intersections = np.maximum(ys2 - ys1, 0) * np.maximum(xs2 - xs1, 0) + unions = box_area + boxes_area - intersections + iou = intersections / unions + return iou From c0ae62a460ad92fb4c37f1f13c3ca76ea5b34757 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 15:12:33 +0100 Subject: [PATCH 4/8] making score/confidence optional to allow for using Detections to process labels --- README.md | 5 +++++ supervision/detection/core.py | 32 ++++++++++++++++++++------------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a6688a95..8042fda0 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ >

+
@@ -53,6 +54,10 @@
+
+ +[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-detect-and-count-objects-in-polygon-zone.ipynb) + ## 👋 hello diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 2d6c6f88..88d8ccdd 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -1,7 +1,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import List, Optional, Union +from typing import List, Optional, Union, Iterator, Tuple import cv2 import numpy as np @@ -18,24 +18,26 @@ class Detections: Attributes: xyxy (np.ndarray): An array of shape `(n, 4)` containing the bounding boxes coordinates in format `[x1, y1, x2, y2]` - confidence (np.ndarray): An array of shape `(n,)` containing the confidence scores of the detections. + confidence (Optional[np.ndarray]): An array of shape `(n,)` containing the confidence scores of the detections. class_id (np.ndarray): An array of shape `(n,)` containing the class ids of the detections. tracker_id (Optional[np.ndarray]): An array of shape `(n,)` containing the tracker ids of the detections. """ xyxy: np.ndarray - confidence: np.ndarray class_id: np.ndarray + confidence: Optional[np.ndarray] = None tracker_id: Optional[np.ndarray] = None def __post_init__(self): n = len(self.xyxy) validators = [ (isinstance(self.xyxy, np.ndarray) and self.xyxy.shape == (n, 4)), - (isinstance(self.confidence, np.ndarray) and self.confidence.shape == (n,)), (isinstance(self.class_id, np.ndarray) and self.class_id.shape == (n,)), - self.tracker_id is None - or ( + self.confidence is None or ( + isinstance(self.confidence, np.ndarray) + and self.confidence.shape == (n,) + ), + self.tracker_id is None or ( isinstance(self.tracker_id, np.ndarray) and self.tracker_id.shape == (n,) ), @@ -43,7 +45,7 @@ class Detections: if not all(validators): raise ValueError( "xyxy must be 2d np.ndarray with (n, 4) shape, " - "confidence must be 1d np.ndarray with (n,) shape, " + "confidence must be None or 1d np.ndarray with (n,) shape, " "class_id must be 1d np.ndarray with (n,) shape, " "tracker_id must be None or 1d np.ndarray with (n,) shape" ) @@ -54,14 +56,14 @@ class Detections: """ return len(self.xyxy) - def __iter__(self): + 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. """ for i in range(len(self.xyxy)): yield ( self.xyxy[i], - self.confidence[i], + self.confidence[i] if self.confidence is not None else None, self.class_id[i], self.tracker_id[i] if self.tracker_id is not None else None, ) @@ -70,11 +72,17 @@ class Detections: return all( [ np.array_equal(self.xyxy, other.xyxy), - np.array_equal(self.confidence, other.confidence), + any( + [ + self.confidence is None and other.confidence is None, + 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) ] ), ] @@ -123,7 +131,7 @@ class Detections: >>> from supervision import Detections >>> model = YOLO('yolov8s.pt') - >>> results = model(frame) + >>> results = model(frame)[0] >>> detections = Detections.from_yolov8(results) ``` """ @@ -287,7 +295,7 @@ class BoxAnnotator: continue text = ( - f"{confidence:0.2f}" + f"{class_id}" if (labels is None or len(detections) != len(labels)) else labels[i] ) From 96d8badf1a697e17ba736084be2f92bac070f482 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 17:35:07 +0100 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=A5=A5=20add=20from=5Fcoco=5Fannotati?= =?UTF-8?q?ons=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/detection/core.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 88d8ccdd..e768def5 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -157,6 +157,17 @@ class Detections: 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'] + xyxy.append([x_min, y_min, x_min + width, y_min + height]) + class_id.append(annotation['category_id']) + + return cls(xyxy=np.array(xyxy), class_id=np.array(class_id)) + def filter(self, mask: np.ndarray, inplace: bool = False) -> Optional[Detections]: """ Filter the detections by applying a mask. @@ -225,6 +236,7 @@ class Detections: ) 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.") indices = non_max_suppression(self.xyxy, self.confidence, threshold=threshold) return self[indices] From eefc5ddf7dda31cbc8d9c31f85886ca74fd13f9c Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 27 Feb 2023 22:09:41 +0100 Subject: [PATCH 6/8] fix redundant assert --- supervision/detection/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index e768def5..35edf1e9 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -236,7 +236,7 @@ class Detections: ) 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] From a27377aaf32ed7d645b980c20f6694d10db306b1 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 28 Feb 2023 15:27:08 +0100 Subject: [PATCH 7/8] add area property to Detections --- supervision/detection/core.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 35edf1e9..3f5b8c0c 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -235,6 +235,10 @@ class Detections: f"Detections.__getitem__ not supported for index of type {type(index)}." ) + @property + 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." indices = non_max_suppression(self.xyxy, self.confidence, threshold=threshold) From 8e7228313b00e4c7666d4ccf957f87d184eea825 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 1 Mar 2023 12:36:15 +0100 Subject: [PATCH 8/8] =?UTF-8?q?make=20black=20happy=20=F0=9F=96=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/__init__.py | 4 ++-- supervision/detection/core.py | 43 +++++++++++++++++++++------------- supervision/detection/utils.py | 8 +++---- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index ea2f155e..1ae9bc68 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -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 diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 3f5b8c0c..64f36907 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -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 @@ -33,11 +33,13 @@ class Detections: 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,) ), @@ -56,7 +58,9 @@ class Detections: """ 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. """ @@ -75,14 +79,14 @@ class 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), ] ), ] @@ -144,9 +148,9 @@ class Detections: @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 @@ -154,7 +158,10 @@ class Detections: 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 @@ -162,9 +169,9 @@ class Detections: 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)) @@ -222,7 +229,9 @@ class Detections: 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], @@ -240,7 +249,9 @@ class Detections: 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] diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 3658f1d9..0bb2734d 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -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)