From 5d381207432f03f00dd704c4bb2c71e2237966ce Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 6 May 2024 15:39:59 +0200 Subject: [PATCH 01/13] added `from_xyxy` and `as_xyxy_int_tuple` methods to `Rect`. added `draw_rounded_rectangle` function. --- supervision/draw/utils.py | 52 ++++++++++++++++++++++++++++++++++++ supervision/geometry/core.py | 13 +++++++++ 2 files changed, 65 insertions(+) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 638e6b75..6783ae25 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -81,6 +81,58 @@ def draw_filled_rectangle(scene: np.ndarray, rect: Rect, color: Color) -> np.nda return scene +def draw_rounded_rectangle( + scene: np.ndarray, + rect: Rect, + color: Color, + border_radius: int, +) -> np.ndarray: + """ + Draws a rounded rectangle on an image. + + Parameters: + scene (np.ndarray): The image on which the rounded rectangle will be drawn. + rect (Rect): The rectangle to be drawn. + color (Color): The color of the rounded rectangle. + border_radius (int): The radius of the corner rounding. + + Returns: + np.ndarray: The image with the rounded rectangle drawn on it. + """ + x1, y1, x2, y2 = rect.as_xyxy_int_tuple() + width, height = x2 - x1, y2 - y1 + border_radius = min(border_radius, min(width, height) // 2) + + rectangle_coordinates = [ + ((x1 + border_radius, y1), (x2 - border_radius, y2)), + ((x1, y1 + border_radius), (x2, y2 - border_radius)), + ] + circle_centers = [ + (x1 + border_radius, y1 + border_radius), + (x2 - border_radius, y1 + border_radius), + (x1 + border_radius, y2 - border_radius), + (x2 - border_radius, y2 - border_radius), + ] + + for coordinates in rectangle_coordinates: + cv2.rectangle( + img=scene, + pt1=coordinates[0], + pt2=coordinates[1], + color=color.as_bgr(), + thickness=-1, + ) + for center in circle_centers: + cv2.circle( + img=scene, + center=center, + radius=border_radius, + color=color.as_bgr(), + thickness=-1, + ) + return scene + + def draw_polygon( scene: np.ndarray, polygon: np.ndarray, color: Color, thickness: int = 2 ) -> np.ndarray: diff --git a/supervision/geometry/core.py b/supervision/geometry/core.py index 39d42c60..81056800 100644 --- a/supervision/geometry/core.py +++ b/supervision/geometry/core.py @@ -98,6 +98,11 @@ class Rect: width: float height: float + @classmethod + def from_xyxy(cls, xyxy: Tuple[float, float, float, float]) -> Rect: + x1, y1, x2, y2 = xyxy + return cls(x=x1, y=y1, width=x2 - x1, height=y2 - y1) + @property def top_left(self) -> Point: return Point(x=self.x, y=self.y) @@ -113,3 +118,11 @@ class Rect: width=self.width + 2 * padding, height=self.height + 2 * padding, ) + + def as_xyxy_int_tuple(self) -> Tuple[int, int, int, int]: + return ( + int(self.x), + int(self.y), + int(self.x + self.width), + int(self.y + self.height) + ) \ No newline at end of file From 5c539c3bda76632d5dd39b833b0ccb99a358f110 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 13:49:22 +0000 Subject: [PATCH 02/13] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto?= =?UTF-8?q?=20format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/geometry/core.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/supervision/geometry/core.py b/supervision/geometry/core.py index 81056800..a884a9da 100644 --- a/supervision/geometry/core.py +++ b/supervision/geometry/core.py @@ -124,5 +124,5 @@ class Rect: int(self.x), int(self.y), int(self.x + self.width), - int(self.y + self.height) - ) \ No newline at end of file + int(self.y + self.height), + ) From 95c243c058062370d63df001bbd30127873a27a6 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 6 May 2024 17:40:33 +0200 Subject: [PATCH 03/13] better `draw_rounded_rectangle` implementation --- supervision/draw/utils.py | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 6783ae25..1980cbe1 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -103,26 +103,22 @@ def draw_rounded_rectangle( width, height = x2 - x1, y2 - y1 border_radius = min(border_radius, min(width, height) // 2) - rectangle_coordinates = [ - ((x1 + border_radius, y1), (x2 - border_radius, y2)), - ((x1, y1 + border_radius), (x2, y2 - border_radius)), - ] - circle_centers = [ - (x1 + border_radius, y1 + border_radius), - (x2 - border_radius, y1 + border_radius), - (x1 + border_radius, y2 - border_radius), - (x2 - border_radius, y2 - border_radius), + corners = [ + (x1 + border_radius, y1), + (x2 - border_radius, y1), + (x2, y1 + border_radius), + (x2, y2 - border_radius), + (x2 - border_radius, y2), + (x1 + border_radius, y2), + (x1, y2 - border_radius), + (x1, y1 + border_radius), ] - for coordinates in rectangle_coordinates: - cv2.rectangle( - img=scene, - pt1=coordinates[0], - pt2=coordinates[1], - color=color.as_bgr(), - thickness=-1, - ) - for center in circle_centers: + pts = np.array(corners, np.int32) + pts = pts.reshape((-1, 1, 2)) + cv2.fillPoly(scene, [pts], color.as_bgr()) + + for center in corners: cv2.circle( img=scene, center=center, @@ -130,6 +126,7 @@ def draw_rounded_rectangle( color=color.as_bgr(), thickness=-1, ) + return scene From ec6864ff04d1b49a1afc8168ea2dd3469e0f61ab Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 6 May 2024 18:00:13 +0200 Subject: [PATCH 04/13] roll back new `draw_rounded_rectangle` implementation --- supervision/draw/utils.py | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 1980cbe1..6783ae25 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -103,22 +103,26 @@ def draw_rounded_rectangle( width, height = x2 - x1, y2 - y1 border_radius = min(border_radius, min(width, height) // 2) - corners = [ - (x1 + border_radius, y1), - (x2 - border_radius, y1), - (x2, y1 + border_radius), - (x2, y2 - border_radius), - (x2 - border_radius, y2), - (x1 + border_radius, y2), - (x1, y2 - border_radius), - (x1, y1 + border_radius), + rectangle_coordinates = [ + ((x1 + border_radius, y1), (x2 - border_radius, y2)), + ((x1, y1 + border_radius), (x2, y2 - border_radius)), + ] + circle_centers = [ + (x1 + border_radius, y1 + border_radius), + (x2 - border_radius, y1 + border_radius), + (x1 + border_radius, y2 - border_radius), + (x2 - border_radius, y2 - border_radius), ] - pts = np.array(corners, np.int32) - pts = pts.reshape((-1, 1, 2)) - cv2.fillPoly(scene, [pts], color.as_bgr()) - - for center in corners: + for coordinates in rectangle_coordinates: + cv2.rectangle( + img=scene, + pt1=coordinates[0], + pt2=coordinates[1], + color=color.as_bgr(), + thickness=-1, + ) + for center in circle_centers: cv2.circle( img=scene, center=center, @@ -126,7 +130,6 @@ def draw_rounded_rectangle( color=color.as_bgr(), thickness=-1, ) - return scene From ab0882dd55a29be6b3ff23b3b96545b8cfab2721 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 6 May 2024 18:15:05 +0200 Subject: [PATCH 05/13] initial version of `VertexLabelAnnotator` --- docs/detection/utils.md | 12 +++ supervision/__init__.py | 8 +- supervision/detection/utils.py | 29 +++++++ supervision/keypoint/annotators.py | 123 +++++++++++++++++++++++++++-- 4 files changed, 163 insertions(+), 9 deletions(-) diff --git a/docs/detection/utils.md b/docs/detection/utils.md index abacdc21..76116fc7 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -70,3 +70,15 @@ status: new :::supervision.detection.utils.scale_boxes + + + +:::supervision.detection.utils.clip_boxes + + + +:::supervision.detection.utils.pad_boxes diff --git a/supervision/__init__.py b/supervision/__init__.py index bb526514..43760686 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -55,6 +55,8 @@ from supervision.detection.utils import ( polygon_to_mask, polygon_to_xyxy, scale_boxes, + clip_boxes, + pad_boxes ) from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( @@ -69,7 +71,11 @@ from supervision.draw.utils import ( ) from supervision.geometry.core import Point, Position, Rect from supervision.geometry.utils import get_polygon_center -from supervision.keypoint.annotators import EdgeAnnotator, VertexAnnotator +from supervision.keypoint.annotators import ( + EdgeAnnotator, + VertexAnnotator, + VertexLabelAnnotator +) from supervision.keypoint.core import KeyPoints from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision from supervision.tracker.byte_tracker.core import ByteTrack diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 3eeba5b4..2b088cce 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -297,6 +297,35 @@ def clip_boxes(xyxy: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: return result +def pad_boxes(xyxy: np.ndarray, px: int, py: Optional[int] = None) -> np.ndarray: + """ + Pads bounding boxes coordinates with a constant padding. + + Args: + xyxy (np.ndarray): A numpy array of shape `(N, 4)` where each + row corresponds to a bounding box in the format + `(x_min, y_min, x_max, y_max)`. + px (int): The padding value to be added to both the left and right sides of + each bounding box. + py (Optional[int]): The padding value to be added to both the top and bottom + sides of each bounding box. If not provided, `px` will be used for both + dimensions. + + Returns: + np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds to a + bounding box with coordinates padded according to the provided padding + values. + """ + if py is None: + py = px + + result = xyxy.copy() + result[:, [0, 1]] -= [px, py] + result[:, [2, 3]] += [px, py] + + return result + + def xywh_to_xyxy(boxes_xywh: np.ndarray) -> np.ndarray: xyxy = boxes_xywh.copy() xyxy[:, 2] = boxes_xywh[:, 0] + boxes_xywh[:, 2] diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index 4b43765c..01059ac6 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -1,12 +1,14 @@ from abc import ABC, abstractmethod from logging import warn -from typing import List, Optional, Tuple +from typing import List, Optional, Tuple, Union import cv2 import numpy as np +from supervision import Rect, pad_boxes from supervision.annotators.base import ImageType from supervision.draw.color import Color +from supervision.draw.utils import draw_rounded_rectangle from supervision.keypoint.core import KeyPoints from supervision.keypoint.skeletons import SKELETONS_BY_VERTEX_COUNT from supervision.utils.conversion import convert_for_annotation_method @@ -26,9 +28,9 @@ class VertexAnnotator(BaseKeyPointAnnotator): """ def __init__( - self, - color: Color = Color.ROBOFLOW, - radius: int = 4, + self, + color: Color = Color.ROBOFLOW, + radius: int = 4, ) -> None: """ Args: @@ -96,10 +98,10 @@ class EdgeAnnotator(BaseKeyPointAnnotator): """ def __init__( - self, - color: Color = Color.ROBOFLOW, - thickness: int = 2, - edges: Optional[List[Tuple[int, int]]] = None, + self, + color: Color = Color.ROBOFLOW, + thickness: int = 2, + edges: Optional[List[Tuple[int, int]]] = None, ) -> None: """ Args: @@ -175,3 +177,108 @@ class EdgeAnnotator(BaseKeyPointAnnotator): ) return scene + + +class VertexLabelAnnotator: + """ + A class for annotating vertex labels on an image using provided detections. + """ + + def __init__( + self, + color: Union[Color, List[Color]] = Color.ROBOFLOW, + text_color: Color = Color.WHITE, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + border_radius: int = 0, + ): + self.border_radius: int = border_radius + self.color: Union[Color, List[Color]] = color + self.text_color: Color = text_color + self.text_scale: float = text_scale + self.text_thickness: int = text_thickness + self.text_padding: int = text_padding + + @staticmethod + def get_text_bounding_box( + text: str, + font: int, + text_scale: float, + text_thickness: int, + center_coordinates: Tuple[int, int] + ) -> Tuple[int, int, int, int]: + text_w, text_h = cv2.getTextSize( + text=text, + fontFace=font, + fontScale=text_scale, + thickness=text_thickness, + )[0] + center_x, center_y = center_coordinates + return ( + center_x - text_w // 2, + center_y - text_h // 2, + center_x + text_w // 2, + center_y + text_h // 2, + ) + + def annotate( + self, + scene: ImageType, + key_points: KeyPoints, + labels: List[str] = None + ) -> ImageType: + font = cv2.FONT_HERSHEY_SIMPLEX + + N, K, _ = key_points.xy.shape + + if N == 0: + return scene + + anchors = key_points.xy.reshape(K * N, 2).astype(int) + colors = np.array(self.color * N) if isinstance(self.color, list) else np.array( + [self.color] * K * N) + labels = np.array(labels * N) + + mask = np.all(anchors != 0, axis=1) + + if np.all(mask == False): + return scene + + anchors = anchors[mask] + colors = colors[mask] + labels = labels[mask] + + xyxy = np.array([ + self.get_text_bounding_box( + text=label, + font=font, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + center_coordinates=tuple(anchor) + ) + for anchor, label + in zip(anchors, labels) + ]) + + xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding) + + for text, color, box, box_padded in zip(labels, colors, xyxy, xyxy_padded): + draw_rounded_rectangle( + scene=scene, + rect=Rect.from_xyxy(box_padded), + color=color, + border_radius=self.border_radius, + ) + cv2.putText( + img=scene, + text=text, + org=(box[0], box[1] + self.text_padding), + fontFace=font, + fontScale=self.text_scale, + color=self.text_color.as_rgb(), + thickness=self.text_thickness, + lineType=cv2.LINE_AA, + ) + + return scene From 7823e0de89326a6fff4ca9a5d3f2404b51f89d77 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 16:16:37 +0000 Subject: [PATCH 06/13] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto?= =?UTF-8?q?=20format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/__init__.py | 6 +-- supervision/keypoint/annotators.py | 73 +++++++++++++++--------------- 2 files changed, 40 insertions(+), 39 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index 43760686..fc79a81f 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -46,17 +46,17 @@ from supervision.detection.utils import ( box_iou_batch, box_non_max_suppression, calculate_masks_centroids, + clip_boxes, filter_polygons_by_area, mask_iou_batch, mask_non_max_suppression, mask_to_polygons, mask_to_xyxy, move_boxes, + pad_boxes, polygon_to_mask, polygon_to_xyxy, scale_boxes, - clip_boxes, - pad_boxes ) from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( @@ -74,7 +74,7 @@ from supervision.geometry.utils import get_polygon_center from supervision.keypoint.annotators import ( EdgeAnnotator, VertexAnnotator, - VertexLabelAnnotator + VertexLabelAnnotator, ) from supervision.keypoint.core import KeyPoints from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index 01059ac6..56eafdf9 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -28,9 +28,9 @@ class VertexAnnotator(BaseKeyPointAnnotator): """ def __init__( - self, - color: Color = Color.ROBOFLOW, - radius: int = 4, + self, + color: Color = Color.ROBOFLOW, + radius: int = 4, ) -> None: """ Args: @@ -98,10 +98,10 @@ class EdgeAnnotator(BaseKeyPointAnnotator): """ def __init__( - self, - color: Color = Color.ROBOFLOW, - thickness: int = 2, - edges: Optional[List[Tuple[int, int]]] = None, + self, + color: Color = Color.ROBOFLOW, + thickness: int = 2, + edges: Optional[List[Tuple[int, int]]] = None, ) -> None: """ Args: @@ -185,13 +185,13 @@ class VertexLabelAnnotator: """ def __init__( - self, - color: Union[Color, List[Color]] = Color.ROBOFLOW, - text_color: Color = Color.WHITE, - text_scale: float = 0.5, - text_thickness: int = 1, - text_padding: int = 10, - border_radius: int = 0, + self, + color: Union[Color, List[Color]] = Color.ROBOFLOW, + text_color: Color = Color.WHITE, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + border_radius: int = 0, ): self.border_radius: int = border_radius self.color: Union[Color, List[Color]] = color @@ -202,11 +202,11 @@ class VertexLabelAnnotator: @staticmethod def get_text_bounding_box( - text: str, - font: int, - text_scale: float, - text_thickness: int, - center_coordinates: Tuple[int, int] + text: str, + font: int, + text_scale: float, + text_thickness: int, + center_coordinates: Tuple[int, int], ) -> Tuple[int, int, int, int]: text_w, text_h = cv2.getTextSize( text=text, @@ -223,10 +223,7 @@ class VertexLabelAnnotator: ) def annotate( - self, - scene: ImageType, - key_points: KeyPoints, - labels: List[str] = None + self, scene: ImageType, key_points: KeyPoints, labels: List[str] = None ) -> ImageType: font = cv2.FONT_HERSHEY_SIMPLEX @@ -236,8 +233,11 @@ class VertexLabelAnnotator: return scene anchors = key_points.xy.reshape(K * N, 2).astype(int) - colors = np.array(self.color * N) if isinstance(self.color, list) else np.array( - [self.color] * K * N) + colors = ( + np.array(self.color * N) + if isinstance(self.color, list) + else np.array([self.color] * K * N) + ) labels = np.array(labels * N) mask = np.all(anchors != 0, axis=1) @@ -249,17 +249,18 @@ class VertexLabelAnnotator: colors = colors[mask] labels = labels[mask] - xyxy = np.array([ - self.get_text_bounding_box( - text=label, - font=font, - text_scale=self.text_scale, - text_thickness=self.text_thickness, - center_coordinates=tuple(anchor) - ) - for anchor, label - in zip(anchors, labels) - ]) + xyxy = np.array( + [ + self.get_text_bounding_box( + text=label, + font=font, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + center_coordinates=tuple(anchor), + ) + for anchor, label in zip(anchors, labels) + ] + ) xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding) From 3b61ee674ea94ee1b7ae5db3dcb11f6fbbe3349d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 10 May 2024 00:28:34 +0000 Subject: [PATCH 07/13] :arrow_up: Bump ruff from 0.4.3 to 0.4.4 Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.3 to 0.4.4. - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/v0.4.3...v0.4.4) --- updated-dependencies: - dependency-name: ruff dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- poetry.lock | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/poetry.lock b/poetry.lock index 0eb454a8..5dc8c24c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3661,28 +3661,28 @@ files = [ [[package]] name = "ruff" -version = "0.4.3" +version = "0.4.4" description = "An extremely fast Python linter and code formatter, written in Rust." optional = false python-versions = ">=3.7" files = [ - {file = "ruff-0.4.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b70800c290f14ae6fcbb41bbe201cf62dfca024d124a1f373e76371a007454ce"}, - {file = "ruff-0.4.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:08a0d6a22918ab2552ace96adeaca308833873a4d7d1d587bb1d37bae8728eb3"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba1f14df3c758dd7de5b55fbae7e1c8af238597961e5fb628f3de446c3c40c5"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:819fb06d535cc76dfddbfe8d3068ff602ddeb40e3eacbc90e0d1272bb8d97113"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0bfc9e955e6dc6359eb6f82ea150c4f4e82b660e5b58d9a20a0e42ec3bb6342b"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:510a67d232d2ebe983fddea324dbf9d69b71c4d2dfeb8a862f4a127536dd4cfb"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dc9ff11cd9a092ee7680a56d21f302bdda14327772cd870d806610a3503d001f"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:29efff25bf9ee685c2c8390563a5b5c006a3fee5230d28ea39f4f75f9d0b6f2f"}, - {file = "ruff-0.4.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:18b00e0bcccf0fc8d7186ed21e311dffd19761cb632241a6e4fe4477cc80ef6e"}, - {file = "ruff-0.4.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:262f5635e2c74d80b7507fbc2fac28fe0d4fef26373bbc62039526f7722bca1b"}, - {file = "ruff-0.4.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7363691198719c26459e08cc17c6a3dac6f592e9ea3d2fa772f4e561b5fe82a3"}, - {file = "ruff-0.4.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:eeb039f8428fcb6725bb63cbae92ad67b0559e68b5d80f840f11914afd8ddf7f"}, - {file = "ruff-0.4.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:927b11c1e4d0727ce1a729eace61cee88a334623ec424c0b1c8fe3e5f9d3c865"}, - {file = "ruff-0.4.3-py3-none-win32.whl", hash = "sha256:25cacda2155778beb0d064e0ec5a3944dcca9c12715f7c4634fd9d93ac33fd30"}, - {file = "ruff-0.4.3-py3-none-win_amd64.whl", hash = "sha256:7a1c3a450bc6539ef00da6c819fb1b76b6b065dec585f91456e7c0d6a0bbc725"}, - {file = "ruff-0.4.3-py3-none-win_arm64.whl", hash = "sha256:71ca5f8ccf1121b95a59649482470c5601c60a416bf189d553955b0338e34614"}, - {file = "ruff-0.4.3.tar.gz", hash = "sha256:ff0a3ef2e3c4b6d133fbedcf9586abfbe38d076041f2dc18ffb2c7e0485d5a07"}, + {file = "ruff-0.4.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:29d44ef5bb6a08e235c8249294fa8d431adc1426bfda99ed493119e6f9ea1bf6"}, + {file = "ruff-0.4.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c4efe62b5bbb24178c950732ddd40712b878a9b96b1d02b0ff0b08a090cbd891"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4c8e2f1e8fc12d07ab521a9005d68a969e167b589cbcaee354cb61e9d9de9c15"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:60ed88b636a463214905c002fa3eaab19795679ed55529f91e488db3fe8976ab"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b90fc5e170fc71c712cc4d9ab0e24ea505c6a9e4ebf346787a67e691dfb72e85"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:8e7e6ebc10ef16dcdc77fd5557ee60647512b400e4a60bdc4849468f076f6eef"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b9ddb2c494fb79fc208cd15ffe08f32b7682519e067413dbaf5f4b01a6087bcd"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c51c928a14f9f0a871082603e25a1588059b7e08a920f2f9fa7157b5bf08cfe9"}, + {file = "ruff-0.4.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b5eb0a4bfd6400b7d07c09a7725e1a98c3b838be557fee229ac0f84d9aa49c36"}, + {file = "ruff-0.4.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:b1867ee9bf3acc21778dcb293db504692eda5f7a11a6e6cc40890182a9f9e595"}, + {file = "ruff-0.4.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1aecced1269481ef2894cc495647392a34b0bf3e28ff53ed95a385b13aa45768"}, + {file = "ruff-0.4.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:9da73eb616b3241a307b837f32756dc20a0b07e2bcb694fec73699c93d04a69e"}, + {file = "ruff-0.4.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:958b4ea5589706a81065e2a776237de2ecc3e763342e5cc8e02a4a4d8a5e6f95"}, + {file = "ruff-0.4.4-py3-none-win32.whl", hash = "sha256:cb53473849f011bca6e754f2cdf47cafc9c4f4ff4570003a0dad0b9b6890e876"}, + {file = "ruff-0.4.4-py3-none-win_amd64.whl", hash = "sha256:424e5b72597482543b684c11def82669cc6b395aa8cc69acc1858b5ef3e5daae"}, + {file = "ruff-0.4.4-py3-none-win_arm64.whl", hash = "sha256:39df0537b47d3b597293edbb95baf54ff5b49589eb7ff41926d8243caa995ea6"}, + {file = "ruff-0.4.4.tar.gz", hash = "sha256:f87ea42d5cdebdc6a69761a9d0bc83ae9b3b30d0ad78952005ba6568d6c022af"}, ] [[package]] From 528c96058771eccbe43838f87fef1bfb56dd7069 Mon Sep 17 00:00:00 2001 From: Linas Kondrackis Date: Sat, 11 May 2024 13:38:23 +0300 Subject: [PATCH 08/13] Minor docs update: missing return in inference slicer callback --- docs/how_to/detect_small_objects.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/how_to/detect_small_objects.md b/docs/how_to/detect_small_objects.md index e2d02328..b0447a64 100644 --- a/docs/how_to/detect_small_objects.md +++ b/docs/how_to/detect_small_objects.md @@ -6,7 +6,7 @@ status: new # Detect Small Objects This guide shows how to detect small objects -with the [Inference](https://github.com/roboflow/inference), +with the [Inference](https://github.com/roboflow/inference), [Ultralytics](https://github.com/ultralytics/ultralytics) or [Transformers](https://github.com/huggingface/transformers) packages using [`InferenceSlicer`](/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer). @@ -175,7 +175,7 @@ objects within each, and aggregating the results. def callback(image_slice: np.ndarray) -> sv.Detections: results = model.infer(image_slice)[0] - detections = sv.Detections.from_inference(results) + return sv.Detections.from_inference(results) slicer = sv.InferenceSlicer(callback = callback) detections = slicer(image) From f56d7a173365c0688172f6ecc2363a1f661f624a Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 13 May 2024 14:01:07 +0200 Subject: [PATCH 09/13] changes after code review --- supervision/keypoint/annotators.py | 155 ++++++++++++++++++++++------- 1 file changed, 117 insertions(+), 38 deletions(-) diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index 56eafdf9..348a42fb 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -48,8 +48,8 @@ class VertexAnnotator(BaseKeyPointAnnotator): points. It draws circles at each key point location. Args: - scene (ImageType): The image where bounding boxes will be drawn. `ImageType` - is a flexible type, accepting either `numpy.ndarray` or + scene (ImageType): The image where skeleton vertices will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. key_points (KeyPoints): A collection of key points where each key point consists of x and y coordinates. @@ -121,7 +121,7 @@ class EdgeAnnotator(BaseKeyPointAnnotator): edges. Args: - scene (ImageType): The image where bounding boxes will be drawn. `ImageType` + scene (ImageType): The image where skeleton edges will be drawn. `ImageType` is a flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. key_points (KeyPoints): A collection of key points where each key point @@ -181,7 +181,8 @@ class EdgeAnnotator(BaseKeyPointAnnotator): class VertexLabelAnnotator: """ - A class for annotating vertex labels on an image using provided detections. + A class that draws labels of skeleton vertices on images. It uses specified key + points to determine the locations where the vertices should be drawn. """ def __init__( @@ -193,6 +194,18 @@ class VertexLabelAnnotator: text_padding: int = 10, border_radius: int = 0, ): + """ + Args: + color (Union[Color, List[Color]], optional): The color to use for each + keypoint label. If a list is provided, the colors will be used in order + for each keypoint. + text_color (Color, optional): The color to use for the labels. + text_scale (float, optional): The scale of the text. + text_thickness (int, optional): The thickness of the text. + text_padding (int, optional): The padding around the text. + border_radius (int, optional): The radius of the rounded corners of the + boxes. Set to a high value to produce circles. + """ self.border_radius: int = border_radius self.color: Union[Color, List[Color]] = color self.text_color: Color = text_color @@ -200,51 +213,62 @@ class VertexLabelAnnotator: self.text_thickness: int = text_thickness self.text_padding: int = text_padding - @staticmethod - def get_text_bounding_box( - text: str, - font: int, - text_scale: float, - text_thickness: int, - center_coordinates: Tuple[int, int], - ) -> Tuple[int, int, int, int]: - text_w, text_h = cv2.getTextSize( - text=text, - fontFace=font, - fontScale=text_scale, - thickness=text_thickness, - )[0] - center_x, center_y = center_coordinates - return ( - center_x - text_w // 2, - center_y - text_h // 2, - center_x + text_w // 2, - center_y + text_h // 2, - ) - def annotate( self, scene: ImageType, key_points: KeyPoints, labels: List[str] = None ) -> ImageType: + """ + A class that draws labels of skeleton vertices on images. It uses specified key + points to determine the locations where the vertices should be drawn. + + Args: + scene (ImageType): The image where vertex labels will be drawn. `ImageType` + is a flexible type, accepting either `numpy.ndarray` or + `PIL.Image.Image`. + key_points (KeyPoints): A collection of key points where each key point + consists of x and y coordinates. + labels (List[str], optional): A list of labels to be displayed on the + annotated image. If not provided, keypoint indices will be used. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Example: + ```python + import supervision as sv + + image = ... + key_points = sv.KeyPoints(...) + + vertex_label_annotator = sv.VertexLabelAnnotator() + annotated_frame = vertex_label_annotator.annotate( + scene=image.copy(), + key_points=key_points + ) + ``` + """ font = cv2.FONT_HERSHEY_SIMPLEX - N, K, _ = key_points.xy.shape - - if N == 0: + skeletons_count, points_count, _ = key_points.xy.shape + if skeletons_count == 0: return scene - anchors = key_points.xy.reshape(K * N, 2).astype(int) - colors = ( - np.array(self.color * N) - if isinstance(self.color, list) - else np.array([self.color] * K * N) - ) - labels = np.array(labels * N) - + anchors = key_points.xy.reshape(points_count * skeletons_count, 2).astype(int) mask = np.all(anchors != 0, axis=1) - if np.all(mask == False): + if not np.any(mask): return scene + colors = self.preprocess_and_validate_colors( + colors=self.color, + points_count=points_count, + skeletons_count=skeletons_count) + + labels = self.preprocess_and_validate_labels( + labels=labels, + points_count=points_count, + skeletons_count=skeletons_count) + anchors = anchors[mask] colors = colors[mask] labels = labels[mask] @@ -283,3 +307,58 @@ class VertexLabelAnnotator: ) return scene + + @staticmethod + def get_text_bounding_box( + text: str, + font: int, + text_scale: float, + text_thickness: int, + center_coordinates: Tuple[int, int], + ) -> Tuple[int, int, int, int]: + text_w, text_h = cv2.getTextSize( + text=text, + fontFace=font, + fontScale=text_scale, + thickness=text_thickness, + )[0] + center_x, center_y = center_coordinates + return ( + center_x - text_w // 2, + center_y - text_h // 2, + center_x + text_w // 2, + center_y + text_h // 2, + ) + + @staticmethod + def preprocess_and_validate_labels( + labels: Optional[List[str]], + points_count: int, + skeletons_count: int + ) -> np.array: + if labels and len(labels) != points_count: + raise ValueError( + f"Number of labels ({len(labels)}) must match number of key points " + f"({points_count})." + ) + if labels is None: + labels = [str(i) for i in range(points_count)] + + return np.array(labels * skeletons_count) + + @staticmethod + def preprocess_and_validate_colors( + colors: Optional[Union[Color, List[Color]]], + points_count: int, + skeletons_count: int + ) -> np.array: + if isinstance(colors, list) and len(colors) != points_count: + raise ValueError( + f"Number of colors ({len(colors)}) must match number of key points " + f"({points_count})." + ) + return ( + np.array(colors * skeletons_count) + if isinstance(colors, list) + else np.array([colors] * points_count * skeletons_count) + ) From 1ebccebf4c194af8679924101b41ee9cacf45eb6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 13 May 2024 12:01:23 +0000 Subject: [PATCH 10/13] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto?= =?UTF-8?q?=20format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/keypoint/annotators.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index 348a42fb..888e7e2a 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -262,12 +262,12 @@ class VertexLabelAnnotator: colors = self.preprocess_and_validate_colors( colors=self.color, points_count=points_count, - skeletons_count=skeletons_count) + skeletons_count=skeletons_count, + ) labels = self.preprocess_and_validate_labels( - labels=labels, - points_count=points_count, - skeletons_count=skeletons_count) + labels=labels, points_count=points_count, skeletons_count=skeletons_count + ) anchors = anchors[mask] colors = colors[mask] @@ -332,9 +332,7 @@ class VertexLabelAnnotator: @staticmethod def preprocess_and_validate_labels( - labels: Optional[List[str]], - points_count: int, - skeletons_count: int + labels: Optional[List[str]], points_count: int, skeletons_count: int ) -> np.array: if labels and len(labels) != points_count: raise ValueError( @@ -350,7 +348,7 @@ class VertexLabelAnnotator: def preprocess_and_validate_colors( colors: Optional[Union[Color, List[Color]]], points_count: int, - skeletons_count: int + skeletons_count: int, ) -> np.array: if isinstance(colors, list) and len(colors) != points_count: raise ValueError( From 051fe5178bb75f205087e13e5571cdbbc7ae3280 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 13 May 2024 14:30:55 +0200 Subject: [PATCH 11/13] VertexLabelAnnotator plugged into docs --- docs/keypoint/annotators.md | 41 ++++++++++++++++++++++++++++-- supervision/keypoint/annotators.py | 19 +++++++++++--- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/docs/keypoint/annotators.md b/docs/keypoint/annotators.md index b5f998bc..e7adeb09 100644 --- a/docs/keypoint/annotators.md +++ b/docs/keypoint/annotators.md @@ -13,7 +13,10 @@ status: new image = ... key_points = sv.KeyPoints(...) - vertex_annotator = sv.VertexAnnotator(color=sv.Color.GREEN, radius=10) + vertex_annotator = sv.VertexAnnotator( + color=sv.Color.GREEN, + radius=10 + ) annotated_frame = vertex_annotator.annotate( scene=image.copy(), key_points=key_points @@ -34,7 +37,10 @@ status: new image = ... key_points = sv.KeyPoints(...) - edge_annotator = sv.EdgeAnnotator(color=sv.Color.GREEN, thickness=5) + edge_annotator = sv.EdgeAnnotator( + color=sv.Color.GREEN, + thickness=5 + ) annotated_frame = edge_annotator.annotate( scene=image.copy(), key_points=key_points @@ -47,6 +53,31 @@ status: new +=== "VertexLabelAnnotator" + + ```python + import supervision as sv + + image = ... + key_points = sv.KeyPoints(...) + + vertex_label_annotator = sv.VertexLabelAnnotator( + color=sv.Color.GREEN, + text_color=sv.Color.BLACK, + border_radius=5 + ) + annotated_frame = vertex_label_annotator.annotate( + scene=image.copy(), + key_points=key_points + ) + ``` + +
+ + ![vertex-label-annotator-example](https://media.roboflow.com/supervision-annotator-examples/vertex-label-annotator-example.png){ align=center width="800" } + +
+ @@ -58,3 +89,9 @@ status: new :::supervision.keypoint.annotators.EdgeAnnotator + + + +:::supervision.keypoint.annotators.VertexLabelAnnotator diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index 348a42fb..e8787273 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -65,7 +65,10 @@ class VertexAnnotator(BaseKeyPointAnnotator): image = ... key_points = sv.KeyPoints(...) - vertex_annotator = sv.VertexAnnotator(color=sv.Color.GREEN, radius=10) + vertex_annotator = sv.VertexAnnotator( + color=sv.Color.GREEN, + radius=10 + ) annotated_frame = vertex_annotator.annotate( scene=image.copy(), key_points=key_points @@ -139,7 +142,10 @@ class EdgeAnnotator(BaseKeyPointAnnotator): image = ... key_points = sv.KeyPoints(...) - edge_annotator = sv.EdgeAnnotator(color=sv.Color.GREEN, thickness=5) + edge_annotator = sv.EdgeAnnotator( + color=sv.Color.GREEN, + thickness=5 + ) annotated_frame = edge_annotator.annotate( scene=image.copy(), key_points=key_points @@ -240,12 +246,19 @@ class VertexLabelAnnotator: image = ... key_points = sv.KeyPoints(...) - vertex_label_annotator = sv.VertexLabelAnnotator() + vertex_label_annotator = sv.VertexLabelAnnotator( + color=sv.Color.GREEN, + text_color=sv.Color.BLACK, + border_radius=5 + ) annotated_frame = vertex_label_annotator.annotate( scene=image.copy(), key_points=key_points ) ``` + + ![vertex-label-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/vertex-label-annotator-example.png) """ font = cv2.FONT_HERSHEY_SIMPLEX From e13c7dc22c66554d15bcdd9934b9a37b1847377c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 13 May 2024 12:31:34 +0000 Subject: [PATCH 12/13] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto?= =?UTF-8?q?=20format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/keypoint/annotators.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/keypoint/annotators.md b/docs/keypoint/annotators.md index e7adeb09..30a970ec 100644 --- a/docs/keypoint/annotators.md +++ b/docs/keypoint/annotators.md @@ -14,7 +14,7 @@ status: new key_points = sv.KeyPoints(...) vertex_annotator = sv.VertexAnnotator( - color=sv.Color.GREEN, + color=sv.Color.GREEN, radius=10 ) annotated_frame = vertex_annotator.annotate( @@ -38,7 +38,7 @@ status: new key_points = sv.KeyPoints(...) edge_annotator = sv.EdgeAnnotator( - color=sv.Color.GREEN, + color=sv.Color.GREEN, thickness=5 ) annotated_frame = edge_annotator.annotate( From 452e1f1ea46301688cd32de314821690e4d596d6 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 13 May 2024 15:21:25 +0200 Subject: [PATCH 13/13] more `VertexLabelAnnotator` docs --- supervision/keypoint/annotators.py | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/supervision/keypoint/annotators.py b/supervision/keypoint/annotators.py index b5723aa4..e6ff1fcf 100644 --- a/supervision/keypoint/annotators.py +++ b/supervision/keypoint/annotators.py @@ -259,6 +259,49 @@ class VertexLabelAnnotator: ![vertex-label-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/vertex-label-annotator-example.png) + + !!! tip + + `VertexLabelAnnotator` allows to customize the color of each keypoint label + values. + + Example: + ```python + import supervision as sv + + image = ... + key_points = sv.KeyPoints(...) + + LABELS = [ + "nose", "left eye", "right eye", "left ear", + "right ear", "left shoulder", "right shoulder", "left elbow", + "right elbow", "left wrist", "right wrist", "left hip", + "right hip", "left knee", "right knee", "left ankle", + "right ankle" + ] + + COLORS = [ + "#FF6347", "#FF6347", "#FF6347", "#FF6347", + "#FF6347", "#FF1493", "#00FF00", "#FF1493", + "#00FF00", "#FF1493", "#00FF00", "#FFD700", + "#00BFFF", "#FFD700", "#00BFFF", "#FFD700", + "#00BFFF" + ] + COLORS = [sv.Color.from_hex(color_hex=c) for c in COLORS] + + vertex_label_annotator = sv.VertexLabelAnnotator( + color=COLORS, + text_color=sv.Color.BLACK, + border_radius=5 + ) + annotated_frame = vertex_label_annotator.annotate( + scene=image.copy(), + key_points=key_points, + labels=labels + ) + ``` + ![vertex-label-annotator-custom-example](https://media.roboflow.com/ + supervision-annotator-examples/vertex-label-annotator-custom-example.png) """ font = cv2.FONT_HERSHEY_SIMPLEX