From 082f2481594e87da189dd3a77e950429dbf0ebed Mon Sep 17 00:00:00 2001 From: mario-dg Date: Mon, 9 Oct 2023 15:42:54 +0200 Subject: [PATCH 01/53] =?UTF-8?q?feat:=20=F0=9F=9A=80=20watermarking=20ima?= =?UTF-8?q?ges=20and=20videos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/draw/utils.py | 62 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 9d75690d..eb61f0ac 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -1,4 +1,5 @@ -from typing import Optional +from typing import Optional, Union +import os import cv2 import numpy as np @@ -168,3 +169,62 @@ def draw_text( lineType=cv2.LINE_AA, ) return scene + +def draw_image( + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect +) -> np.ndarray: + """ + Draws an image onto a given scene with specified opacity and dimensions. + + Args: + scene (np.ndarray): The background image onto which the image will be drawn. + image (Union[str, np.ndarray]): The image to be drawn. Can be either a file path or a NumPy array. + opacity (float): The opacity level of the image to be drawn, ranging from 0.0 to 1.0. + rect (Rect): A Rect object specifying the dimensions and position where the image will be drawn. + + Returns: + np.ndarray: The scene with the image drawn onto it. + + Example: + >>> scene = np.zeros((400, 400, 3), dtype=np.uint8) + >>> image_path = "path/to/image.jpg" + >>> opacity = 0.5 + >>> rect = Rect(x=50, y=50, width=200, height=200) + >>> new_scene = draw_image(scene, image_path, opacity, rect) + """ + if isinstance(image, str): + assert os.path.exists(image), f'The specified path ("{image}") does not exist.' + image = cv2.imread(image, cv2.IMREAD_UNCHANGED) + + assert 0.0 <= opacity <= 1.0, "The opacity has to be between 0.0 and 1.0." + + assert ( + rect.x >= 0 and rect.y >= 0 + ), "The top left coordinates of the rectangle have to be positive." + assert ( + rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= scene.shape[0] + ), "The image you are trying to draw exceeds the bounds of the scene." + + image = cv2.resize(image, (rect.width, rect.height)) + + # watermark with transparent background + if image.shape[2] == 4: + b, g, r, a = cv2.split(image) + b = cv2.bitwise_and(b, b, mask=a) + g = cv2.bitwise_and(g, g, mask=a) + r = cv2.bitwise_and(r, r, mask=a) + image = cv2.merge([b, g, r, a]) + del b, g, r, a # immediately free up memory + + if scene.shape[2] == 3: + scene = np.dstack([scene, np.ones(scene.shape[:2], dtype=np.uint8) * 255]) + + scene_h, scene_w, channels = scene.shape[:3] + water_h, water_w = image.shape[:2] + + overlay = np.zeros((scene_h, scene_w, channels), dtype="uint8") + overlay[rect.y : rect.y + water_h, rect.x : rect.x + water_w] = image + + cv2.addWeighted(overlay, opacity, scene, 1.0, 0, scene) + + return scene[:, :, :3] \ No newline at end of file From 6a0482ded5d2005484b4d116fc228155f50ab228 Mon Sep 17 00:00:00 2001 From: Mario da Graca Date: Tue, 10 Oct 2023 08:24:29 +0200 Subject: [PATCH 02/53] Fixed pre-commit issues --- supervision/draw/utils.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index eb61f0ac..73844fbd 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -1,5 +1,5 @@ -from typing import Optional, Union import os +from typing import Optional, Union import cv2 import numpy as np @@ -170,6 +170,7 @@ def draw_text( ) return scene + def draw_image( scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: @@ -178,9 +179,12 @@ def draw_image( Args: scene (np.ndarray): The background image onto which the image will be drawn. - image (Union[str, np.ndarray]): The image to be drawn. Can be either a file path or a NumPy array. - opacity (float): The opacity level of the image to be drawn, ranging from 0.0 to 1.0. - rect (Rect): A Rect object specifying the dimensions and position where the image will be drawn. + image (Union[str, np.ndarray]): The image to be drawn. + Can be either a file path or a NumPy array. + opacity (float): The opacity level of the image to be drawn, + ranging from 0.0 to 1.0. + rect (Rect): A Rect object specifying the dimensions and + position where the image will be drawn. Returns: np.ndarray: The scene with the image drawn onto it. @@ -227,4 +231,4 @@ def draw_image( cv2.addWeighted(overlay, opacity, scene, 1.0, 0, scene) - return scene[:, :, :3] \ No newline at end of file + return scene[:, :, :3] From c51159b598c9490d8e288fdb9ef6e13c4f8e7c04 Mon Sep 17 00:00:00 2001 From: kapter Date: Thu, 12 Oct 2023 23:44:26 +0300 Subject: [PATCH 03/53] added HeatmapAnnotator --- supervision/annotators/core.py | 108 +++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 8edca92b..ae61d27c 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -84,6 +84,114 @@ class BoundingBoxAnnotator(BaseAnnotator): ) return scene +class HeatmapAnnotator: + """ + A class for drawing heatmap on an image using provided detections. + Heat is accumulated over time. Drawn as a semi-transparent overlay as blured circles. + """ + def __init__( + self, + position: Optional[Position] = Position.BOTTOM_CENTER, + opacity: float = 0.2, + radius: int = 40, + kernel_size: Optional[int] = 25, + + ): + """ + Args: + position (Optional[Position]): The position of the heatmap. + Defaults to `BOTTOM_CENTER`. + opacity (float): Opacity of the overlay mask. Must be between `0` and `1`. + radius (int): Radius of the heat circle. + kernel_size (Optional[int]): Kernel size for blurring the heatmap. + """ + self.position = position + self.opacity = opacity + self.radius = radius + self.kernel_size = kernel_size + self.heatmask = None + + + def get_xy(self, xyxy: Tuple[int, int, int, int],position: Optional[Position]) -> Tuple[int, int, int, int]: + """ + Returns the xy coordinates of the heatmap based on the provided position. + """ + if (position is None) or (position == Position.TOP_LEFT): + return xyxy[0], xyxy[1] + elif position == Position.TOP_CENTER: + return int((xyxy[0]+xyxy[2])/2), int(xyxy[1]) + elif position == Position.TOP_RIGHT: + return int(xyxy[2]), int(xyxy[1]) + elif position == Position.CENTER_LEFT: + return int(xyxy[0]), int((xyxy[1]+xyxy[3])/2) + elif position == Position.CENTER: + return int((xyxy[0]+xyxy[2])/2), int((xyxy[1]+xyxy[3])/2) + elif position == Position.CENTER_RIGHT: + return int(xyxy[2]), int((xyxy[1]+xyxy[3])/2) + elif position == Position.BOTTOM_LEFT: + return int(xyxy[0]), int(xyxy[3]) + elif position == Position.BOTTOM_CENTER: + return (int((xyxy[0]+xyxy[2])/2), int(xyxy[3])) + elif position == Position.BOTTOM_RIGHT: + return int(xyxy[2]), int(xyxy[3]) + + def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: + """ + Annotates the given scene with heatmap based on the provided detections. + + Args: + scene (np.ndarray): The image where heatmap will be drawn. + detections (Detections): Object detections to annotate. + + Returns: + np.ndarray: The annotated image. + + Example: + ```python + >>> import supervision as sv + >>> model = YOLO('yolov8s.pt') + >>> video_info = sv.VideoInfo.from_video_path(video_path=video_path) + >>> hma = HeatmapAnnotator( + ... position=Position.BOTTOM_CENTER, + ... opacity=0.2, + ... radius=40, + ... kernel_size=25, + ...) + >>> with sv.VideoSink(target_path=target_path, video_info=video_info) as sink: + ... for result in tqdm(model(source=video_path, agnostic_nms=True, verbose=False), total=video_info.total_frames): + ... frame = result.orig_img + ... detections = sv.Detections.from_ultralytics(result) + ... detections = detections[detections.class_id == 0] + ... annotated_frame = hma.annotate( + ... scene=frame.copy(), + ... detections=detections) + ... sink.write_frame(frame=annotated_frame) + ``` + + ![heatmap-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/heatmap-annotator-example.png) + """ + + if self.heatmask is None: + self.heatmask = np.zeros(scene.shape[:2]) + mask = np.zeros(scene.shape[:2]) + for xyxy,_,_,_,_ in detections: + cv2.circle(mask, self.get_xy(xyxy,self.position), self.radius, 1, -1) + self.heatmask = mask+self.heatmask + temp = self.heatmask.copy() + temp = 100-temp/temp.max()*90 + temp = temp.astype(np.uint8) + if self.kernel_size is not None: + temp = cv2.GaussianBlur(temp,(self.kernel_size,self.kernel_size),0) + hsv = np.zeros(scene.shape) + hsv[...,0] = temp + hsv[...,1] = 255 + hsv[...,2] = 255 + mask = temp>0 + temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) + scene[mask] = cv2.addWeighted( temp, self.opacity,scene, 1-self.opacity, 0)[mask] + return scene + class MaskAnnotator(BaseAnnotator): """ From ae00a9d65f562ad1b96245dcf3abe0e2fffe2c5c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 12 Oct 2023 20:48:19 +0000 Subject: [PATCH 04/53] =?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/annotators/core.py | 46 ++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index ae61d27c..e8fe785a 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -84,18 +84,19 @@ class BoundingBoxAnnotator(BaseAnnotator): ) return scene + class HeatmapAnnotator: """ A class for drawing heatmap on an image using provided detections. Heat is accumulated over time. Drawn as a semi-transparent overlay as blured circles. """ + def __init__( self, position: Optional[Position] = Position.BOTTOM_CENTER, opacity: float = 0.2, radius: int = 40, - kernel_size: Optional[int] = 25, - + kernel_size: Optional[int] = 25, ): """ Args: @@ -110,28 +111,29 @@ class HeatmapAnnotator: self.radius = radius self.kernel_size = kernel_size self.heatmask = None - - def get_xy(self, xyxy: Tuple[int, int, int, int],position: Optional[Position]) -> Tuple[int, int, int, int]: + def get_xy( + self, xyxy: Tuple[int, int, int, int], position: Optional[Position] + ) -> Tuple[int, int, int, int]: """ Returns the xy coordinates of the heatmap based on the provided position. """ if (position is None) or (position == Position.TOP_LEFT): return xyxy[0], xyxy[1] elif position == Position.TOP_CENTER: - return int((xyxy[0]+xyxy[2])/2), int(xyxy[1]) + return int((xyxy[0] + xyxy[2]) / 2), int(xyxy[1]) elif position == Position.TOP_RIGHT: return int(xyxy[2]), int(xyxy[1]) elif position == Position.CENTER_LEFT: - return int(xyxy[0]), int((xyxy[1]+xyxy[3])/2) + return int(xyxy[0]), int((xyxy[1] + xyxy[3]) / 2) elif position == Position.CENTER: - return int((xyxy[0]+xyxy[2])/2), int((xyxy[1]+xyxy[3])/2) + return int((xyxy[0] + xyxy[2]) / 2), int((xyxy[1] + xyxy[3]) / 2) elif position == Position.CENTER_RIGHT: - return int(xyxy[2]), int((xyxy[1]+xyxy[3])/2) + return int(xyxy[2]), int((xyxy[1] + xyxy[3]) / 2) elif position == Position.BOTTOM_LEFT: return int(xyxy[0]), int(xyxy[3]) elif position == Position.BOTTOM_CENTER: - return (int((xyxy[0]+xyxy[2])/2), int(xyxy[3])) + return (int((xyxy[0] + xyxy[2]) / 2), int(xyxy[3])) elif position == Position.BOTTOM_RIGHT: return int(xyxy[2]), int(xyxy[3]) @@ -142,7 +144,7 @@ class HeatmapAnnotator: Args: scene (np.ndarray): The image where heatmap will be drawn. detections (Detections): Object detections to annotate. - + Returns: np.ndarray: The annotated image. @@ -175,23 +177,25 @@ class HeatmapAnnotator: if self.heatmask is None: self.heatmask = np.zeros(scene.shape[:2]) mask = np.zeros(scene.shape[:2]) - for xyxy,_,_,_,_ in detections: - cv2.circle(mask, self.get_xy(xyxy,self.position), self.radius, 1, -1) - self.heatmask = mask+self.heatmask + for xyxy, _, _, _, _ in detections: + cv2.circle(mask, self.get_xy(xyxy, self.position), self.radius, 1, -1) + self.heatmask = mask + self.heatmask temp = self.heatmask.copy() - temp = 100-temp/temp.max()*90 + temp = 100 - temp / temp.max() * 90 temp = temp.astype(np.uint8) if self.kernel_size is not None: - temp = cv2.GaussianBlur(temp,(self.kernel_size,self.kernel_size),0) + temp = cv2.GaussianBlur(temp, (self.kernel_size, self.kernel_size), 0) hsv = np.zeros(scene.shape) - hsv[...,0] = temp - hsv[...,1] = 255 - hsv[...,2] = 255 - mask = temp>0 + hsv[..., 0] = temp + hsv[..., 1] = 255 + hsv[..., 2] = 255 + mask = temp > 0 temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) - scene[mask] = cv2.addWeighted( temp, self.opacity,scene, 1-self.opacity, 0)[mask] + scene[mask] = cv2.addWeighted(temp, self.opacity, scene, 1 - self.opacity, 0)[ + mask + ] return scene - + class MaskAnnotator(BaseAnnotator): """ From 1324cda60080884d8c867dd44288aca285f5a250 Mon Sep 17 00:00:00 2001 From: kapter Date: Fri, 13 Oct 2023 16:09:24 +0300 Subject: [PATCH 05/53] unnecessary function(get_xy) removed --- supervision/annotators/core.py | 29 ++--------------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index e8fe785a..072e1026 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -112,31 +112,6 @@ class HeatmapAnnotator: self.kernel_size = kernel_size self.heatmask = None - def get_xy( - self, xyxy: Tuple[int, int, int, int], position: Optional[Position] - ) -> Tuple[int, int, int, int]: - """ - Returns the xy coordinates of the heatmap based on the provided position. - """ - if (position is None) or (position == Position.TOP_LEFT): - return xyxy[0], xyxy[1] - elif position == Position.TOP_CENTER: - return int((xyxy[0] + xyxy[2]) / 2), int(xyxy[1]) - elif position == Position.TOP_RIGHT: - return int(xyxy[2]), int(xyxy[1]) - elif position == Position.CENTER_LEFT: - return int(xyxy[0]), int((xyxy[1] + xyxy[3]) / 2) - elif position == Position.CENTER: - return int((xyxy[0] + xyxy[2]) / 2), int((xyxy[1] + xyxy[3]) / 2) - elif position == Position.CENTER_RIGHT: - return int(xyxy[2]), int((xyxy[1] + xyxy[3]) / 2) - elif position == Position.BOTTOM_LEFT: - return int(xyxy[0]), int(xyxy[3]) - elif position == Position.BOTTOM_CENTER: - return (int((xyxy[0] + xyxy[2]) / 2), int(xyxy[3])) - elif position == Position.BOTTOM_RIGHT: - return int(xyxy[2]), int(xyxy[3]) - def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: """ Annotates the given scene with heatmap based on the provided detections. @@ -177,8 +152,8 @@ class HeatmapAnnotator: if self.heatmask is None: self.heatmask = np.zeros(scene.shape[:2]) mask = np.zeros(scene.shape[:2]) - for xyxy, _, _, _, _ in detections: - cv2.circle(mask, self.get_xy(xyxy, self.position), self.radius, 1, -1) + for xy in detections.get_anchor_coordinates(self.position): + cv2.circle(mask, (int(xy[0]), int(xy[1])), self.radius, 1, -1) self.heatmask = mask + self.heatmask temp = self.heatmask.copy() temp = 100 - temp / temp.max() * 90 From 4baf570b288ebe02c98bd40237d0788aa7362048 Mon Sep 17 00:00:00 2001 From: Onuralp SEZER Date: Sat, 14 Oct 2023 01:12:16 +0300 Subject: [PATCH 06/53] =?UTF-8?q?docs(fix):=20=F0=9F=93=93=20poetry=20env?= =?UTF-8?q?=20typo=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 3019901f..ae3a425a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -63,7 +63,7 @@ You can install `supervision` with pip in a cd supervision # setup python environment and activate it - poetry env use python 3.10 + poetry env use python3.10 poetry shell # headless install From 338c589032336ff51a93096182a5405d992f2598 Mon Sep 17 00:00:00 2001 From: abhishek7kalra Date: Sun, 15 Oct 2023 17:42:40 +0530 Subject: [PATCH 07/53] LineZone.trigger update to return info --- supervision/detection/line_counter.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/supervision/detection/line_counter.py b/supervision/detection/line_counter.py index ea97fcb8..db86e3f9 100644 --- a/supervision/detection/line_counter.py +++ b/supervision/detection/line_counter.py @@ -26,6 +26,7 @@ class LineZone: self.tracker_state: Dict[str, bool] = {} self.in_count: int = 0 self.out_count: int = 0 + self.crossed = [] def trigger(self, detections: Detections): """ @@ -33,9 +34,14 @@ class LineZone: Attributes: detections (Detections): The detections for which to update the counts. - + + Returns: + np.ndarray: A boolean array indicating + which detection has crossed the line on the either sides """ - for xyxy, _, confidence, class_id, tracker_id in detections: + self.crossed = [False] * len(detections) + + for i, (xyxy, _, confidence, class_id, tracker_id) in enumerate(detections): # handle detections with no tracker_id if tracker_id is None: continue @@ -67,8 +73,13 @@ class LineZone: self.tracker_state[tracker_id] = tracker_state if tracker_state: self.in_count += 1 + self.crossed[i] = True + else: self.out_count += 1 + self.crossed[i] = True + + return self.crossed class LineZoneAnnotator: From bf725ef0f72699079152d3630a5f27c6acf27311 Mon Sep 17 00:00:00 2001 From: abhishek7kalra Date: Sun, 15 Oct 2023 18:10:54 +0530 Subject: [PATCH 08/53] fix pre-commit --- supervision/detection/line_counter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/detection/line_counter.py b/supervision/detection/line_counter.py index db86e3f9..1c1fe770 100644 --- a/supervision/detection/line_counter.py +++ b/supervision/detection/line_counter.py @@ -34,7 +34,7 @@ class LineZone: Attributes: detections (Detections): The detections for which to update the counts. - + Returns: np.ndarray: A boolean array indicating which detection has crossed the line on the either sides From fe8a8260dcdf1181d28c0de4d748c3c557c08a90 Mon Sep 17 00:00:00 2001 From: abhishek7kalra Date: Sun, 15 Oct 2023 19:06:18 +0530 Subject: [PATCH 09/53] change return type from list to nparray --- supervision/detection/line_counter.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/supervision/detection/line_counter.py b/supervision/detection/line_counter.py index 1c1fe770..c668354e 100644 --- a/supervision/detection/line_counter.py +++ b/supervision/detection/line_counter.py @@ -26,9 +26,8 @@ class LineZone: self.tracker_state: Dict[str, bool] = {} self.in_count: int = 0 self.out_count: int = 0 - self.crossed = [] - def trigger(self, detections: Detections): + def trigger(self, detections: Detections) -> np.ndarray: """ Update the in_count and out_count for the detections that cross the line. @@ -39,7 +38,7 @@ class LineZone: np.ndarray: A boolean array indicating which detection has crossed the line on the either sides """ - self.crossed = [False] * len(detections) + crossed = np.full(len(detections), False) for i, (xyxy, _, confidence, class_id, tracker_id) in enumerate(detections): # handle detections with no tracker_id @@ -73,13 +72,13 @@ class LineZone: self.tracker_state[tracker_id] = tracker_state if tracker_state: self.in_count += 1 - self.crossed[i] = True + crossed[i] = True else: self.out_count += 1 - self.crossed[i] = True + crossed[i] = True - return self.crossed + return crossed class LineZoneAnnotator: From 75db51aa908d94f0befcbfc3c69605c3543b78ae Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Mon, 16 Oct 2023 09:00:12 +0100 Subject: [PATCH 10/53] add 404 page --- custom_theme/404.html | 7 +++++++ mkdocs.yml | 1 + 2 files changed, 8 insertions(+) create mode 100644 custom_theme/404.html diff --git a/custom_theme/404.html b/custom_theme/404.html new file mode 100644 index 00000000..81639b40 --- /dev/null +++ b/custom_theme/404.html @@ -0,0 +1,7 @@ +{% extends "main.html" %} + +{% block content %} +

Page Not Found

+

The page you have requested was not found.

+

Go back to the documentation home.

+{% endblock %} \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 6528b238..e3816bd8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -76,6 +76,7 @@ theme: font: text: Roboto code: Roboto Mono + custom_dir: 'custom_theme' plugins: - mkdocstrings From 3d843d710dbf8154214d71ed9cf0c17fcc00f1b7 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Oct 2023 08:04:16 +0000 Subject: [PATCH 11/53] =?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 --- custom_theme/404.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/custom_theme/404.html b/custom_theme/404.html index 81639b40..4ce71946 100644 --- a/custom_theme/404.html +++ b/custom_theme/404.html @@ -1,7 +1,7 @@ -{% extends "main.html" %} +{% extends "main.html" %} {% block content %} -

Page Not Found

+

Page Not Found

The page you have requested was not found.

Go back to the documentation home.

-{% endblock %} \ No newline at end of file +{% endblock %} From 1ab50cdb3c21661923a00f875f40c137acec59b7 Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Mon, 16 Oct 2023 13:06:43 +0100 Subject: [PATCH 12/53] add / to mkdocs site_url --- mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mkdocs.yml b/mkdocs.yml index e3816bd8..542a7ad5 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,5 +1,5 @@ site_name: Supervision -site_url: https://roboflow.github.io/supervision +site_url: https://roboflow.github.io/supervision/ site_author: Roboflow site_description: A set of easy-to-use utils that will come in handy in any Computer Vision project repo_name: roboflow/supervision From eda6909c91ccc53588095f48d34616bc1467d344 Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Mon, 16 Oct 2023 13:10:52 +0100 Subject: [PATCH 13/53] change domain to supervision.roboflow.com in mkdocs --- mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mkdocs.yml b/mkdocs.yml index 542a7ad5..276c85dc 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,5 +1,5 @@ site_name: Supervision -site_url: https://roboflow.github.io/supervision/ +site_url: https://supervision.roboflow.com/ site_author: Roboflow site_description: A set of easy-to-use utils that will come in handy in any Computer Vision project repo_name: roboflow/supervision From b2e9a668b2c9ae74b0e62926b4948f16506fd3c8 Mon Sep 17 00:00:00 2001 From: PankajKrana Date: Tue, 17 Oct 2023 01:48:54 +0530 Subject: [PATCH 14/53] Create sv.DotMarkerAnnotator #396 --- .../annotators/dot_marker_annotator.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 supervision/annotators/dot_marker_annotator.py diff --git a/supervision/annotators/dot_marker_annotator.py b/supervision/annotators/dot_marker_annotator.py new file mode 100644 index 00000000..4f931b5f --- /dev/null +++ b/supervision/annotators/dot_marker_annotator.py @@ -0,0 +1,46 @@ +from typing import Union +import numpy as np +import cv2 +from supervision import Color, ColorPalette, Position, Detections +from supervision.annotators.base import BaseAnnotator + + + +class DotMarkerAnnotator(BaseAnnotator): + def __init__( + self, + color: Union[Color, ColorPalette] = ColorPalette.default(), + radius: int = 4, + position: Position = Position.CENTER, + color_map: str = "class", + ): + self.color = color + self.radius = radius + self.position = position + self.color_map = color_map + + def annotate( + self, + scene: np.ndarray, + detections: Detections, + ) -> np.ndarray: + annotated_scene = scene.copy() + + for detection in detections: + dot_color = self._get_color(detection) + box_position = detection.bounding_box.get_position(self.position) + dot_position = (int(box_position[0]), int(box_position[1])) + cv2.circle(annotated_scene, dot_position, self.radius, dot_color, -1) + + return annotated_scene + + def _get_color(self, detection): + if self.color_map == "class": + return self.color[detection.class_id] + elif self.color_map == "index": + return self.color[detection.index % len(self.color)] + elif self.color_map == "track": + return self.color[detection.track_id % len(self.color)] + else: + raise ValueError("Invalid color mapping strategy") + From 72a780b74acd35ac5179f57ae95ac5c81e414097 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Oct 2023 21:06:21 +0000 Subject: [PATCH 15/53] Bump urllib3 from 2.0.6 to 2.0.7 Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.0.6 to 2.0.7. - [Release notes](https://github.com/urllib3/urllib3/releases) - [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst) - [Commits](https://github.com/urllib3/urllib3/compare/2.0.6...2.0.7) --- updated-dependencies: - dependency-name: urllib3 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- poetry.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/poetry.lock b/poetry.lock index e8f92e94..7065eb8b 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3358,13 +3358,13 @@ dev = ["flake8", "flake8-annotations", "flake8-bandit", "flake8-bugbear", "flake [[package]] name = "urllib3" -version = "2.0.6" +version = "2.0.7" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false python-versions = ">=3.7" files = [ - {file = "urllib3-2.0.6-py3-none-any.whl", hash = "sha256:7a7c7003b000adf9e7ca2a377c9688bbc54ed41b985789ed576570342a375cd2"}, - {file = "urllib3-2.0.6.tar.gz", hash = "sha256:b19e1a85d206b56d7df1d5e683df4a7725252a964e3993648dd0fb5a1c157564"}, + {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"}, + {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"}, ] [package.extras] From db4afe98854e24fe646d9a35d1f8cbe7fa4a8843 Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Wed, 18 Oct 2023 10:20:42 +0100 Subject: [PATCH 16/53] add how to detect and annotate guide --- docs/how_to/detect_and_annotate.md | 64 +++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index c9497945..987b311e 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -1 +1,63 @@ -🚧 Page under construction. +## How to Detect and Annotate + +Supervision enables you to annotate predictions from object detection and segmentation models in a few lines of code. + +The `sv.BoxAnnotator()` class lets you annotate images with bounding boxes, while the `sv.MaskAnnotator()` class lets you annotate images with segmentation masks. `sv.MaskAnnotator()` is a drop-in replacement for `sv.BoxAnnotator()`, so you don't need to update any other code if you want to switch between the two. + +In this guide, we run inference on an Ultralytics YOLOv8 object detection model and plot the predictions with the `sv.BoxAnnotator()` class. + +## Load a Model and Retrieve Predictions + +First, we need to retrieve predictions from a model. For this guide, we will retrieve predictions from a YOLOv8 model. See a list of all models from which you can load predictions into supervision. + +```python +import supervision as sv +from ultralytics import YOLO +import cv2 + +model = YOLO("yolov8n.pt") + +results = model("image.jpg") +``` + +In this code, we import `supervision`, `ultralytics`, and `cv2` (OpenCV). We then load a YOLOv8 object detection model, then run inference on an image called `image.jpg`. The `results` variable contains the predictions from the model. + +## Load Predictions into Supervision + +Now that we have predictions from a model, we can load them into supervision. + +We can do so using the `sv.Detections.from_ultralytics()` method, which accepts model results from Ultralytics models. See a list of other supported data loaders. + +```python +detections = sv.Detections.from_ultralytics(results) +``` + +## Annotate Image + +Next, we can annotate the image with the predictions returned by our model. Since we are working with an object detection model, we will use the `sv.BoxAnnotator()` class to annotate an image with predictions. + +```python +image = cv2.imread("image.jpg") + +annotator = sv.BoxAnnotator() + +annotated_image = annotator.annotate(image, detections) +``` + +In this code, we: + +1. Load the image to annotate. +2. Create a `sv.BoxAnnotator()` object to annotate the image. +3. Use the `annotate()` method to annotate the image with the predictions. + +## Display Annotated Image + +Finally, we can display the annotated image: + +```python +sv.plot_image(annotated_image) +``` + +Here is the result: + +![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate.png) \ No newline at end of file From 1ddb78b662feb760a60b24bb7a9520328021155b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 09:22:43 +0000 Subject: [PATCH 17/53] =?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/how_to/detect_and_annotate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index 987b311e..a84f5e0e 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -60,4 +60,4 @@ sv.plot_image(annotated_image) Here is the result: -![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate.png) \ No newline at end of file +![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate.png) From a7449ba56fb99a91d7bd6b78c3b3465f61b1910e Mon Sep 17 00:00:00 2001 From: Piotr Skalski Date: Wed, 18 Oct 2023 12:42:26 +0200 Subject: [PATCH 18/53] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index ffb88e98..78d8fbf0 100644 --- a/README.md +++ b/README.md @@ -364,5 +364,4 @@ We love your input! Please see our [contributing guide](https://github.com/robof - From a5a853e1415244e3d9f9d684cc9ab1b9af246674 Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Wed, 18 Oct 2023 13:11:29 +0100 Subject: [PATCH 19/53] resolve conflict --- docs/how_to/detect_and_annotate.md | 36 +++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index a84f5e0e..891e18df 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -2,9 +2,18 @@ Supervision enables you to annotate predictions from object detection and segmentation models in a few lines of code. -The `sv.BoxAnnotator()` class lets you annotate images with bounding boxes, while the `sv.MaskAnnotator()` class lets you annotate images with segmentation masks. `sv.MaskAnnotator()` is a drop-in replacement for `sv.BoxAnnotator()`, so you don't need to update any other code if you want to switch between the two. +The `sv.BoxAnnotator` class lets you annotate images with bounding boxes, while the `sv.MaskAnnotator` class lets you annotate images with segmentation masks. `sv.MaskAnnotator` is a drop-in replacement for `sv.BoxAnnotator`, so you don't need to update any other code if you want to switch between the two. -In this guide, we run inference on an Ultralytics YOLOv8 object detection model and plot the predictions with the `sv.BoxAnnotator()` class. +In this guide, we run inference on an Ultralytics YOLOv8 object detection model and plot the predictions with the `sv.BoxAnnotator` class. You can also load predictions using: + +- `from_deepsparse` (Deepsparse) +- `from_detectron2` (Detectron2) +- `from_mmdetection` (MMDetection) +- `from_ultralytics` (Ultralytics) +- `from_roboflow` (Roboflow) +- `from_sam` (Segment Anything Model) +- `from_transformers` (Hugging Face Transformers) +- `from_yolo_nas` (YOLO-NAS) ## Load a Model and Retrieve Predictions @@ -20,35 +29,42 @@ model = YOLO("yolov8n.pt") results = model("image.jpg") ``` -In this code, we import `supervision`, `ultralytics`, and `cv2` (OpenCV). We then load a YOLOv8 object detection model, then run inference on an image called `image.jpg`. The `results` variable contains the predictions from the model. +In this code, we import `supervision`, `ultralytics`, and `cv2` (OpenCV). We load then load a YOLOv8 object detection model, then run inference on an image called `image.jpg`. The image is loaded using OpenCV. The `results` variable contains the predictions from the model. ## Load Predictions into Supervision Now that we have predictions from a model, we can load them into supervision. -We can do so using the `sv.Detections.from_ultralytics()` method, which accepts model results from Ultralytics models. See a list of other supported data loaders. +We can do so using the `sv.Detections.from_ultralytics` method, which accepts model results from Ultralytics models. See a list of other supported data loaders. ```python -detections = sv.Detections.from_ultralytics(results) +detections = sv.Detections.from_ultralytics(results[0]) ``` ## Annotate Image -Next, we can annotate the image with the predictions returned by our model. Since we are working with an object detection model, we will use the `sv.BoxAnnotator()` class to annotate an image with predictions. +Next, we can annotate the image with the predictions returned by our model. Since we are working with an object detection model, we will use the `sv.BoxAnnotator` class to annotate an image with predictions. ```python image = cv2.imread("image.jpg") annotator = sv.BoxAnnotator() -annotated_image = annotator.annotate(image, detections) +labels = [ + results.names[class_id] + for class_id + in detections.class_id +] + +annotated_image = annotator.annotate(image, detections, labels) ``` In this code, we: 1. Load the image to annotate. -2. Create a `sv.BoxAnnotator()` object to annotate the image. -3. Use the `annotate()` method to annotate the image with the predictions. +2. Create a `sv.BoxAnnotator` object to annotate the image. +3. Create a list of labels for each prediction. In this example, we get the class name associated with each class ID using the `results[0].names` attribute available in the `results` object` +3. Use the `annotate` method to annotate the image with the predictions. ## Display Annotated Image @@ -60,4 +76,4 @@ sv.plot_image(annotated_image) Here is the result: -![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate.png) +![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate_example.png) From 8dcfb427511f800e67948fa7941d35a3a6311542 Mon Sep 17 00:00:00 2001 From: James Gallagher Date: Wed, 18 Oct 2023 13:13:09 +0100 Subject: [PATCH 20/53] add data loader link --- docs/how_to/detect_and_annotate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index 891e18df..7c121fa2 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -35,7 +35,7 @@ In this code, we import `supervision`, `ultralytics`, and `cv2` (OpenCV). We loa Now that we have predictions from a model, we can load them into supervision. -We can do so using the `sv.Detections.from_ultralytics` method, which accepts model results from Ultralytics models. See a list of other supported data loaders. +We can do so using the `sv.Detections.from_ultralytics` method, which accepts model results from Ultralytics models. [See a list of other supported data loaders](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_deepsparse). ```python detections = sv.Detections.from_ultralytics(results[0]) From 00e209744fc89e0f9a235da333bd578dd5c47d5c Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 14:42:59 +0200 Subject: [PATCH 21/53] Add documentation and improvements to "LineZone" functionality Descriptions for various attributes and functionalities have been added into LineZone class to aid developers in understanding their behaviour. Also, the trigger function was modified to return two separate boolean arrays - 'crossed_in' and 'crossed_out' to denote objects crossing the line in specific directions. Moreover, Line Zone documentation is added to the side navigation in mkdocs.yml. --- docs/detection/tools/line_zone.md | 3 ++ mkdocs.yml | 1 + supervision/detection/line_counter.py | 53 ++++++++++++++++----------- 3 files changed, 35 insertions(+), 22 deletions(-) create mode 100644 docs/detection/tools/line_zone.md diff --git a/docs/detection/tools/line_zone.md b/docs/detection/tools/line_zone.md new file mode 100644 index 00000000..3e15a00e --- /dev/null +++ b/docs/detection/tools/line_zone.md @@ -0,0 +1,3 @@ +## LineZone + +:::supervision.detection.line_counter.LineZone \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 276c85dc..f511cb2f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -39,6 +39,7 @@ nav: - Core: detection/core.md - Utils: detection/utils.md - Tools: + - Line Zone: detection/tools/line_zone.md - Polygon Zone: detection/tools/polygon_zone.md - Inference Slicer: detection/tools/inference_slicer.md - Annotators: annotators.md diff --git a/supervision/detection/line_counter.py b/supervision/detection/line_counter.py index c668354e..851d1d4a 100644 --- a/supervision/detection/line_counter.py +++ b/supervision/detection/line_counter.py @@ -1,4 +1,4 @@ -from typing import Dict, Optional +from typing import Dict, Optional, Tuple import cv2 import numpy as np @@ -10,42 +10,54 @@ from supervision.geometry.core import Point, Rect, Vector class LineZone: """ - Count the number of objects that cross a line. + This class is responsible for counting the number of objects that cross a + predefined line. + + !!! warning + + LineZone utilizes the `tracker_id`. Read + [here](https://supervision.roboflow.com/trackers/) to learn how to plug + tracking into your inference pipeline. + + Attributes: + in_count (int): The number of objects that have crossed the line from outside + to inside. + out_count (int): The number of objects that have crossed the line from inside + to outside. """ def __init__(self, start: Point, end: Point): """ - Initialize a LineCounter object. - - Attributes: + Args: start (Point): The starting point of the line. end (Point): The ending point of the line. - """ self.vector = Vector(start=start, end=end) self.tracker_state: Dict[str, bool] = {} self.in_count: int = 0 self.out_count: int = 0 - def trigger(self, detections: Detections) -> np.ndarray: + def trigger(self, detections: Detections) -> Tuple[np.ndarray, np.ndarray]: """ - Update the in_count and out_count for the detections that cross the line. + Update the `in_count` and `out_count` based on the objects that cross the line. - Attributes: - detections (Detections): The detections for which to update the counts. + Args: + detections (Detections): A list of detections for which to update the + counts. Returns: - np.ndarray: A boolean array indicating - which detection has crossed the line on the either sides + A tuple of two boolean NumPy arrays. The first array indicates which + detections have crossed the line from outside to inside. The second + array indicates which detections have crossed the line from inside to + outside. """ - crossed = np.full(len(detections), False) + crossed_in = np.full(len(detections), False) + crossed_out = np.full(len(detections), False) for i, (xyxy, _, confidence, class_id, tracker_id) in enumerate(detections): - # handle detections with no tracker_id if tracker_id is None: continue - # we check if all four anchors of bbox are on the same side of vector x1, y1, x2, y2 = xyxy anchors = [ Point(x=x1, y=y1), @@ -55,30 +67,27 @@ class LineZone: ] triggers = [self.vector.is_in(point=anchor) for anchor in anchors] - # detection is partially in and partially out if len(set(triggers)) == 2: continue tracker_state = triggers[0] - # handle new detection + if tracker_id not in self.tracker_state: self.tracker_state[tracker_id] = tracker_state continue - # handle detection on the same side of the line if self.tracker_state.get(tracker_id) == tracker_state: continue self.tracker_state[tracker_id] = tracker_state if tracker_state: self.in_count += 1 - crossed[i] = True - + crossed_in[i] = True else: self.out_count += 1 - crossed[i] = True + crossed_out[i] = True - return crossed + return crossed_in, crossed_out class LineZoneAnnotator: From 62c45548a63bdf47165fa017fd59b36f620f5e6b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 12:44:19 +0000 Subject: [PATCH 22/53] =?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/detection/tools/line_zone.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/detection/tools/line_zone.md b/docs/detection/tools/line_zone.md index 3e15a00e..cbecdaa9 100644 --- a/docs/detection/tools/line_zone.md +++ b/docs/detection/tools/line_zone.md @@ -1,3 +1,3 @@ ## LineZone -:::supervision.detection.line_counter.LineZone \ No newline at end of file +:::supervision.detection.line_counter.LineZone From 61809f9329c40a4d2941c532f397cb6317d0ee2b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 13:53:25 +0000 Subject: [PATCH 23/53] =?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/annotators/dot_marker_annotator.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/supervision/annotators/dot_marker_annotator.py b/supervision/annotators/dot_marker_annotator.py index 4f931b5f..ecdb9af0 100644 --- a/supervision/annotators/dot_marker_annotator.py +++ b/supervision/annotators/dot_marker_annotator.py @@ -1,9 +1,10 @@ from typing import Union -import numpy as np -import cv2 -from supervision import Color, ColorPalette, Position, Detections -from supervision.annotators.base import BaseAnnotator +import cv2 +import numpy as np + +from supervision import Color, ColorPalette, Detections, Position +from supervision.annotators.base import BaseAnnotator class DotMarkerAnnotator(BaseAnnotator): @@ -43,4 +44,3 @@ class DotMarkerAnnotator(BaseAnnotator): return self.color[detection.track_id % len(self.color)] else: raise ValueError("Invalid color mapping strategy") - From fabfe0783aad29a6fa6475016075ebe05772a354 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 18:09:13 +0200 Subject: [PATCH 24/53] Refactor DotMarkerAnnotator and merge into core annotators The DotMarkerAnnotator class has been refactored and named DotAnnotator for simplicity. It's now part of the core annotators to conform with the project structure. The color lookup on the DotAnnotator now uses the 'color_lookup' parameter, allowing for more flexibility and customization in the colors used for the annotations. All the changes aim to standardize the way different annotators are organized and make color customization easier. --- supervision/__init__.py | 1 + supervision/annotators/core.py | 33 +++++++++++++ .../annotators/dot_marker_annotator.py | 46 ------------------- 3 files changed, 34 insertions(+), 46 deletions(-) delete mode 100644 supervision/annotators/dot_marker_annotator.py diff --git a/supervision/__init__.py b/supervision/__init__.py index 31d01314..b1d25337 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -12,6 +12,7 @@ from supervision.annotators.core import ( BoxCornerAnnotator, BoxMaskAnnotator, CircleAnnotator, + DotAnnotator, EllipseAnnotator, HaloAnnotator, LabelAnnotator, diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 8005f49b..3bde610a 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -602,6 +602,39 @@ class CircleAnnotator(BaseAnnotator): return scene +class DotAnnotator(BaseAnnotator): + def __init__( + self, + color: Union[Color, ColorPalette] = ColorPalette.default(), + radius: int = 4, + position: Position = Position.CENTER, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + self.color: Union[Color, ColorPalette] = color + self.radius: int = radius + self.position: Position = position + self.color_lookup: ColorLookup = color_lookup + + def annotate( + self, + scene: np.ndarray, + detections: Detections, + custom_color_lookup: Optional[np.ndarray] = None, + ) -> np.ndarray: + xy = detections.get_anchor_coordinates(anchor=self.position) + for detection_idx in range(len(detections)): + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + center = (int(xy[detection_idx, 0]), int(xy[detection_idx, 1])) + cv2.circle(scene, center, self.radius, color.as_bgr(), -1) + return scene + class LabelAnnotator: """ A class for annotating labels on an image using provided detections. diff --git a/supervision/annotators/dot_marker_annotator.py b/supervision/annotators/dot_marker_annotator.py deleted file mode 100644 index ecdb9af0..00000000 --- a/supervision/annotators/dot_marker_annotator.py +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Union - -import cv2 -import numpy as np - -from supervision import Color, ColorPalette, Detections, Position -from supervision.annotators.base import BaseAnnotator - - -class DotMarkerAnnotator(BaseAnnotator): - def __init__( - self, - color: Union[Color, ColorPalette] = ColorPalette.default(), - radius: int = 4, - position: Position = Position.CENTER, - color_map: str = "class", - ): - self.color = color - self.radius = radius - self.position = position - self.color_map = color_map - - def annotate( - self, - scene: np.ndarray, - detections: Detections, - ) -> np.ndarray: - annotated_scene = scene.copy() - - for detection in detections: - dot_color = self._get_color(detection) - box_position = detection.bounding_box.get_position(self.position) - dot_position = (int(box_position[0]), int(box_position[1])) - cv2.circle(annotated_scene, dot_position, self.radius, dot_color, -1) - - return annotated_scene - - def _get_color(self, detection): - if self.color_map == "class": - return self.color[detection.class_id] - elif self.color_map == "index": - return self.color[detection.index % len(self.color)] - elif self.color_map == "track": - return self.color[detection.track_id % len(self.color)] - else: - raise ValueError("Invalid color mapping strategy") From 1b6613d4a3b3f66adf8cfef82e3679c4baeacdbb Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 16:09:40 +0000 Subject: [PATCH 25/53] =?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/annotators/core.py | 1 + 1 file changed, 1 insertion(+) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 3bde610a..4abb4f91 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -635,6 +635,7 @@ class DotAnnotator(BaseAnnotator): cv2.circle(scene, center, self.radius, color.as_bgr(), -1) return scene + class LabelAnnotator: """ A class for annotating labels on an image using provided detections. From 142fe02959d6fa2ecb4ff81a525e4fc192f38f23 Mon Sep 17 00:00:00 2001 From: kapter Date: Wed, 18 Oct 2023 19:44:15 +0300 Subject: [PATCH 26/53] add params for hsv --- supervision/annotators/core.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 072e1026..a9aa0da6 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -97,6 +97,8 @@ class HeatmapAnnotator: opacity: float = 0.2, radius: int = 40, kernel_size: Optional[int] = 25, + top_hue: int = 0, #red + low_hue: int = 125, #blue ): """ Args: @@ -105,12 +107,19 @@ class HeatmapAnnotator: opacity (float): Opacity of the overlay mask. Must be between `0` and `1`. radius (int): Radius of the heat circle. kernel_size (Optional[int]): Kernel size for blurring the heatmap. + top_hue (int): Hue of the top of the heatmap. + Defaults to `0` (red). + low_hue (int): Hue of the bottom of the heatmap. + Defaults to `125` (blue). """ self.position = position self.opacity = opacity self.radius = radius self.kernel_size = kernel_size self.heatmask = None + self.top_hue = top_hue + self.low_hue = low_hue + def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: """ @@ -156,19 +165,17 @@ class HeatmapAnnotator: cv2.circle(mask, (int(xy[0]), int(xy[1])), self.radius, 1, -1) self.heatmask = mask + self.heatmask temp = self.heatmask.copy() - temp = 100 - temp / temp.max() * 90 + temp = self.low_hue-temp/temp.max()*(self.low_hue-self.top_hue) temp = temp.astype(np.uint8) if self.kernel_size is not None: - temp = cv2.GaussianBlur(temp, (self.kernel_size, self.kernel_size), 0) + temp = cv2.blur(temp, (self.kernel_size, self.kernel_size)) hsv = np.zeros(scene.shape) hsv[..., 0] = temp hsv[..., 1] = 255 hsv[..., 2] = 255 - mask = temp > 0 temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) - scene[mask] = cv2.addWeighted(temp, self.opacity, scene, 1 - self.opacity, 0)[ - mask - ] + mask = cv2.cvtColor(self.heatmask.astype(np.uint8), cv2.COLOR_GRAY2BGR)>0 + scene[mask] = cv2.addWeighted( temp, self.opacity,scene, 1-self.opacity, 0)[mask] return scene From b9d1d78f31013a1416837e306eceb8e6ecf13c9b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 16:45:50 +0000 Subject: [PATCH 27/53] =?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/annotators/core.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index a9aa0da6..7764d420 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -97,8 +97,8 @@ class HeatmapAnnotator: opacity: float = 0.2, radius: int = 40, kernel_size: Optional[int] = 25, - top_hue: int = 0, #red - low_hue: int = 125, #blue + top_hue: int = 0, # red + low_hue: int = 125, # blue ): """ Args: @@ -107,7 +107,7 @@ class HeatmapAnnotator: opacity (float): Opacity of the overlay mask. Must be between `0` and `1`. radius (int): Radius of the heat circle. kernel_size (Optional[int]): Kernel size for blurring the heatmap. - top_hue (int): Hue of the top of the heatmap. + top_hue (int): Hue of the top of the heatmap. Defaults to `0` (red). low_hue (int): Hue of the bottom of the heatmap. Defaults to `125` (blue). @@ -119,7 +119,6 @@ class HeatmapAnnotator: self.heatmask = None self.top_hue = top_hue self.low_hue = low_hue - def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: """ @@ -165,7 +164,7 @@ class HeatmapAnnotator: cv2.circle(mask, (int(xy[0]), int(xy[1])), self.radius, 1, -1) self.heatmask = mask + self.heatmask temp = self.heatmask.copy() - temp = self.low_hue-temp/temp.max()*(self.low_hue-self.top_hue) + temp = self.low_hue - temp / temp.max() * (self.low_hue - self.top_hue) temp = temp.astype(np.uint8) if self.kernel_size is not None: temp = cv2.blur(temp, (self.kernel_size, self.kernel_size)) @@ -174,8 +173,10 @@ class HeatmapAnnotator: hsv[..., 1] = 255 hsv[..., 2] = 255 temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) - mask = cv2.cvtColor(self.heatmask.astype(np.uint8), cv2.COLOR_GRAY2BGR)>0 - scene[mask] = cv2.addWeighted( temp, self.opacity,scene, 1-self.opacity, 0)[mask] + mask = cv2.cvtColor(self.heatmask.astype(np.uint8), cv2.COLOR_GRAY2BGR) > 0 + scene[mask] = cv2.addWeighted(temp, self.opacity, scene, 1 - self.opacity, 0)[ + mask + ] return scene From 25a45aa42357a7a81ddedfb1b08aff6117c76a9f Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 18:53:39 +0200 Subject: [PATCH 28/53] Expand and update Color, ColorPalette, and DotAnnotator classes Added detailed comments and examples to the Color and ColorPalette classes in supervision/draw/color.py, in addition to the DotAnnotator class in supervision/annotators/core.py. The changes clarify the usage and function of these classes. Also appended to the documentation by creating a new section for Color in docs/draw/color.md and including Color and DotAnnotator in docs/annotators.md. Incorporated the new documentation into the navigation structure in mkdocs.yml for user accessibility. The improvements enhance overall code-readability and understandability. --- docs/annotators.md | 29 +++++++++++ docs/draw/color.md | 7 +++ mkdocs.yml | 1 + supervision/annotators/core.py | 42 ++++++++++++++++ supervision/annotators/utils.py | 11 ++++- supervision/draw/color.py | 87 ++++++++++++++++++++++++++------- 6 files changed, 157 insertions(+), 20 deletions(-) create mode 100644 docs/draw/color.md diff --git a/docs/annotators.md b/docs/annotators.md index 9709d7c8..98f5fd08 100644 --- a/docs/annotators.md +++ b/docs/annotators.md @@ -82,6 +82,27 @@ +=== "Dot" + + ```python + >>> import supervision as sv + + >>> image = ... + >>> detections = sv.Detections(...) + + >>> dot_annotator = sv.DotAnnotator() + >>> annotated_frame = dot_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + ``` + +
+ + ![circle-annotator-example](https://media.roboflow.com/supervision-annotator-examples/dot-annotator-example-purple.png){ align=center width="800" } + +
+ === "Ellipse" ```python @@ -224,6 +245,10 @@ :::supervision.annotators.core.CircleAnnotator +## DotAnnotator + +:::supervision.annotators.core.DotAnnotator + ## EllipseAnnotator :::supervision.annotators.core.EllipseAnnotator @@ -247,3 +272,7 @@ ## TraceAnnotator :::supervision.annotators.core.TraceAnnotator + +## ColorLookup + +:::supervision.annotators.utils.ColorLookup diff --git a/docs/draw/color.md b/docs/draw/color.md new file mode 100644 index 00000000..d0259463 --- /dev/null +++ b/docs/draw/color.md @@ -0,0 +1,7 @@ +## Color + +:::supervision.draw.color.Color + +## ColorPalette + +:::supervision.draw.color.ColorPalette \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index f511cb2f..98d21dc4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -48,6 +48,7 @@ nav: - Metrics: - Object Detection: metrics/detection.md - Draw: + - Color: draw/color.md - Utils: draw/utils.md - Utils: - Video: utils/video.md diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 4abb4f91..d371a9fc 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -603,6 +603,10 @@ class CircleAnnotator(BaseAnnotator): class DotAnnotator(BaseAnnotator): + """ + A class for drawing dots on an image at specific coordinates based on provided detections. + """ + def __init__( self, color: Union[Color, ColorPalette] = ColorPalette.default(), @@ -610,6 +614,15 @@ class DotAnnotator(BaseAnnotator): position: Position = Position.CENTER, color_lookup: ColorLookup = ColorLookup.CLASS, ): + """ + Args: + color (Union[Color, ColorPalette]): The color or color palette to use for + annotating detections. + radius (int): Radius of the drawn dots. + position (Position): The anchor position for placing the dot. + color_lookup (ColorLookup): Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACE`. + """ self.color: Union[Color, ColorPalette] = color self.radius: int = radius self.position: Position = position @@ -621,6 +634,35 @@ class DotAnnotator(BaseAnnotator): detections: Detections, custom_color_lookup: Optional[np.ndarray] = None, ) -> np.ndarray: + """ + Annotates the given scene with dots based on the provided detections. + + Args: + scene (np.ndarray): The image where dots will be drawn. + detections (Detections): Object detections to annotate. + custom_color_lookup (Optional[np.ndarray]): Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + np.ndarray: The annotated image. + + Example: + ```python + >>> import supervision as sv + + >>> image = ... + >>> detections = sv.Detections(...) + + >>> dot_annotator = sv.DotAnnotator() + >>> annotated_frame = dot_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + ``` + + ![dot-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/dot-annotator-example-purple.png) + """ xy = detections.get_anchor_coordinates(anchor=self.position) for detection_idx in range(len(detections)): color = resolve_color( diff --git a/supervision/annotators/utils.py b/supervision/annotators/utils.py index 6b6b9837..5b4e86cb 100644 --- a/supervision/annotators/utils.py +++ b/supervision/annotators/utils.py @@ -10,13 +10,22 @@ from supervision.geometry.core import Position class ColorLookup(Enum): """ - Enum for annotator color lookup. + Enumeration class to define strategies for mapping colors to annotations. + + This enum supports three different lookup strategies: + - `INDEX`: Colors are determined by the index of the detection within the scene. + - `CLASS`: Colors are determined by the class label of the detected object. + - `TRACK`: Colors are determined by the tracking identifier of the object. """ INDEX = "index" CLASS = "class" TRACK = "track" + @classmethod + def list(cls): + return list(map(lambda c: c.value, cls)) + def resolve_color_idx( detections: Detections, diff --git a/supervision/draw/color.py b/supervision/draw/color.py index ed28e78b..a4d41b76 100644 --- a/supervision/draw/color.py +++ b/supervision/draw/color.py @@ -34,6 +34,14 @@ def _validate_color_hex(color_hex: str): @dataclass class Color: + """ + Represents a color in RGB format. + + Attributes: + r (int): Red channel. + g (int): Green channel. + b (int): Blue channel. + """ r: int g: int b: int @@ -41,14 +49,19 @@ class Color: @classmethod def from_hex(cls, color_hex: str): """ - Creates a Color instance from a color hex string + Create a Color instance from a hex string. - :param color_hex: str : The color hex string in the format - of "fff", "ffffff", "#fff", or "#ffffff" - :return: Color : A Color instance representing the color + Args: + color_hex (str): Hex string of the color. + + Returns: + Color: Instance representing the color. Example: - color = Color.from_hex('#ff00ff') + ``` + >>> Color.from_hex('#ff00ff') + Color(r=255, g=0, b=255) + ``` """ _validate_color_hex(color_hex) color_hex = color_hex.lstrip("#") @@ -59,17 +72,31 @@ class Color: def as_rgb(self) -> Tuple[int, int, int]: """ - Returns the color as a tuple of integers in the RGB format + Returns the color as an RGB tuple. - :return: Tuple[int, int, int] : The color in the RGB format + Returns: + Tuple[int, int, int]: RGB tuple. + + Example: + ``` + >>> color.as_rgb() + (255, 0, 255) + ``` """ return self.r, self.g, self.b def as_bgr(self) -> Tuple[int, int, int]: """ - Returns the color as a tuple of integers in the BGR format + Returns the color as a BGR tuple. - :return: Tuple[int, int, int] : The color in the BGR format + Returns: + Tuple[int, int, int]: BGR tuple. + + Example: + ``` + >>> color.as_bgr() + (255, 0, 255) + ``` """ return self.b, self.g, self.r @@ -100,33 +127,55 @@ class ColorPalette: @classmethod def default(cls) -> ColorPalette: + """ + Returns a default color palette. + + Returns: + ColorPalette: A ColorPalette instance with default colors. + + Example: + ``` + >>> ColorPalette.default() + ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...]) + ``` + """ return ColorPalette.from_hex(color_hex_list=DEFAULT_COLOR_PALETTE) @classmethod def from_hex(cls, color_hex_list: List[str]): """ - Creates a ColorPalette instance from a list of color hex strings + Create a ColorPalette instance from a list of hex strings. - :param color_hex_list: List[str] : A list of color hex strings in the - format of "fff", "ffffff", "#fff", or "#ffffff" - :return: ColorPalette : A ColorPalette instance representing the color palette + Args: + color_hex_list (List[str]): List of color hex strings. + + Returns: + ColorPalette: A ColorPalette instance. Example: - color_palette = ColorPalette.from_hex(['#ff0000', '#00ff00', '#0000ff']) + ``` + >>> ColorPalette.from_hex(['#ff0000', '#00ff00', '#0000ff']) + ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...]) + ``` """ colors = [Color.from_hex(color_hex) for color_hex in color_hex_list] return cls(colors) def by_idx(self, idx: int) -> Color: """ - Returns the color at a given index in the color palette. + Return the color at a given index in the palette. - :param idx: int : The index of the color in the color palette - :return: Color : The color at the given index + Args: + idx (int): Index of the color in the palette. + + Returns: + Color: Color at the given index. Example: - color_palette = ColorPalette.from_hex(['#ff0000', '#00ff00', '#0000ff']) - color = color_palette.by_idx(1) + ``` + >>> color_palette.by_idx(1) + Color(r=0, g=255, b=0) + ``` """ if idx < 0: raise ValueError("idx argument should not be negative") From e209c7436c38be5e4010eb8562f849a9a5b05fc5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 16:57:04 +0000 Subject: [PATCH 29/53] =?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/draw/color.md | 2 +- supervision/draw/color.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/draw/color.md b/docs/draw/color.md index d0259463..5114f4ba 100644 --- a/docs/draw/color.md +++ b/docs/draw/color.md @@ -4,4 +4,4 @@ ## ColorPalette -:::supervision.draw.color.ColorPalette \ No newline at end of file +:::supervision.draw.color.ColorPalette diff --git a/supervision/draw/color.py b/supervision/draw/color.py index a4d41b76..aceb0da0 100644 --- a/supervision/draw/color.py +++ b/supervision/draw/color.py @@ -42,6 +42,7 @@ class Color: g (int): Green channel. b (int): Blue channel. """ + r: int g: int b: int From e173510117dde22ca9fb268bf9ae99470767cd94 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 19:01:54 +0200 Subject: [PATCH 30/53] Refactor DotAnnotator docstring for clarity --- supervision/annotators/core.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index d371a9fc..cb50f868 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -604,7 +604,8 @@ class CircleAnnotator(BaseAnnotator): class DotAnnotator(BaseAnnotator): """ - A class for drawing dots on an image at specific coordinates based on provided detections. + A class for drawing dots on an image at specific coordinates based on provided + detections. """ def __init__( From 809d8946e61bd22402a2172e55b9a801c309fc17 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 20:50:52 +0200 Subject: [PATCH 31/53] Update docs on object detection and annotation This commit clarifies the process of object detection and annotation using Supervision and the Ultralytics YOLOv8 model. The changes also include updated instructions on how to load model predictions into Supervision and using them to annotate images, with links to the methods used in the process and the available options. An image showing the resulting annotated image has also been added for better understanding. The changes are shaped to make the documentation more informative, concise, and easy to follow. --- docs/how_to/detect_and_annotate.md | 87 +++++++++++++++--------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index 7c121fa2..66e09115 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -1,54 +1,59 @@ -## How to Detect and Annotate +With Supervision, you can easily [annotate](https://supervision.roboflow.com/annotators/) predictions obtained from a variety of object detection and segmentation models. This document outlines how to run inference using the [Ultralytics](https://github.com/ultralytics/ultralytics) YOLOv8 model, load these predictions into Supervision, and annotate the image. -Supervision enables you to annotate predictions from object detection and segmentation models in a few lines of code. - -The `sv.BoxAnnotator` class lets you annotate images with bounding boxes, while the `sv.MaskAnnotator` class lets you annotate images with segmentation masks. `sv.MaskAnnotator` is a drop-in replacement for `sv.BoxAnnotator`, so you don't need to update any other code if you want to switch between the two. - -In this guide, we run inference on an Ultralytics YOLOv8 object detection model and plot the predictions with the `sv.BoxAnnotator` class. You can also load predictions using: - -- `from_deepsparse` (Deepsparse) -- `from_detectron2` (Detectron2) -- `from_mmdetection` (MMDetection) -- `from_ultralytics` (Ultralytics) -- `from_roboflow` (Roboflow) -- `from_sam` (Segment Anything Model) -- `from_transformers` (Hugging Face Transformers) -- `from_yolo_nas` (YOLO-NAS) - -## Load a Model and Retrieve Predictions - -First, we need to retrieve predictions from a model. For this guide, we will retrieve predictions from a YOLOv8 model. See a list of all models from which you can load predictions into supervision. +## Run Inference +First, you'll need to obtain predictions from your object detection or segmentation model. ```python -import supervision as sv -from ultralytics import YOLO import cv2 +from ultralytics import YOLO model = YOLO("yolov8n.pt") - -results = model("image.jpg") +image = cv2.imread("image.jpg") +results = model(image)[0] ``` -In this code, we import `supervision`, `ultralytics`, and `cv2` (OpenCV). We load then load a YOLOv8 object detection model, then run inference on an image called `image.jpg`. The image is loaded using OpenCV. The `results` variable contains the predictions from the model. - ## Load Predictions into Supervision -Now that we have predictions from a model, we can load them into supervision. - -We can do so using the `sv.Detections.from_ultralytics` method, which accepts model results from Ultralytics models. [See a list of other supported data loaders](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_deepsparse). +Now that we have predictions from a model, we can load them into Supervision. We can do so using the [`sv.Detections.from_ultralytics`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_ultralytics) method, which accepts model results from both detection and segmentation models. ```python -detections = sv.Detections.from_ultralytics(results[0]) +import cv2 +from ultralytics import YOLO +import supervision as sv + +model = YOLO("yolov8n.pt") +image = cv2.imread("image.jpg") +results = model(image)[0] +detections = sv.Detections.from_ultralytics(results) ``` +You can conveniently load predictions from other computer vision frameworks and libraries using: + +- [`from_deepsparse`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_deepsparse) ([Deepsparse](https://github.com/neuralmagic/deepsparse)) +- [`from_detectron2`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_detectron2) ([Detectron2](https://github.com/facebookresearch/detectron2)) +- [`from_mmdetection`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_mmdetection) ([MMDetection](https://github.com/open-mmlab/mmdetection)) +- [`from_roboflow`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_roboflow) ([Roboflow Inference](https://github.com/roboflow/inference)) +- [`from_sam`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_sam) ([Segment Anything Model](https://github.com/facebookresearch/segment-anything)) +- [`from_transformers`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_transformers) ([HuggingFace Transformers](https://github.com/huggingface/transformers)) +- [`from_yolo_nas`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_yolo_nas) ([YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md)) + + ## Annotate Image -Next, we can annotate the image with the predictions returned by our model. Since we are working with an object detection model, we will use the `sv.BoxAnnotator` class to annotate an image with predictions. +Finally, we can annotate the image with the predictions. Since we are working with an object detection model, we will use the [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) and [`sv.LabelAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.LabelAnnotator) classes. If you are running the segmentation model [`sv.MaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.MaskAnnotator) is a drop-in replacement for [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) that will allow you to draw masks instead of boxes. ```python -image = cv2.imread("image.jpg") +import cv2 +from ultralytics import YOLO +import supervision as sv -annotator = sv.BoxAnnotator() +model = YOLO("yolov8n.pt") +image = cv2.imread("image.jpg") +results = model(image)[0] +detections = sv.Detections.from_ultralytics(results) + +bounding_box_annotator = sv.BoundingBoxAnnotator() +label_annotator = sv.LabelAnnotator() labels = [ results.names[class_id] @@ -56,24 +61,18 @@ labels = [ in detections.class_id ] -annotated_image = annotator.annotate(image, detections, labels) +annotated_image = bounding_box_annotator.annotate( + scene=image, detections=detections) +annotated_image = label_annotator.annotate( + scene=annotated_image, detections=detections, labels=labels) ``` -In this code, we: - -1. Load the image to annotate. -2. Create a `sv.BoxAnnotator` object to annotate the image. -3. Create a list of labels for each prediction. In this example, we get the class name associated with each class ID using the `results[0].names` attribute available in the `results` object` -3. Use the `annotate` method to annotate the image with the predictions. +![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate_example.png) ## Display Annotated Image -Finally, we can display the annotated image: +To display the annotated image in Jupyter Notebook or Google Colab, use the [`sv.plot_image`](https://supervision.roboflow.com/utils/notebook/#supervision.utils.notebook.plot_image) function. ```python sv.plot_image(annotated_image) ``` - -Here is the result: - -![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate_example.png) From 54bb79c22002c388a4ff01e2af3c0fa45e079a4a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 18:51:32 +0000 Subject: [PATCH 32/53] =?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/how_to/detect_and_annotate.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/how_to/detect_and_annotate.md b/docs/how_to/detect_and_annotate.md index 66e09115..04250bc3 100644 --- a/docs/how_to/detect_and_annotate.md +++ b/docs/how_to/detect_and_annotate.md @@ -14,7 +14,7 @@ results = model(image)[0] ## Load Predictions into Supervision -Now that we have predictions from a model, we can load them into Supervision. We can do so using the [`sv.Detections.from_ultralytics`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_ultralytics) method, which accepts model results from both detection and segmentation models. +Now that we have predictions from a model, we can load them into Supervision. We can do so using the [`sv.Detections.from_ultralytics`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_ultralytics) method, which accepts model results from both detection and segmentation models. ```python import cv2 @@ -40,7 +40,7 @@ You can conveniently load predictions from other computer vision frameworks and ## Annotate Image -Finally, we can annotate the image with the predictions. Since we are working with an object detection model, we will use the [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) and [`sv.LabelAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.LabelAnnotator) classes. If you are running the segmentation model [`sv.MaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.MaskAnnotator) is a drop-in replacement for [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) that will allow you to draw masks instead of boxes. +Finally, we can annotate the image with the predictions. Since we are working with an object detection model, we will use the [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) and [`sv.LabelAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.LabelAnnotator) classes. If you are running the segmentation model [`sv.MaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.MaskAnnotator) is a drop-in replacement for [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) that will allow you to draw masks instead of boxes. ```python import cv2 From a037a4a4041109593d1d98fa013332d74a8e3807 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 21:17:51 +0200 Subject: [PATCH 33/53] Add HeatMapAnnotator class to supervision A HeatMapAnnotator class has been added for visualization purposes. This class can be used to draw heatmaps on an image based on provided detections, where the heat accumulates over time and is drawn as a semi-transparent overlay of blurred circles. --- supervision/__init__.py | 1 + supervision/annotators/core.py | 217 +++++++++++++++++---------------- 2 files changed, 114 insertions(+), 104 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index b1d25337..69b1a344 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -15,6 +15,7 @@ from supervision.annotators.core import ( DotAnnotator, EllipseAnnotator, HaloAnnotator, + HeatMapAnnotator, LabelAnnotator, MaskAnnotator, TraceAnnotator, diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 4d3fea5f..444d8ff2 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -89,101 +89,6 @@ class BoundingBoxAnnotator(BaseAnnotator): return scene -class HeatmapAnnotator: - """ - A class for drawing heatmap on an image using provided detections. - Heat is accumulated over time. Drawn as a semi-transparent overlay as blured circles. - """ - - def __init__( - self, - position: Optional[Position] = Position.BOTTOM_CENTER, - opacity: float = 0.2, - radius: int = 40, - kernel_size: Optional[int] = 25, - top_hue: int = 0, # red - low_hue: int = 125, # blue - ): - """ - Args: - position (Optional[Position]): The position of the heatmap. - Defaults to `BOTTOM_CENTER`. - opacity (float): Opacity of the overlay mask. Must be between `0` and `1`. - radius (int): Radius of the heat circle. - kernel_size (Optional[int]): Kernel size for blurring the heatmap. - top_hue (int): Hue of the top of the heatmap. - Defaults to `0` (red). - low_hue (int): Hue of the bottom of the heatmap. - Defaults to `125` (blue). - """ - self.position = position - self.opacity = opacity - self.radius = radius - self.kernel_size = kernel_size - self.heatmask = None - self.top_hue = top_hue - self.low_hue = low_hue - - def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: - """ - Annotates the given scene with heatmap based on the provided detections. - - Args: - scene (np.ndarray): The image where heatmap will be drawn. - detections (Detections): Object detections to annotate. - - Returns: - np.ndarray: The annotated image. - - Example: - ```python - >>> import supervision as sv - >>> model = YOLO('yolov8s.pt') - >>> video_info = sv.VideoInfo.from_video_path(video_path=video_path) - >>> hma = HeatmapAnnotator( - ... position=Position.BOTTOM_CENTER, - ... opacity=0.2, - ... radius=40, - ... kernel_size=25, - ...) - >>> with sv.VideoSink(target_path=target_path, video_info=video_info) as sink: - ... for result in tqdm(model(source=video_path, agnostic_nms=True, verbose=False), total=video_info.total_frames): - ... frame = result.orig_img - ... detections = sv.Detections.from_ultralytics(result) - ... detections = detections[detections.class_id == 0] - ... annotated_frame = hma.annotate( - ... scene=frame.copy(), - ... detections=detections) - ... sink.write_frame(frame=annotated_frame) - ``` - - ![heatmap-annotator-example](https://media.roboflow.com/ - supervision-annotator-examples/heatmap-annotator-example.png) - """ - - if self.heatmask is None: - self.heatmask = np.zeros(scene.shape[:2]) - mask = np.zeros(scene.shape[:2]) - for xy in detections.get_anchor_coordinates(self.position): - cv2.circle(mask, (int(xy[0]), int(xy[1])), self.radius, 1, -1) - self.heatmask = mask + self.heatmask - temp = self.heatmask.copy() - temp = self.low_hue - temp / temp.max() * (self.low_hue - self.top_hue) - temp = temp.astype(np.uint8) - if self.kernel_size is not None: - temp = cv2.blur(temp, (self.kernel_size, self.kernel_size)) - hsv = np.zeros(scene.shape) - hsv[..., 0] = temp - hsv[..., 1] = 255 - hsv[..., 2] = 255 - temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) - mask = cv2.cvtColor(self.heatmask.astype(np.uint8), cv2.COLOR_GRAY2BGR) > 0 - scene[mask] = cv2.addWeighted(temp, self.opacity, scene, 1 - self.opacity, 0)[ - mask - ] - return scene - - class MaskAnnotator(BaseAnnotator): """ A class for drawing masks on an image using provided detections. @@ -1010,7 +915,7 @@ class TraceAnnotator: def __init__( self, color: Union[Color, ColorPalette] = ColorPalette.default(), - position: Optional[Position] = Position.CENTER, + position: Position = Position.CENTER, trace_length: int = 30, thickness: int = 2, color_lookup: ColorLookup = ColorLookup.CLASS, @@ -1019,7 +924,7 @@ class TraceAnnotator: Args: color (Union[Color, ColorPalette]): The color to draw the trace, can be a single color or a color palette. - position (Optional[Position]): The position of the trace. + position (Position): The position of the trace. Defaults to `CENTER`. trace_length (int): The maximum length of the trace in terms of historical points. Defaults to `30`. @@ -1055,15 +960,25 @@ class TraceAnnotator: Example: ```python >>> import supervision as sv + >>> from ultralytics import YOLO - >>> image = ... - >>> detections = sv.Detections(...) + >>> model = YOLO('yolov8x.pt') - >>> trace_annotator = sv.TraceAnnotator() - >>> annotated_frame = trace_annotator.annotate( - ... scene=image.copy(), - ... detections=detections - ... ) + >>> heat_map_annotator = sv.TraceAnnotator() + + >>> video_info = sv.VideoInfo.from_video_path(video_path=...) + >>> frames_generator = get_video_frames_generator(source_path=...) + >>> tracker = sv.ByteTrack() + + >>> with sv.VideoSink(target_path=..., video_info=video_info) as sink: + ... for frame in frames_generator: + ... result = model(frame)[0] + ... detections = sv.Detections.from_ultralytics(result) + ... detections = tracker.update_with_detections(detections) + ... annotated_frame = trace_annotator.annotate( + ... scene=frame.copy(), + ... detections=detections) + ... sink.write_frame(frame=annotated_frame) ``` ![trace-annotator-example](https://media.roboflow.com/ @@ -1091,3 +1006,97 @@ class TraceAnnotator: thickness=self.thickness, ) return scene + + +class HeatMapAnnotator: + """ + A class for drawing heatmaps on an image based on provided detections. + Heat accumulates over time and is drawn as a semi-transparent overlay + of blurred circles. + """ + + def __init__( + self, + position: Position = Position.BOTTOM_CENTER, + opacity: float = 0.2, + radius: int = 40, + kernel_size: int = 25, + top_hue: int = 0, + low_hue: int = 125, + ): + """ + Args: + position (Position): The position of the heatmap. Defaults to + `BOTTOM_CENTER`. + opacity (float): Opacity of the overlay mask, between 0 and 1. + radius (int): Radius of the heat circle. + kernel_size (int): Kernel size for blurring the heatmap. + top_hue (int): Hue at the top of the heatmap. Defaults to 0 (red). + low_hue (int): Hue at the bottom of the heatmap. Defaults to 125 (blue). + """ + self.position = position + self.opacity = opacity + self.radius = radius + self.kernel_size = kernel_size + self.heat_mask = None + self.top_hue = top_hue + self.low_hue = low_hue + + def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray: + """ + Annotates the scene with a heatmap based on the provided detections. + + Args: + scene (np.ndarray): The image where the heatmap will be drawn. + detections (Detections): Object detections to annotate. + + Returns: + np.ndarray: Annotated image. + + Example: + ```python + >>> import supervision as sv + >>> from ultralytics import YOLO + + >>> model = YOLO('yolov8x.pt') + + >>> heat_map_annotator = sv.HeatMapAnnotator() + + >>> video_info = sv.VideoInfo.from_video_path(video_path=...) + >>> frames_generator = get_video_frames_generator(source_path=...) + + >>> with sv.VideoSink(target_path=..., video_info=video_info) as sink: + ... for frame in frames_generator: + ... result = model(frame)[0] + ... detections = sv.Detections.from_ultralytics(result) + ... annotated_frame = heat_map_annotator.annotate( + ... scene=frame.copy(), + ... detections=detections) + ... sink.write_frame(frame=annotated_frame) + ``` + + ![heatmap-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/heatmap-annotator-example.png) + """ + + if self.heat_mask is None: + self.heat_mask = np.zeros(scene.shape[:2]) + mask = np.zeros(scene.shape[:2]) + for xy in detections.get_anchor_coordinates(self.position): + cv2.circle(mask, (int(xy[0]), int(xy[1])), self.radius, 1, -1) + self.heat_mask = mask + self.heat_mask + temp = self.heat_mask.copy() + temp = self.low_hue - temp / temp.max() * (self.low_hue - self.top_hue) + temp = temp.astype(np.uint8) + if self.kernel_size is not None: + temp = cv2.blur(temp, (self.kernel_size, self.kernel_size)) + hsv = np.zeros(scene.shape) + hsv[..., 0] = temp + hsv[..., 1] = 255 + hsv[..., 2] = 255 + temp = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2BGR) + mask = cv2.cvtColor(self.heat_mask.astype(np.uint8), cv2.COLOR_GRAY2BGR) > 0 + scene[mask] = cv2.addWeighted(temp, self.opacity, scene, 1 - self.opacity, 0)[ + mask + ] + return scene From d66a53977954a33e66d752f08eb7407a6648a4b9 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 21:25:44 +0200 Subject: [PATCH 34/53] Update example code blocks in `core.py` and `annotators.md` Code examples in `supervision/annotators/core.py` and `docs/annotators.md` have been updated for clarity and consistency. The changes include renaming variables more appropriately and elaborating on the video processing steps which now includes tracking and annotating frames using a YOLO model. This revision aims to make examples more understandable and consistent for users following the documentation. --- docs/annotators.md | 55 ++++++++++++++++++++++++++++++---- supervision/annotators/core.py | 14 ++++----- 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/docs/annotators.md b/docs/annotators.md index 98f5fd08..b9ae93d8 100644 --- a/docs/annotators.md +++ b/docs/annotators.md @@ -212,15 +212,54 @@ ```python >>> import supervision as sv + >>> from ultralytics import YOLO - >>> image = ... - >>> detections = sv.Detections(...) + >>> model = YOLO('yolov8x.pt') >>> trace_annotator = sv.TraceAnnotator() - >>> annotated_frame = trace_annotator.annotate( - ... scene=image.copy(), - ... detections=detections - ... ) + + >>> video_info = sv.VideoInfo.from_video_path(video_path='...') + >>> frames_generator = get_video_frames_generator(source_path='...') + >>> tracker = sv.ByteTrack() + + >>> with sv.VideoSink(target_path='...', video_info=video_info) as sink: + ... for frame in frames_generator: + ... result = model(frame)[0] + ... detections = sv.Detections.from_ultralytics(result) + ... detections = tracker.update_with_detections(detections) + ... annotated_frame = trace_annotator.annotate( + ... scene=frame.copy(), + ... detections=detections) + ... sink.write_frame(frame=annotated_frame) + ``` + +
+ + ![trace-annotator-example](https://media.roboflow.com/supervision-annotator-examples/trace-annotator-example-purple.png){ align=center width="800" } + +
+ +=== "HeatMap" + + ```python + >>> import supervision as sv + >>> from ultralytics import YOLO + + >>> model = YOLO('yolov8x.pt') + + >>> heat_map_annotator = sv.HeatMapAnnotator() + + >>> video_info = sv.VideoInfo.from_video_path(video_path='...') + >>> frames_generator = get_video_frames_generator(source_path='...') + + >>> with sv.VideoSink(target_path='...', video_info=video_info) as sink: + ... for frame in frames_generator: + ... result = model(frame)[0] + ... detections = sv.Detections.from_ultralytics(result) + ... annotated_frame = heat_map_annotator.annotate( + ... scene=frame.copy(), + ... detections=detections) + ... sink.write_frame(frame=annotated_frame) ```
@@ -257,6 +296,10 @@ :::supervision.annotators.core.HaloAnnotator +## HeatMapAnnotator + +:::supervision.annotators.core.HeatMapAnnotator + ## MaskAnnotator :::supervision.annotators.core.MaskAnnotator diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 444d8ff2..5c133a23 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -964,13 +964,13 @@ class TraceAnnotator: >>> model = YOLO('yolov8x.pt') - >>> heat_map_annotator = sv.TraceAnnotator() + >>> trace_annotator = sv.TraceAnnotator() - >>> video_info = sv.VideoInfo.from_video_path(video_path=...) - >>> frames_generator = get_video_frames_generator(source_path=...) + >>> video_info = sv.VideoInfo.from_video_path(video_path='...') + >>> frames_generator = sv.get_video_frames_generator(source_path='...') >>> tracker = sv.ByteTrack() - >>> with sv.VideoSink(target_path=..., video_info=video_info) as sink: + >>> with sv.VideoSink(target_path='...', video_info=video_info) as sink: ... for frame in frames_generator: ... result = model(frame)[0] ... detections = sv.Detections.from_ultralytics(result) @@ -1062,10 +1062,10 @@ class HeatMapAnnotator: >>> heat_map_annotator = sv.HeatMapAnnotator() - >>> video_info = sv.VideoInfo.from_video_path(video_path=...) - >>> frames_generator = get_video_frames_generator(source_path=...) + >>> video_info = sv.VideoInfo.from_video_path(video_path='...') + >>> frames_generator = get_video_frames_generator(source_path='...') - >>> with sv.VideoSink(target_path=..., video_info=video_info) as sink: + >>> with sv.VideoSink(target_path='...', video_info=video_info) as sink: ... for frame in frames_generator: ... result = model(frame)[0] ... detections = sv.Detections.from_ultralytics(result) From 5f82aac9e67600d6ea01db265ddde3ed362326c5 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 21:34:56 +0200 Subject: [PATCH 35/53] Update example images link in `core.py` and `annotators.md` The hyperlink to images in the example blocks in `supervision/annotators/core.py`, and `docs/annotators.md` was modified to reflect recent updates to the annotated heat map image. --- docs/annotators.md | 2 +- supervision/annotators/core.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/annotators.md b/docs/annotators.md index b9ae93d8..efb77d11 100644 --- a/docs/annotators.md +++ b/docs/annotators.md @@ -264,7 +264,7 @@
- ![trace-annotator-example](https://media.roboflow.com/supervision-annotator-examples/trace-annotator-example-purple.png){ align=center width="800" } + ![trace-annotator-example](https://media.roboflow.com/supervision-annotator-examples/heat-map-annotator-example-purple.png){ align=center width="800" }
diff --git a/supervision/annotators/core.py b/supervision/annotators/core.py index 5c133a23..3fbd7a85 100644 --- a/supervision/annotators/core.py +++ b/supervision/annotators/core.py @@ -1076,7 +1076,7 @@ class HeatMapAnnotator: ``` ![heatmap-annotator-example](https://media.roboflow.com/ - supervision-annotator-examples/heatmap-annotator-example.png) + supervision-annotator-examples/heat-map-annotator-example-purple.png) """ if self.heat_mask is None: From 737cb37249e0313ab861899600f3ffc547b85fa9 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:31:34 +0200 Subject: [PATCH 36/53] Add new drawing methods and improve type hints Expanded the drawing functionality by adding new utility methods 'draw_image', 'draw_line' and 'draw_rectangle' and imported them in supervision/__init__.py. Updated the documentation of draw/utils, to include 'draw_image'. Improved type hinting in draw/color.py and draw/utils.py. Also, some redundant comments and unnecessary immediate memory freeing line are removed from draw/utils.py to enhance code readability. --- docs/draw/utils.md | 4 ++++ supervision/__init__.py | 9 ++++++++- supervision/draw/color.py | 4 ++-- supervision/draw/utils.py | 5 +++-- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/draw/utils.md b/docs/draw/utils.md index e7bb806b..5832089e 100644 --- a/docs/draw/utils.md +++ b/docs/draw/utils.md @@ -17,3 +17,7 @@ ## draw_text :::supervision.draw.utils.draw_text + +## draw_image + +:::supervision.draw.utils.draw_image diff --git a/supervision/__init__.py b/supervision/__init__.py index 69b1a344..10f654b8 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -42,7 +42,14 @@ from supervision.detection.utils import ( polygon_to_xyxy, ) from supervision.draw.color import Color, ColorPalette -from supervision.draw.utils import draw_filled_rectangle, draw_polygon, draw_text +from supervision.draw.utils import ( + draw_filled_rectangle, + draw_polygon, + draw_text, + draw_image, + draw_line, + draw_rectangle +) from supervision.geometry.core import Point, Position, Rect from supervision.geometry.utils import get_polygon_center from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision diff --git a/supervision/draw/color.py b/supervision/draw/color.py index aceb0da0..69bcc9c5 100644 --- a/supervision/draw/color.py +++ b/supervision/draw/color.py @@ -48,7 +48,7 @@ class Color: b: int @classmethod - def from_hex(cls, color_hex: str): + def from_hex(cls, color_hex: str) -> Color: """ Create a Color instance from a hex string. @@ -143,7 +143,7 @@ class ColorPalette: return ColorPalette.from_hex(color_hex_list=DEFAULT_COLOR_PALETTE) @classmethod - def from_hex(cls, color_hex_list: List[str]): + def from_hex(cls, color_hex_list: List[str]) -> ColorPalette: """ Create a ColorPalette instance from a list of hex strings. diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 73844fbd..f9152969 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -190,11 +190,13 @@ def draw_image( np.ndarray: The scene with the image drawn onto it. Example: + ```python >>> scene = np.zeros((400, 400, 3), dtype=np.uint8) >>> image_path = "path/to/image.jpg" >>> opacity = 0.5 >>> rect = Rect(x=50, y=50, width=200, height=200) >>> new_scene = draw_image(scene, image_path, opacity, rect) + ``` """ if isinstance(image, str): assert os.path.exists(image), f'The specified path ("{image}") does not exist.' @@ -211,14 +213,13 @@ def draw_image( image = cv2.resize(image, (rect.width, rect.height)) - # watermark with transparent background if image.shape[2] == 4: b, g, r, a = cv2.split(image) b = cv2.bitwise_and(b, b, mask=a) g = cv2.bitwise_and(g, g, mask=a) r = cv2.bitwise_and(r, r, mask=a) image = cv2.merge([b, g, r, a]) - del b, g, r, a # immediately free up memory + del b, g, r, a if scene.shape[2] == 3: scene = np.dstack([scene, np.ones(scene.shape[:2], dtype=np.uint8) * 255]) From 743f3281a5a45baf547a160dbaddbfec1159b1bd Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 20:33:05 +0000 Subject: [PATCH 37/53] =?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 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index 10f654b8..f4e70ead 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -44,11 +44,11 @@ from supervision.detection.utils import ( from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( draw_filled_rectangle, - draw_polygon, - draw_text, draw_image, draw_line, - draw_rectangle + draw_polygon, + draw_rectangle, + draw_text, ) from supervision.geometry.core import Point, Position, Rect from supervision.geometry.utils import get_polygon_center From 57ba059f1c2a1016ccf5a1a122c1aa8c26e8e745 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:45:58 +0200 Subject: [PATCH 38/53] test --- supervision/draw/utils.py | 72 ++++++++++++++------------------------- 1 file changed, 26 insertions(+), 46 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index f9152969..171694aa 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,64 +172,44 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. - - Args: - scene (np.ndarray): The background image onto which the image will be drawn. - image (Union[str, np.ndarray]): The image to be drawn. - Can be either a file path or a NumPy array. - opacity (float): The opacity level of the image to be drawn, - ranging from 0.0 to 1.0. - rect (Rect): A Rect object specifying the dimensions and - position where the image will be drawn. - - Returns: - np.ndarray: The scene with the image drawn onto it. - - Example: - ```python - >>> scene = np.zeros((400, 400, 3), dtype=np.uint8) - >>> image_path = "path/to/image.jpg" - >>> opacity = 0.5 - >>> rect = Rect(x=50, y=50, width=200, height=200) - >>> new_scene = draw_image(scene, image_path, opacity, rect) - ``` """ + # Input checks + assert 0.0 <= opacity <= 1.0, "Opacity has to be between 0.0 and 1.0." + assert rect.x >= 0 and rect.y >= 0, "Top left coordinates of the rect must be positive." + assert rect.width > 0 and rect.height > 0, "Rect dimensions should be positive." + assert rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= \ + scene.shape[0], "Image exceeds scene bounds." + + # Read image if a path is provided if isinstance(image, str): - assert os.path.exists(image), f'The specified path ("{image}") does not exist.' + assert os.path.exists(image), f"The specified path '{image}' does not exist." image = cv2.imread(image, cv2.IMREAD_UNCHANGED) - assert 0.0 <= opacity <= 1.0, "The opacity has to be between 0.0 and 1.0." - - assert ( - rect.x >= 0 and rect.y >= 0 - ), "The top left coordinates of the rectangle have to be positive." - assert ( - rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= scene.shape[0] - ), "The image you are trying to draw exceeds the bounds of the scene." - + # Resize the image image = cv2.resize(image, (rect.width, rect.height)) + # If image has an alpha channel, extract it + alpha_channel = None if image.shape[2] == 4: - b, g, r, a = cv2.split(image) - b = cv2.bitwise_and(b, b, mask=a) - g = cv2.bitwise_and(g, g, mask=a) - r = cv2.bitwise_and(r, r, mask=a) - image = cv2.merge([b, g, r, a]) - del b, g, r, a + alpha_channel = image[:, :, 3] + image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR) - if scene.shape[2] == 3: - scene = np.dstack([scene, np.ones(scene.shape[:2], dtype=np.uint8) * 255]) + # Apply opacity to the alpha channel + if alpha_channel is None: + alpha_channel = np.ones(image.shape[:2], dtype=image.dtype) * 255 + alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) - scene_h, scene_w, channels = scene.shape[:3] - water_h, water_w = image.shape[:2] + # Get ROI from the scene + scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] - overlay = np.zeros((scene_h, scene_w, channels), dtype="uint8") - overlay[rect.y : rect.y + water_h, rect.x : rect.x + water_w] = image + # Blend the image and the ROI + blended_roi = cv2.addWeighted(scene_roi, 1 - opacity, image, opacity, 0) - cv2.addWeighted(overlay, opacity, scene, 1.0, 0, scene) + # Apply the blended ROI to the scene + scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi - return scene[:, :, :3] + return scene From b35a6161dd5592c435efa469bce37a77abe4eb7c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 20:46:24 +0000 Subject: [PATCH 39/53] =?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/draw/utils.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 171694aa..550ab134 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,17 +172,20 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. """ # Input checks assert 0.0 <= opacity <= 1.0, "Opacity has to be between 0.0 and 1.0." - assert rect.x >= 0 and rect.y >= 0, "Top left coordinates of the rect must be positive." + assert ( + rect.x >= 0 and rect.y >= 0 + ), "Top left coordinates of the rect must be positive." assert rect.width > 0 and rect.height > 0, "Rect dimensions should be positive." - assert rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= \ - scene.shape[0], "Image exceeds scene bounds." + assert ( + rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= scene.shape[0] + ), "Image exceeds scene bounds." # Read image if a path is provided if isinstance(image, str): @@ -204,12 +207,12 @@ def draw_image( alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) # Get ROI from the scene - scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] # Blend the image and the ROI blended_roi = cv2.addWeighted(scene_roi, 1 - opacity, image, opacity, 0) # Apply the blended ROI to the scene - scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi + scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi return scene From 893a19a991cf0e63b04a5ae2e93d817f082c7d15 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:49:35 +0200 Subject: [PATCH 40/53] test --- supervision/draw/utils.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 171694aa..bded8142 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -192,22 +192,22 @@ def draw_image( # Resize the image image = cv2.resize(image, (rect.width, rect.height)) - # If image has an alpha channel, extract it - alpha_channel = None + # Handle alpha channel for transparent PNG if image.shape[2] == 4: alpha_channel = image[:, :, 3] image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR) + else: + alpha_channel = np.ones(image.shape[:2], dtype=image.dtype) * 255 # Apply opacity to the alpha channel - if alpha_channel is None: - alpha_channel = np.ones(image.shape[:2], dtype=image.dtype) * 255 alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) # Get ROI from the scene scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] - # Blend the image and the ROI - blended_roi = cv2.addWeighted(scene_roi, 1 - opacity, image, opacity, 0) + # Alpha blending + blended_roi = cv2.addWeighted(scene_roi, 1 - (alpha_channel / 255.0), image, + (alpha_channel / 255.0), 0) # Apply the blended ROI to the scene scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi From 08af18ad41193e7cfd75bc472683a8be51a8c6ea Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 20:49:56 +0000 Subject: [PATCH 41/53] =?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/draw/utils.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 08f0b586..7acea903 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -209,8 +209,9 @@ def draw_image( scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] # Alpha blending - blended_roi = cv2.addWeighted(scene_roi, 1 - (alpha_channel / 255.0), image, - (alpha_channel / 255.0), 0) + blended_roi = cv2.addWeighted( + scene_roi, 1 - (alpha_channel / 255.0), image, (alpha_channel / 255.0), 0 + ) # Apply the blended ROI to the scene scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi From be16b84340970075179351e684028139a17affa0 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:53:10 +0200 Subject: [PATCH 42/53] test --- supervision/draw/utils.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 08f0b586..8d8df0e4 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,20 +172,17 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. """ # Input checks assert 0.0 <= opacity <= 1.0, "Opacity has to be between 0.0 and 1.0." - assert ( - rect.x >= 0 and rect.y >= 0 - ), "Top left coordinates of the rect must be positive." + assert rect.x >= 0 and rect.y >= 0, "Top left coordinates of the rect must be positive." assert rect.width > 0 and rect.height > 0, "Rect dimensions should be positive." - assert ( - rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= scene.shape[0] - ), "Image exceeds scene bounds." + assert rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= \ + scene.shape[0], "Image exceeds scene bounds." # Read image if a path is provided if isinstance(image, str): @@ -206,13 +203,19 @@ def draw_image( alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) # Get ROI from the scene - scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] + scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] # Alpha blending - blended_roi = cv2.addWeighted(scene_roi, 1 - (alpha_channel / 255.0), image, - (alpha_channel / 255.0), 0) + alpha_float = alpha_channel.astype(np.float32) / 255.0 + blended_roi = cv2.addWeighted( + scene_roi, + 1.0 - alpha_float[..., np.newaxis], + image, + alpha_float[..., np.newaxis], + 0 + ) # Apply the blended ROI to the scene - scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi + scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi return scene From a5c211ff61e691f9f5aa473fd2ed45b9050cf992 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 20:54:15 +0000 Subject: [PATCH 43/53] =?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/draw/utils.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 8d8df0e4..ceb453d8 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,17 +172,20 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. """ # Input checks assert 0.0 <= opacity <= 1.0, "Opacity has to be between 0.0 and 1.0." - assert rect.x >= 0 and rect.y >= 0, "Top left coordinates of the rect must be positive." + assert ( + rect.x >= 0 and rect.y >= 0 + ), "Top left coordinates of the rect must be positive." assert rect.width > 0 and rect.height > 0, "Rect dimensions should be positive." - assert rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= \ - scene.shape[0], "Image exceeds scene bounds." + assert ( + rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= scene.shape[0] + ), "Image exceeds scene bounds." # Read image if a path is provided if isinstance(image, str): @@ -203,7 +206,7 @@ def draw_image( alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) # Get ROI from the scene - scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] # Alpha blending alpha_float = alpha_channel.astype(np.float32) / 255.0 @@ -212,10 +215,10 @@ def draw_image( 1.0 - alpha_float[..., np.newaxis], image, alpha_float[..., np.newaxis], - 0 + 0, ) # Apply the blended ROI to the scene - scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi + scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi return scene From 0e6d69cf854c58251b5acdf566788bd2690d4c58 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:56:09 +0200 Subject: [PATCH 44/53] test --- supervision/draw/utils.py | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 8d8df0e4..ddacdf37 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -177,45 +177,29 @@ def draw_image( """ Draws an image onto a given scene with specified opacity and dimensions. """ - # Input checks - assert 0.0 <= opacity <= 1.0, "Opacity has to be between 0.0 and 1.0." - assert rect.x >= 0 and rect.y >= 0, "Top left coordinates of the rect must be positive." - assert rect.width > 0 and rect.height > 0, "Rect dimensions should be positive." - assert rect.x + rect.width <= scene.shape[1] and rect.y + rect.height <= \ - scene.shape[0], "Image exceeds scene bounds." # Read image if a path is provided if isinstance(image, str): - assert os.path.exists(image), f"The specified path '{image}' does not exist." image = cv2.imread(image, cv2.IMREAD_UNCHANGED) # Resize the image image = cv2.resize(image, (rect.width, rect.height)) - # Handle alpha channel for transparent PNG + # If the image has an alpha channel, extract it and remove from the image if image.shape[2] == 4: alpha_channel = image[:, :, 3] - image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR) + image = image[:, :, :3] else: - alpha_channel = np.ones(image.shape[:2], dtype=image.dtype) * 255 + alpha_channel = np.ones((rect.height, rect.width), dtype=np.uint8) * 255 # Apply opacity to the alpha channel alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) - # Get ROI from the scene - scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + # Define the ROI and blend the image onto the scene + roi = scene[rect.y: rect.y + rect.height, rect.x: rect.x + rect.width] - # Alpha blending - alpha_float = alpha_channel.astype(np.float32) / 255.0 - blended_roi = cv2.addWeighted( - scene_roi, - 1.0 - alpha_float[..., np.newaxis], - image, - alpha_float[..., np.newaxis], - 0 - ) - - # Apply the blended ROI to the scene - scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi + for c in range(0, 3): + roi[:, :, c] = roi[:, :, c] * (1 - alpha_channel / 255.0) + image[:, :, c] * ( + alpha_channel / 255.0) return scene From 8b73c12bcc89d378ecc4abcef8d6eb888d3b8d87 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 22:58:58 +0200 Subject: [PATCH 45/53] test --- supervision/draw/utils.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index ddacdf37..2bc26e6b 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,20 +172,20 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. """ - # Read image if a path is provided + # Load image if a path is provided if isinstance(image, str): image = cv2.imread(image, cv2.IMREAD_UNCHANGED) # Resize the image image = cv2.resize(image, (rect.width, rect.height)) - # If the image has an alpha channel, extract it and remove from the image + # Separate the alpha channel if present if image.shape[2] == 4: alpha_channel = image[:, :, 3] image = image[:, :, :3] @@ -195,11 +195,21 @@ def draw_image( # Apply opacity to the alpha channel alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) - # Define the ROI and blend the image onto the scene - roi = scene[rect.y: rect.y + rect.height, rect.x: rect.x + rect.width] + # Get the ROI from the scene + scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] - for c in range(0, 3): - roi[:, :, c] = roi[:, :, c] * (1 - alpha_channel / 255.0) + image[:, :, c] * ( - alpha_channel / 255.0) + # Manually apply alpha blending + alpha_float = alpha_channel.astype(np.float32) / 255.0 + blended_roi = ((1.0 - alpha_float[..., np.newaxis]) * scene_roi.astype(np.float32)) + (alpha_float[..., np.newaxis] * image.astype(np.float32)) + blended_roi = blended_roi.astype(np.uint8) + + # Insert blended ROI back into the scene + scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi return scene + + + + + + From 586ff5b3fbe50ec189d1e588589b248d6b9f3e1c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 20:59:14 +0000 Subject: [PATCH 46/53] =?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/draw/utils.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 2bc26e6b..56740377 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -1,4 +1,3 @@ -import os from typing import Optional, Union import cv2 @@ -196,20 +195,16 @@ def draw_image( alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) # Get the ROI from the scene - scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] # Manually apply alpha blending alpha_float = alpha_channel.astype(np.float32) / 255.0 - blended_roi = ((1.0 - alpha_float[..., np.newaxis]) * scene_roi.astype(np.float32)) + (alpha_float[..., np.newaxis] * image.astype(np.float32)) + blended_roi = ( + (1.0 - alpha_float[..., np.newaxis]) * scene_roi.astype(np.float32) + ) + (alpha_float[..., np.newaxis] * image.astype(np.float32)) blended_roi = blended_roi.astype(np.uint8) # Insert blended ROI back into the scene - scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi + scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi return scene - - - - - - From 2fed8ae0c3e18ea79d8d6c04cbd35cc72db5c213 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Wed, 18 Oct 2023 23:10:36 +0200 Subject: [PATCH 47/53] test --- supervision/draw/utils.py | 68 +++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 24 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 56740377..721836f3 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -1,3 +1,4 @@ +import os from typing import Optional, Union import cv2 @@ -171,40 +172,59 @@ def draw_text( def draw_image( - scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect + scene: np.ndarray, + image: Union[str, np.ndarray], + opacity: float, + rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. + + Args: + scene (np.ndarray): Background image where the new image will be drawn. + image (Union[str, np.ndarray]): Image to draw. + opacity (float): Opacity of the image to be drawn. + rect (Rect): Rectangle specifying where to draw the image. + + Returns: + np.ndarray: The updated scene. + + Raises: + FileNotFoundError: If the image path does not exist. + ValueError: For invalid opacity or rectangle dimensions. """ - # Load image if a path is provided + # Validate and load image if isinstance(image, str): + if not os.path.exists(image): + raise FileNotFoundError(f"Image path ('{image}') does not exist.") image = cv2.imread(image, cv2.IMREAD_UNCHANGED) - # Resize the image + # Validate opacity + if not 0.0 <= opacity <= 1.0: + raise ValueError("Opacity must be between 0.0 and 1.0.") + + # Validate rectangle dimensions + if rect.x < 0 or rect.y < 0 or \ + rect.x + rect.width > scene.shape[1] or rect.y + rect.height > scene.shape[ + 0]: + raise ValueError("Invalid rectangle dimensions.") + + # Resize and isolate alpha channel image = cv2.resize(image, (rect.width, rect.height)) + alpha_channel = image[:, :, 3] if image.shape[2] == 4 else np.ones( + (rect.height, rect.width), dtype=image.dtype) * 255 + alpha_scaled = cv2.convertScaleAbs(alpha_channel * opacity) - # Separate the alpha channel if present - if image.shape[2] == 4: - alpha_channel = image[:, :, 3] - image = image[:, :, :3] - else: - alpha_channel = np.ones((rect.height, rect.width), dtype=np.uint8) * 255 + # Perform blending + scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + alpha_float = alpha_scaled.astype(np.float32) / 255.0 + blended_roi = cv2.convertScaleAbs( + (1 - alpha_float[..., np.newaxis]) * scene_roi + alpha_float[ + ..., np.newaxis] * image[:, :, :3] + ) - # Apply opacity to the alpha channel - alpha_channel = cv2.convertScaleAbs(alpha_channel * opacity) - - # Get the ROI from the scene - scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] - - # Manually apply alpha blending - alpha_float = alpha_channel.astype(np.float32) / 255.0 - blended_roi = ( - (1.0 - alpha_float[..., np.newaxis]) * scene_roi.astype(np.float32) - ) + (alpha_float[..., np.newaxis] * image.astype(np.float32)) - blended_roi = blended_roi.astype(np.uint8) - - # Insert blended ROI back into the scene - scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi + # Update the scene + scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi return scene From 815c43beb8aba117914db4df59b9063879db3b99 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 21:11:26 +0000 Subject: [PATCH 48/53] =?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/draw/utils.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/supervision/draw/utils.py b/supervision/draw/utils.py index 721836f3..1d4d5ec6 100644 --- a/supervision/draw/utils.py +++ b/supervision/draw/utils.py @@ -172,10 +172,7 @@ def draw_text( def draw_image( - scene: np.ndarray, - image: Union[str, np.ndarray], - opacity: float, - rect: Rect + scene: np.ndarray, image: Union[str, np.ndarray], opacity: float, rect: Rect ) -> np.ndarray: """ Draws an image onto a given scene with specified opacity and dimensions. @@ -205,26 +202,32 @@ def draw_image( raise ValueError("Opacity must be between 0.0 and 1.0.") # Validate rectangle dimensions - if rect.x < 0 or rect.y < 0 or \ - rect.x + rect.width > scene.shape[1] or rect.y + rect.height > scene.shape[ - 0]: + if ( + rect.x < 0 + or rect.y < 0 + or rect.x + rect.width > scene.shape[1] + or rect.y + rect.height > scene.shape[0] + ): raise ValueError("Invalid rectangle dimensions.") # Resize and isolate alpha channel image = cv2.resize(image, (rect.width, rect.height)) - alpha_channel = image[:, :, 3] if image.shape[2] == 4 else np.ones( - (rect.height, rect.width), dtype=image.dtype) * 255 + alpha_channel = ( + image[:, :, 3] + if image.shape[2] == 4 + else np.ones((rect.height, rect.width), dtype=image.dtype) * 255 + ) alpha_scaled = cv2.convertScaleAbs(alpha_channel * opacity) # Perform blending - scene_roi = scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] + scene_roi = scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] alpha_float = alpha_scaled.astype(np.float32) / 255.0 blended_roi = cv2.convertScaleAbs( - (1 - alpha_float[..., np.newaxis]) * scene_roi + alpha_float[ - ..., np.newaxis] * image[:, :, :3] + (1 - alpha_float[..., np.newaxis]) * scene_roi + + alpha_float[..., np.newaxis] * image[:, :, :3] ) # Update the scene - scene[rect.y:rect.y + rect.height, rect.x:rect.x + rect.width] = blended_roi + scene[rect.y : rect.y + rect.height, rect.x : rect.x + rect.width] = blended_roi return scene From a640e527d0c164b1f6d063186bddaf9865ae93cb Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Thu, 19 Oct 2023 00:41:13 +0200 Subject: [PATCH 49/53] Remove custom 404 page and update documentation for new release The custom 404.html was removed as it was no longer necessary with the updates to the Mkdocs.yml file. Upgraded the project version from 0.16.0rc2 to 0.16.0rc3 in the pyproject.toml file. Various updates were added to the changelog.md to reflect improvements and bug fixes in the new project release. This includes new annotations, utility improvements, and bug-fixes to improve project functionality. --- custom_theme/404.html | 7 ------- docs/changelog.md | 44 +++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 - pyproject.toml | 2 +- 4 files changed, 45 insertions(+), 9 deletions(-) delete mode 100644 custom_theme/404.html diff --git a/custom_theme/404.html b/custom_theme/404.html deleted file mode 100644 index 4ce71946..00000000 --- a/custom_theme/404.html +++ /dev/null @@ -1,7 +0,0 @@ -{% extends "main.html" %} - -{% block content %} -

Page Not Found

-

The page you have requested was not found.

-

Go back to the documentation home.

-{% endblock %} diff --git a/docs/changelog.md b/docs/changelog.md index 5c303b86..a3088393 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,3 +1,47 @@ +### 0.16.0 October 19, 2023 + +- Added [#422](https://github.com/roboflow/supervision/pull/422): [`sv.BoxMaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoxMaskAnnotator) allowing to annotate images and videos with mox masks. + +- Added [#433](https://github.com/roboflow/supervision/pull/433): [`sv.HaloAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.HaloAnnotator) allowing to annotate images and videos with halo effect. + +```python +>>> import supervision as sv + +>>> image = ... +>>> detections = sv.Detections(...) + +>>> halo_annotator = sv.HaloAnnotator() +>>> annotated_frame = halo_annotator.annotate( +... scene=image.copy(), +... detections=detections +... ) +``` + +- Added [#466](https://github.com/roboflow/supervision/pull/466): [`sv.HeatMapAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.HeatMapAnnotator) allowing to annotate videos with heat maps. + +- Added [#492](https://github.com/roboflow/supervision/pull/492): [`sv.DotAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.DotAnnotator) allowing to annotate images and videos with dots. + +- Added [#449](https://github.com/roboflow/supervision/pull/449): [`sv.draw_image`](https://supervision.roboflow.com/draw/utils/#supervision.draw.utils.draw_image) allowing to draw an image onto a given scene with specified opacity and dimensions. + +- Added [#280](https://github.com/roboflow/supervision/pull/280): [`sv.FPSMonitor`](https://supervision.roboflow.com/utils/video/#supervision.utils.video.FPSMonitor) for monitoring frames per second (FPS) to benchmark latency. + +- Added [#454](https://github.com/roboflow/supervision/pull/454): 🤗 Hugging Face Annotators [space](https://huggingface.co/spaces/Roboflow/Annotators). + +- Changed [#482](https://github.com/roboflow/supervision/pull/482): [`sv.LineZone.tigger`](https://supervision.roboflow.com/detection/tools/line_zone/#supervision.detection.line_counter.LineZone.trigger) now return `Tuple[np.ndarray, np.ndarray]`. The first array indicates which detections have crossed the line from outside to inside. The second array indicates which detections have crossed the line from inside to outside. + +- Changed [#465](https://github.com/roboflow/supervision/pull/465): Annotator argument name from `color_map: str` to `color_lookup: ColorLookup` enum to increase type safety. + +- Changed [#426](https://github.com/roboflow/supervision/pull/426): [`sv.MaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.MaskAnnotator) allowing 2x faster annotation. + +- Fixed [#477](https://github.com/roboflow/supervision/pull/477): Poetry env definition allowing proper local installation. + +- Fixed [#430](https://github.com/roboflow/supervision/pull/430): [`sv.ByteTrack`](https://supervision.roboflow.com/trackers/#supervision.tracker.byte_tracker.core.ByteTrack) to return `np.array([], dtype=int)` when `svDetections` is empty. + +!!! warning + + `sv.Detections.from_yolov8` and `sv.Classifications.from_yolov8` as those are now replaced by [`sv.Detections.from_ultralytics`](https://supervision.roboflow.com/detection/core/#supervision.detection.core.Detections.from_ultralytics) and [`sv.Classifications.from_ultralytics`](https://supervision.roboflow.com/classification/core/#supervision.classification.core.Classifications.from_ultralytics). + + ### 0.15.0 October 5, 2023 - Added [#170](https://github.com/roboflow/supervision/pull/170): [`sv.BoundingBoxAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoundingBoxAnnotator) allowing to annotate images and videos with bounding boxes. diff --git a/mkdocs.yml b/mkdocs.yml index 98d21dc4..6f0cbed4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -78,7 +78,6 @@ theme: font: text: Roboto code: Roboto Mono - custom_dir: 'custom_theme' plugins: - mkdocstrings diff --git a/pyproject.toml b/pyproject.toml index d78a50b7..95b5b242 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "supervision" -version = "0.16.0rc2" +version = "0.16.0rc3" description = "A set of easy-to-use utils that will come in handy in any Computer Vision project" authors = ["Piotr Skalski "] maintainers = ["Piotr Skalski "] From c1797ffd81fcb628cab6a099155f323f3395317e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Oct 2023 22:42:54 +0000 Subject: [PATCH 50/53] =?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/changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.md b/docs/changelog.md index a3088393..1039bb07 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,6 +1,6 @@ ### 0.16.0 October 19, 2023 -- Added [#422](https://github.com/roboflow/supervision/pull/422): [`sv.BoxMaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoxMaskAnnotator) allowing to annotate images and videos with mox masks. +- Added [#422](https://github.com/roboflow/supervision/pull/422): [`sv.BoxMaskAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.BoxMaskAnnotator) allowing to annotate images and videos with mox masks. - Added [#433](https://github.com/roboflow/supervision/pull/433): [`sv.HaloAnnotator`](https://supervision.roboflow.com/annotators/#supervision.annotators.core.HaloAnnotator) allowing to annotate images and videos with halo effect. From f44a9376ec1bc21ca9f05f57f78cdf4995e2bd1f Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Thu, 19 Oct 2023 10:22:38 +0200 Subject: [PATCH 51/53] Update version number in pyproject.toml Updated the version number in pyproject.toml from 0.16.0rc3 to 0.16.0. This denotes the transition from the release candidate to the official version. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 95b5b242..cd47f273 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "supervision" -version = "0.16.0rc3" +version = "0.16.0" description = "A set of easy-to-use utils that will come in handy in any Computer Vision project" authors = ["Piotr Skalski "] maintainers = ["Piotr Skalski "] From b815c0e7fc86702d8ac54daf639ac275379ae3d1 Mon Sep 17 00:00:00 2001 From: Onuralp SEZER Date: Sat, 21 Oct 2023 10:36:30 +0300 Subject: [PATCH 52/53] =?UTF-8?q?fix(notebook):=20=F0=9F=90=9B=F0=9F=93=98?= =?UTF-8?q?=20sam=20detection=20ColorLookup=20param=20and=20enum=20added?= =?UTF-8?q?=20and=20sv=20version=20updated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Onuralp SEZER --- demo.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/demo.ipynb b/demo.ipynb index 11abb584..9c06b62c 100644 --- a/demo.ipynb +++ b/demo.ipynb @@ -226,7 +226,7 @@ "output_type": "stream", "text": [ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/45.4 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m45.4/45.4 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", - "\u001b[?25h0.15.0\n" + "\u001b[?25h0.16.0\n" ] } ], @@ -540,7 +540,7 @@ } ], "source": [ - "mask_annotator = sv.MaskAnnotator(color_map=\"index\")\n", + "mask_annotator = sv.MaskAnnotator(color_lookup=sv.ColorLookup.INDEX)\n", "\n", "annotated_image = mask_annotator.annotate(image.copy(), detections=detections)\n", "\n", From 8bf721559f7eebb6a2c8ce0f2cc2c4e7eec3c74e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 23 Oct 2023 17:44:59 +0000 Subject: [PATCH 53/53] =?UTF-8?q?chore(pre=5Fcommit):=20=E2=AC=86=20pre=5F?= =?UTF-8?q?commit=20autoupdate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/psf/black: 23.9.1 → 23.10.0](https://github.com/psf/black/compare/23.9.1...23.10.0) - [github.com/astral-sh/ruff-pre-commit: v0.0.292 → v0.1.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.292...v0.1.1) --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2e0b0ede..2853b370 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -65,12 +65,12 @@ repos: - repo: https://github.com/psf/black - rev: 23.9.1 + rev: 23.10.0 hooks: - id: black - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.292 + rev: v0.1.1 hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix]