From e30d4a9abbd97253312e3f95f9664b7c16e74c16 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Thu, 2 May 2024 12:49:31 +0200 Subject: [PATCH 01/51] add test for generating annotation with mask --- test/dataset/formats/test_coco.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 62d1b75b..40d686db 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -1,5 +1,5 @@ from contextlib import ExitStack as DoesNotRaise -from typing import Dict, List, Tuple +from typing import Dict, List, Tuple, Union import numpy as np import pytest @@ -20,6 +20,8 @@ def mock_cock_coco_annotation( category_id: int = 0, bbox: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0), area: float = 0.0, + segmentation: List[list] = None, + iscrowd: bool = False, ) -> dict: return { "id": annotation_id, @@ -27,7 +29,8 @@ def mock_cock_coco_annotation( "category_id": category_id, "bbox": list(bbox), "area": area, - "iscrowd": 0, + "segmentation": segmentation, + "iscrowd": int(iscrowd), } @@ -226,6 +229,21 @@ def test_group_coco_annotations_by_image_id( ), DoesNotRaise(), ), # two image annotations + ( + [ + mock_cock_coco_annotation( + category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 0,9, 9,9, 9,0]], + ) + ], + (20, 20), + True, + Detections( + xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask = np.array([np.fromfunction(lambda i, j:np.bitwise_and(i<10, j<10), (20, 20), dtype=int)]) + ), + DoesNotRaise(), + ), # single image annotations with mask, segmentation mask outlines 10x10 square ], ) def test_coco_annotations_to_detections( From cc5e72dd5b9113abc922ef00f0133a5a6b61f67f Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Thu, 2 May 2024 22:08:08 +0200 Subject: [PATCH 02/51] test for RLE format --- test/dataset/formats/test_coco.py | 33 +++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 40d686db..5055a859 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -229,10 +229,10 @@ def test_group_coco_annotations_by_image_id( ), DoesNotRaise(), ), # two image annotations - ( + ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 0,9, 9,9, 9,0]], + category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]], ) ], (20, 20), @@ -240,10 +240,35 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask = np.array([np.fromfunction(lambda i, j:np.bitwise_and(i<10, j<10), (20, 20), dtype=int)]) + mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) ), DoesNotRaise(), - ), # single image annotations with mask, segmentation mask outlines 10x10 square + ), # single image annotations with mask, segmentation mask in L-like shape, like below: + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 + ( + [ + mock_cock_coco_annotation( + category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, + segmentation = {'size':[20,20], 'counts':[0, 5, 20, 5, 40, 5, 60, 5, 80, 5, 100, 10, 120, 10, 140, 10, 160, 10, 180, 10]}, iscrowd = True + ) + ], + (20, 20), + True, + Detections( + xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) + ), + DoesNotRaise(), + ), # single image annotations with mask, RLE encoded segmentation mask in L-like shape, like below: + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 + ], ) def test_coco_annotations_to_detections( From 7f114cba4c13d621ce86177db1fdbbfa2d4575a2 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 3 May 2024 00:24:46 +0200 Subject: [PATCH 03/51] RLE decoding --- supervision/dataset/formats/coco.py | 33 +++++++++++++++++++++++++---- supervision/detection/utils.py | 10 +++++++++ test/dataset/formats/test_coco.py | 2 +- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 4f8679d5..4105f86e 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -11,7 +11,7 @@ from supervision.dataset.utils import ( map_detections_class_id, ) from supervision.detection.core import Detections -from supervision.detection.utils import polygon_to_mask +from supervision.detection.utils import polygon_to_mask, rle_to_mask from supervision.utils.file import read_json_file, save_json_file @@ -68,6 +68,26 @@ def _polygons_to_masks( dtype=bool, ) +def _rles_to_masks( + rles: List[np.ndarray], resolution_wh: Tuple[int, int] +) -> np.ndarray: + return np.array( + [ + rle_to_mask(rle=rle, resolution_wh=resolution_wh) + for rle in rles + ], + dtype=bool, + ) + +def _concatenate_annotation_masks(mask_polygon, mask_rle): + if mask_polygon.ndim == 3 and mask_rle.ndim == 3: + return np.concatenate((mask_polygon, mask_rle)) + elif mask_polygon.ndim == 3: + return mask_polygon + elif mask_rle.ndim == 3: + return mask_rle + else: + None def coco_annotations_to_detections( image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool @@ -87,11 +107,16 @@ def coco_annotations_to_detections( np.reshape( np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2) ) - for image_annotation in image_annotations + for image_annotation in image_annotations if not image_annotation["iscrowd"] ] - mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + mask_polygon = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + + rles = [np.array(image_annotation["segmentation"]["counts"]) + for image_annotation in image_annotations if image_annotation["iscrowd"]] + mask_rle = _rles_to_masks(rles = rles, resolution_wh = resolution_wh) + return Detections( - class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask + class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=_concatenate_annotation_masks(mask_polygon=mask_polygon, mask_rle=mask_rle) ) return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 3eeba5b4..2b6f7d63 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -766,3 +766,13 @@ def get_data_item( raise TypeError(f"Unsupported data type for key '{key}': {type(value)}") return subset_data + + +def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: + width, height = resolution_wh + + zero_one_values = np.zeros_like(rle) + zero_one_values[1::2]=1 + + decoded_rle = np.repeat(zero_one_values, rle) + return decoded_rle.reshape((height,width), order='F') diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 5055a859..7254c9a9 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -252,7 +252,7 @@ def test_group_coco_annotations_by_image_id( [ mock_cock_coco_annotation( category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, - segmentation = {'size':[20,20], 'counts':[0, 5, 20, 5, 40, 5, 60, 5, 80, 5, 100, 10, 120, 10, 140, 10, 160, 10, 180, 10]}, iscrowd = True + segmentation = {'size':[20,20], 'counts':[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15, 5, 15, 5, 15, 5, 15, 5, 15, 5, 210]}, iscrowd = True ) ], (20, 20), From 6913ecf54d59ba270c2efa69586c15e9ac5729fb Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 3 May 2024 01:19:01 +0200 Subject: [PATCH 04/51] 2 annotations with segmentation, one polygon one RLE --- test/dataset/formats/test_coco.py | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 7254c9a9..ef627e89 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -263,12 +263,41 @@ def test_group_coco_annotations_by_image_id( mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) ), DoesNotRaise(), - ), # single image annotations with mask, RLE encoded segmentation mask in L-like shape, like below: + ), # single image annotations with mask, RLE segmentation mask in L-like shape, like below: # 1 0 0 0 # 1 1 0 0 # 0 0 0 0 # 0 0 0 0 + ( + [ + mock_cock_coco_annotation( + category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]] + ), + mock_cock_coco_annotation( + category_id=0, bbox=(5, 0, 5, 5), area=5 * 5, + segmentation = {'size':[20,20], 'counts':[100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215]}, iscrowd = True + ), + ], + (20, 20), + True, + Detections( + xyxy=np.array( + [[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32 + ), + class_id=np.array([0, 0], dtype=int), + mask = np.array([ + np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), + np.array([1 if j>4 and j<10 and i<5 else 0 for i in range(0,20) for j in range(0,20)]).reshape((20,20)) + ]) + ), + DoesNotRaise(), + ), # two image annotations with mask, one mask as polygon in in L-like shape, second as RLE in shape of square, like below (P = polygon, R = RLE): + # P R 0 0 + # P P 0 0 + # 0 0 0 0 + # 0 0 0 0 + ], ) def test_coco_annotations_to_detections( From 4a068ff8d7cf71f1e32e8e168e10f5539643a20d Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 3 May 2024 09:16:13 +0200 Subject: [PATCH 05/51] binary mask to RL encoding --- supervision/detection/utils.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 2b6f7d63..a915972a 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -1,4 +1,4 @@ -from itertools import chain +from itertools import chain, groupby from typing import Dict, List, Optional, Tuple, Union import cv2 @@ -776,3 +776,12 @@ def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: decoded_rle = np.repeat(zero_one_values, rle) return decoded_rle.reshape((height,width), order='F') + +def mask_to_rle(binary_mask: np.ndarray) -> list: + rle = [] + for _, group in groupby(binary_mask.ravel(order='F')): + rle.append(len(list(group))) + + if binary_mask[0][0] == 1: + rle = [0]+rle + return rle \ No newline at end of file From dc1ce02860e4c4ee7aab3522268391ed7353f652 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 3 May 2024 23:40:10 +0200 Subject: [PATCH 06/51] move rle encode decode functions to dataset/utils.py --- supervision/dataset/formats/coco.py | 14 +++++++++----- supervision/dataset/utils.py | 20 ++++++++++++++++++++ supervision/detection/utils.py | 21 +-------------------- 3 files changed, 30 insertions(+), 25 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 4105f86e..d29f3ade 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -9,9 +9,11 @@ import numpy as np from supervision.dataset.utils import ( approximate_mask_with_polygons, map_detections_class_id, + rle_to_mask, + mask_to_rle, ) from supervision.detection.core import Detections -from supervision.detection.utils import polygon_to_mask, rle_to_mask +from supervision.detection.utils import polygon_to_mask from supervision.utils.file import read_json_file, save_json_file @@ -133,9 +135,9 @@ def detections_to_coco_annotations( coco_annotations = [] for xyxy, mask, _, class_id, _, _ in detections: box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] - polygon = [] + segmentation = [] if mask is not None: - polygon = list( + segmentation = list( approximate_mask_with_polygons( mask=mask, min_image_area_percentage=min_image_area_percentage, @@ -143,14 +145,16 @@ def detections_to_coco_annotations( approximation_percentage=approximation_percentage, )[0].flatten() ) + # todo: flag for when to use RLE? + # segmentation = {"counts": mask_to_rle(binary_mask=mask), "size": list(mask.shape[:2])} coco_annotation = { "id": annotation_id, "image_id": image_id, "category_id": int(class_id), "bbox": [xyxy[0], xyxy[1], box_width, box_height], "area": box_width * box_height, - "segmentation": [polygon] if polygon else [], - "iscrowd": 0, + "segmentation": [segmentation] if segmentation else [], + "iscrowd": 0, ## todo: iscrowd depends on flag 1 if RLE 0 if polygon } coco_annotations.append(coco_annotation) annotation_id += 1 diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 05ee3201..d46aa45b 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -3,6 +3,8 @@ import os import random from pathlib import Path from typing import Dict, List, Optional, Tuple, TypeVar +from itertools import groupby + import cv2 import numpy as np @@ -129,3 +131,21 @@ def train_test_split( split_index = int(len(data) * train_ratio) return data[:split_index], data[split_index:] + +def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: + width, height = resolution_wh + + zero_one_values = np.zeros_like(rle) + zero_one_values[1::2]=1 + + decoded_rle = np.repeat(zero_one_values, rle) + return decoded_rle.reshape((height,width), order='F') + +def mask_to_rle(binary_mask: np.ndarray) -> list: + rle = [] + for _, group in groupby(binary_mask.ravel(order='F')): + rle.append(len(list(group))) + + if binary_mask[0][0] == 1: + rle = [0]+rle + return rle diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index a915972a..3eeba5b4 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -1,4 +1,4 @@ -from itertools import chain, groupby +from itertools import chain from typing import Dict, List, Optional, Tuple, Union import cv2 @@ -766,22 +766,3 @@ def get_data_item( raise TypeError(f"Unsupported data type for key '{key}': {type(value)}") return subset_data - - -def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: - width, height = resolution_wh - - zero_one_values = np.zeros_like(rle) - zero_one_values[1::2]=1 - - decoded_rle = np.repeat(zero_one_values, rle) - return decoded_rle.reshape((height,width), order='F') - -def mask_to_rle(binary_mask: np.ndarray) -> list: - rle = [] - for _, group in groupby(binary_mask.ravel(order='F')): - rle.append(len(list(group))) - - if binary_mask[0][0] == 1: - rle = [0]+rle - return rle \ No newline at end of file From 869204d42debc065c512dd02a5e731307276d2df Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 5 May 2024 11:59:20 +0000 Subject: [PATCH 07/51] =?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/dataset/formats/coco.py | 33 +++++--- supervision/dataset/utils.py | 15 ++-- test/dataset/formats/test_coco.py | 122 +++++++++++++++++++++------- 3 files changed, 121 insertions(+), 49 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index d29f3ade..9b7e534a 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -10,7 +10,6 @@ from supervision.dataset.utils import ( approximate_mask_with_polygons, map_detections_class_id, rle_to_mask, - mask_to_rle, ) from supervision.detection.core import Detections from supervision.detection.utils import polygon_to_mask @@ -70,17 +69,16 @@ def _polygons_to_masks( dtype=bool, ) + def _rles_to_masks( - rles: List[np.ndarray], resolution_wh: Tuple[int, int] + rles: List[np.ndarray], resolution_wh: Tuple[int, int] ) -> np.ndarray: return np.array( - [ - rle_to_mask(rle=rle, resolution_wh=resolution_wh) - for rle in rles - ], + [rle_to_mask(rle=rle, resolution_wh=resolution_wh) for rle in rles], dtype=bool, ) + def _concatenate_annotation_masks(mask_polygon, mask_rle): if mask_polygon.ndim == 3 and mask_rle.ndim == 3: return np.concatenate((mask_polygon, mask_rle)) @@ -91,6 +89,7 @@ def _concatenate_annotation_masks(mask_polygon, mask_rle): else: None + def coco_annotations_to_detections( image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool ) -> Detections: @@ -109,16 +108,26 @@ def coco_annotations_to_detections( np.reshape( np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2) ) - for image_annotation in image_annotations if not image_annotation["iscrowd"] + for image_annotation in image_annotations + if not image_annotation["iscrowd"] ] - mask_polygon = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + mask_polygon = _polygons_to_masks( + polygons=polygons, resolution_wh=resolution_wh + ) - rles = [np.array(image_annotation["segmentation"]["counts"]) - for image_annotation in image_annotations if image_annotation["iscrowd"]] - mask_rle = _rles_to_masks(rles = rles, resolution_wh = resolution_wh) + rles = [ + np.array(image_annotation["segmentation"]["counts"]) + for image_annotation in image_annotations + if image_annotation["iscrowd"] + ] + mask_rle = _rles_to_masks(rles=rles, resolution_wh=resolution_wh) return Detections( - class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=_concatenate_annotation_masks(mask_polygon=mask_polygon, mask_rle=mask_rle) + class_id=np.asarray(class_ids, dtype=int), + xyxy=xyxy, + mask=_concatenate_annotation_masks( + mask_polygon=mask_polygon, mask_rle=mask_rle + ), ) return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index d46aa45b..ef30aa48 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -1,10 +1,9 @@ import copy import os import random +from itertools import groupby from pathlib import Path from typing import Dict, List, Optional, Tuple, TypeVar -from itertools import groupby - import cv2 import numpy as np @@ -132,20 +131,22 @@ def train_test_split( split_index = int(len(data) * train_ratio) return data[:split_index], data[split_index:] + def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: width, height = resolution_wh - + zero_one_values = np.zeros_like(rle) - zero_one_values[1::2]=1 + zero_one_values[1::2] = 1 decoded_rle = np.repeat(zero_one_values, rle) - return decoded_rle.reshape((height,width), order='F') + return decoded_rle.reshape((height, width), order="F") + def mask_to_rle(binary_mask: np.ndarray) -> list: rle = [] - for _, group in groupby(binary_mask.ravel(order='F')): + for _, group in groupby(binary_mask.ravel(order="F")): rle.append(len(list(group))) if binary_mask[0][0] == 1: - rle = [0]+rle + rle = [0] + rle return rle diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index ef627e89..bfde080d 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -1,5 +1,5 @@ from contextlib import ExitStack as DoesNotRaise -from typing import Dict, List, Tuple, Union +from typing import Dict, List, Tuple import numpy as np import pytest @@ -232,7 +232,10 @@ def test_group_coco_annotations_by_image_id( ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]], + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], ) ], (20, 20), @@ -240,19 +243,53 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) + mask=np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((1, 20, 20)), ), DoesNotRaise(), ), # single image annotations with mask, segmentation mask in L-like shape, like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, - segmentation = {'size':[20,20], 'counts':[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15, 5, 15, 5, 15, 5, 15, 5, 15, 5, 210]}, iscrowd = True + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation={ + "size": [20, 20], + "counts": [ + 0, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 15, + 5, + 15, + 5, + 15, + 5, + 15, + 5, + 15, + 5, + 210, + ], + }, + iscrowd=True, ) ], (20, 20), @@ -260,44 +297,69 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) + mask=np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((1, 20, 20)), ), DoesNotRaise(), ), # single image annotations with mask, RLE segmentation mask in L-like shape, like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 - + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]] + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], ), mock_cock_coco_annotation( - category_id=0, bbox=(5, 0, 5, 5), area=5 * 5, - segmentation = {'size':[20,20], 'counts':[100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215]}, iscrowd = True + category_id=0, + bbox=(5, 0, 5, 5), + area=5 * 5, + segmentation={ + "size": [20, 20], + "counts": [100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215], + }, + iscrowd=True, ), ], (20, 20), True, Detections( - xyxy=np.array( - [[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32 - ), + xyxy=np.array([[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32), class_id=np.array([0, 0], dtype=int), - mask = np.array([ - np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), - np.array([1 if j>4 and j<10 and i<5 else 0 for i in range(0,20) for j in range(0,20)]).reshape((20,20)) - ]) + mask=np.array( + [ + np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + np.array( + [ + 1 if j > 4 and j < 10 and i < 5 else 0 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + ] + ), ), DoesNotRaise(), ), # two image annotations with mask, one mask as polygon in in L-like shape, second as RLE in shape of square, like below (P = polygon, R = RLE): - # P R 0 0 - # P P 0 0 - # 0 0 0 0 - # 0 0 0 0 - + # P R 0 0 + # P P 0 0 + # 0 0 0 0 + # 0 0 0 0 ], ) def test_coco_annotations_to_detections( From 18a790e9ea4160d6ab1c2f9a08f62e14ab458784 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 6 May 2024 20:21:02 +0200 Subject: [PATCH 08/51] typing chanches and doc strings for rle_to_mask and mask_to_rle functions --- supervision/dataset/utils.py | 48 ++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index d46aa45b..1cd038ec 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -8,6 +8,7 @@ from itertools import groupby import cv2 import numpy as np +import numpy.typing as npt from supervision.detection.core import Detections from supervision.detection.utils import ( @@ -132,7 +133,24 @@ def train_test_split( split_index = int(len(data) * train_ratio) return data[:split_index], data[split_index:] -def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: +def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> npt.NDArray[np.bool_]: + """ + Converts run-length encoding (RLE) to a binary mask. + + Args: + rle (np.ndarray): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, + values of an array with even indices represent the number of pixels assigned as background, + values of an array with odd indices represent the number of pixels assigned as foreground object). + resolution_wh (Tuple[int, int]): The width (w) and height (h) of the desired binary mask resolution. + + Returns: + npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), where the foreground object + is marked with `True`'s and the rest is filled with `False`'s. + + Examples: + rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], + [False, True, False]] + """ width, height = resolution_wh zero_one_values = np.zeros_like(rle) @@ -141,11 +159,31 @@ def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: decoded_rle = np.repeat(zero_one_values, rle) return decoded_rle.reshape((height,width), order='F') -def mask_to_rle(binary_mask: np.ndarray) -> list: +def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: + """ + Converts a binary mask into a run-length encoding (RLE). + + Args: + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object + and `False` indicates background. + + Returns: + List[int]: the run-length encoded mask. Values of a list with even indices represent the number of pixels assigned as background (`False`), + values of a list with odd indices represent the number of pixels assigned as foreground object (`True`). + + Examples: + mask = [[False, True, True], -> rle = [2, 4] + [False, True, True]] + + mask = [[True, True, True], -> rle = [0, 6] + [True, True, True]] + """ rle = [] - for _, group in groupby(binary_mask.ravel(order='F')): + + if mask[0][0] == 1: + rle = [0] + + for _, group in groupby(mask.ravel(order='F')): rle.append(len(list(group))) - if binary_mask[0][0] == 1: - rle = [0]+rle return rle From 3ade7f060a2db171f89494bc687c6255cca70f87 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 6 May 2024 22:42:26 +0200 Subject: [PATCH 09/51] fix order caused error with mask generation in coco_annotations_to_detections --- supervision/dataset/formats/coco.py | 48 +++++----------------- test/dataset/formats/test_coco.py | 63 +++++++++++++++++++++++++---- 2 files changed, 66 insertions(+), 45 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index d29f3ade..c8f7cd04 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -59,37 +59,20 @@ def group_coco_annotations_by_image_id( return annotations -def _polygons_to_masks( - polygons: List[np.ndarray], resolution_wh: Tuple[int, int] -) -> np.ndarray: +def _annotations_to_mask(image_annotations: List[dict], resolution_wh: Tuple[int, int]): return np.array( [ - polygon_to_mask(polygon=polygon, resolution_wh=resolution_wh) - for polygon in polygons + rle_to_mask(rle=np.array(image_annotation["segmentation"]["counts"]), + resolution_wh=resolution_wh) + if image_annotation["iscrowd"] + else + polygon_to_mask(polygon= np.reshape(np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2)), + resolution_wh=resolution_wh) + for image_annotation in image_annotations ], dtype=bool, ) -def _rles_to_masks( - rles: List[np.ndarray], resolution_wh: Tuple[int, int] -) -> np.ndarray: - return np.array( - [ - rle_to_mask(rle=rle, resolution_wh=resolution_wh) - for rle in rles - ], - dtype=bool, - ) - -def _concatenate_annotation_masks(mask_polygon, mask_rle): - if mask_polygon.ndim == 3 and mask_rle.ndim == 3: - return np.concatenate((mask_polygon, mask_rle)) - elif mask_polygon.ndim == 3: - return mask_polygon - elif mask_rle.ndim == 3: - return mask_rle - else: - None def coco_annotations_to_detections( image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool @@ -105,20 +88,9 @@ def coco_annotations_to_detections( xyxy[:, 2:4] += xyxy[:, 0:2] if with_masks: - polygons = [ - np.reshape( - np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2) - ) - for image_annotation in image_annotations if not image_annotation["iscrowd"] - ] - mask_polygon = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) - - rles = [np.array(image_annotation["segmentation"]["counts"]) - for image_annotation in image_annotations if image_annotation["iscrowd"]] - mask_rle = _rles_to_masks(rles = rles, resolution_wh = resolution_wh) - + mask = _annotations_to_mask(image_annotations, resolution_wh) return Detections( - class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=_concatenate_annotation_masks(mask_polygon=mask_polygon, mask_rle=mask_rle) + class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask ) return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index ef627e89..610b9350 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -268,31 +268,80 @@ def test_group_coco_annotations_by_image_id( # 1 1 0 0 # 0 0 0 0 # 0 0 0 0 + ( + [ + mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], + ), + mock_cock_coco_annotation( + category_id=0, + bbox=(5, 0, 5, 5), + area=5 * 5, + segmentation={ + "size": [20, 20], + "counts": [100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215], + }, + iscrowd=True, + ), + ], + (20, 20), + True, + Detections( + xyxy=np.array([[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32), + class_id=np.array([0, 0], dtype=int), + mask=np.array( + [ + np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + np.array( + [ + 1 if j > 4 and j < 10 and i < 5 else 0 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + ] + ), + ), + DoesNotRaise(), + ), # two image annotations with mask, one mask as polygon in in L-like shape, second as RLE in shape of square, like below (P = polygon, R = RLE): + # P R 0 0 + # P P 0 0 + # 0 0 0 0 + # 0 0 0 0 ( [ - mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]] - ), mock_cock_coco_annotation( category_id=0, bbox=(5, 0, 5, 5), area=5 * 5, segmentation = {'size':[20,20], 'counts':[100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215]}, iscrowd = True ), + mock_cock_coco_annotation( + category_id=1, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]] + ), ], (20, 20), True, Detections( xyxy=np.array( - [[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32 + [[5, 0, 10, 5], [0, 0, 10, 10]], dtype=np.float32 ), - class_id=np.array([0, 0], dtype=int), + class_id=np.array([0, 1], dtype=int), mask = np.array([ + np.array([1 if j>4 and j<10 and i<5 else 0 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), - np.array([1 if j>4 and j<10 and i<5 else 0 for i in range(0,20) for j in range(0,20)]).reshape((20,20)) ]) ), DoesNotRaise(), - ), # two image annotations with mask, one mask as polygon in in L-like shape, second as RLE in shape of square, like below (P = polygon, R = RLE): + ), # two image annotations with mask, first mask as RLE in shape of square, second as polygon in in L-like shape, like below (P = polygon, R = RLE): # P R 0 0 # P P 0 0 # 0 0 0 0 From a941583bb0354de5b87ad1167e2b02198da11dd1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 21:07:49 +0000 Subject: [PATCH 10/51] =?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/dataset/formats/coco.py | 18 ++-- supervision/dataset/utils.py | 20 +++-- test/dataset/formats/test_coco.py | 122 +++++++++++++++++++++------- 3 files changed, 115 insertions(+), 45 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 34cb84ce..febeb8d6 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -61,12 +61,18 @@ def group_coco_annotations_by_image_id( def _annotations_to_mask(image_annotations: List[dict], resolution_wh: Tuple[int, int]): return np.array( [ - rle_to_mask(rle=np.array(image_annotation["segmentation"]["counts"]), - resolution_wh=resolution_wh) - if image_annotation["iscrowd"] - else - polygon_to_mask(polygon= np.reshape(np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2)), - resolution_wh=resolution_wh) + rle_to_mask( + rle=np.array(image_annotation["segmentation"]["counts"]), + resolution_wh=resolution_wh, + ) + if image_annotation["iscrowd"] + else polygon_to_mask( + polygon=np.reshape( + np.asarray(image_annotation["segmentation"], dtype=np.int32), + (-1, 2), + ), + resolution_wh=resolution_wh, + ) for image_annotation in image_annotations ], dtype=bool, diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index d1981bfe..de2511e5 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -133,22 +133,24 @@ def train_test_split( return data[:split_index], data[split_index:] -def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> npt.NDArray[np.bool_]: +def rle_to_mask( + rle: np.ndarray, resolution_wh: Tuple[int, int] +) -> npt.NDArray[np.bool_]: """ Converts run-length encoding (RLE) to a binary mask. Args: - rle (np.ndarray): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, + rle (np.ndarray): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, values of an array with even indices represent the number of pixels assigned as background, values of an array with odd indices represent the number of pixels assigned as foreground object). resolution_wh (Tuple[int, int]): The width (w) and height (h) of the desired binary mask resolution. Returns: - npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), where the foreground object - is marked with `True`'s and the rest is filled with `False`'s. + npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), where the foreground object + is marked with `True`'s and the rest is filled with `False`'s. Examples: - rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], + rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], [False, True, False]] """ width, height = resolution_wh @@ -157,7 +159,7 @@ def rle_to_mask(rle: np.ndarray, resolution_wh: Tuple[int, int]) -> npt.NDArray[ zero_one_values[1::2] = 1 decoded_rle = np.repeat(zero_one_values, rle) - return decoded_rle.reshape((height,width), order="F") + return decoded_rle.reshape((height, width), order="F") def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: @@ -165,7 +167,7 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: Converts a binary mask into a run-length encoding (RLE). Args: - mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object and `False` indicates background. Returns: @@ -174,10 +176,10 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: Examples: mask = [[False, True, True], -> rle = [2, 4] - [False, True, True]] + [False, True, True]] mask = [[True, True, True], -> rle = [0, 6] - [True, True, True]] + [True, True, True]] """ rle = [] if mask[0][0] == 1: diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 610b9350..bb4a6e64 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -1,5 +1,5 @@ from contextlib import ExitStack as DoesNotRaise -from typing import Dict, List, Tuple, Union +from typing import Dict, List, Tuple import numpy as np import pytest @@ -232,7 +232,10 @@ def test_group_coco_annotations_by_image_id( ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]], + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], ) ], (20, 20), @@ -240,19 +243,53 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) + mask=np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((1, 20, 20)), ), DoesNotRaise(), ), # single image annotations with mask, segmentation mask in L-like shape, like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 ( [ mock_cock_coco_annotation( - category_id=0, bbox=(0, 0, 10, 10), area=10 * 10, - segmentation = {'size':[20,20], 'counts':[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15, 5, 15, 5, 15, 5, 15, 5, 15, 5, 210]}, iscrowd = True + category_id=0, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation={ + "size": [20, 20], + "counts": [ + 0, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 15, + 5, + 15, + 5, + 15, + 5, + 15, + 5, + 15, + 5, + 210, + ], + }, + iscrowd=True, ) ], (20, 20), @@ -260,14 +297,20 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask = np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((1,20,20)) + mask=np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((1, 20, 20)), ), DoesNotRaise(), ), # single image annotations with mask, RLE segmentation mask in L-like shape, like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 + # 1 0 0 0 + # 1 1 0 0 + # 0 0 0 0 + # 0 0 0 0 ( [ mock_cock_coco_annotation( @@ -317,36 +360,55 @@ def test_group_coco_annotations_by_image_id( # P P 0 0 # 0 0 0 0 # 0 0 0 0 - ( [ mock_cock_coco_annotation( - category_id=0, bbox=(5, 0, 5, 5), area=5 * 5, - segmentation = {'size':[20,20], 'counts':[100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215]}, iscrowd = True + category_id=0, + bbox=(5, 0, 5, 5), + area=5 * 5, + segmentation={ + "size": [20, 20], + "counts": [100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215], + }, + iscrowd=True, ), mock_cock_coco_annotation( - category_id=1, bbox=(0, 0, 10, 10), area=10 * 10, segmentation = [[0,0, 4,0, 4,5, 9,5, 9,9, 0,9]] + category_id=1, + bbox=(0, 0, 10, 10), + area=10 * 10, + segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], ), ], (20, 20), True, Detections( - xyxy=np.array( - [[5, 0, 10, 5], [0, 0, 10, 10]], dtype=np.float32 - ), + xyxy=np.array([[5, 0, 10, 5], [0, 0, 10, 10]], dtype=np.float32), class_id=np.array([0, 1], dtype=int), - mask = np.array([ - np.array([1 if j>4 and j<10 and i<5 else 0 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), - np.array([0 if i>=10 or j>=10 or (i<5 and j >=5) else 1 for i in range(0,20) for j in range(0,20)]).reshape((20,20)), - ]) + mask=np.array( + [ + np.array( + [ + 1 if j > 4 and j < 10 and i < 5 else 0 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + np.array( + [ + 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 + for i in range(0, 20) + for j in range(0, 20) + ] + ).reshape((20, 20)), + ] + ), ), DoesNotRaise(), ), # two image annotations with mask, first mask as RLE in shape of square, second as polygon in in L-like shape, like below (P = polygon, R = RLE): - # P R 0 0 - # P P 0 0 - # 0 0 0 0 - # 0 0 0 0 - + # P R 0 0 + # P P 0 0 + # 0 0 0 0 + # 0 0 0 0 ], ) def test_coco_annotations_to_detections( From 88a43cc795c840b57beb0d159b1bcbd9a9bc1259 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Tue, 7 May 2024 00:22:24 +0200 Subject: [PATCH 11/51] unit tests for rle_to_mask and mask_to_rle functions --- supervision/dataset/utils.py | 4 +- test/dataset/test_utils.py | 98 ++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index de2511e5..53593a35 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -134,13 +134,13 @@ def train_test_split( def rle_to_mask( - rle: np.ndarray, resolution_wh: Tuple[int, int] + rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]: """ Converts run-length encoding (RLE) to a binary mask. Args: - rle (np.ndarray): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, + rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, values of an array with even indices represent the number of pixels assigned as background, values of an array with odd indices represent the number of pixels assigned as foreground object). resolution_wh (Tuple[int, int]): The width (w) and height (h) of the desired binary mask resolution. diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index 5ca96ca5..9cefa438 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -2,6 +2,8 @@ from contextlib import ExitStack as DoesNotRaise from test.test_utils import mock_detections from typing import Dict, List, Optional, Tuple, TypeVar +import numpy as np +import numpy.typing as npt import pytest from supervision import Detections @@ -10,6 +12,8 @@ from supervision.dataset.utils import ( map_detections_class_id, merge_class_lists, train_test_split, + mask_to_rle, + rle_to_mask, ) T = TypeVar("T") @@ -229,3 +233,97 @@ def test_map_detections_class_id( source_to_target_mapping=source_to_target_mapping, detections=detections ) assert result == expected_result + + +@pytest.mark.parametrize( + "mask, expected_rle, exception", + [ + ( + np.zeros((3,3)).astype(bool), + [9], + DoesNotRaise(), + ), # mask with background only (mask with only False values) + ( + np.ones((3,3)).astype(bool), + [0, 9], + DoesNotRaise(), + ), # mask with foreground only (mask with only True values) + ( + np.array( + [[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + ).astype(bool), + [6, 3, 2, 1, 1, 1, 2, 3, 6], + DoesNotRaise(), + ), # mask where foreground object has hole + ( + np.array( + [[1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1]] + ).astype(bool), + [0, 5, 5, 5, 5, 5], + DoesNotRaise(), + ), # mask where foreground consists of 3 separate components + ], +) +def test_mask_to_rle_convertion( + mask: npt.NDArray[np.bool_], expected_rle: List[int], exception: Exception +) -> None: + with exception: + result = mask_to_rle(mask=mask) + assert result == expected_rle + + +@pytest.mark.parametrize( + "rle, resolution_wh, expected_mask, exception", + [ + ( + [9], + [3, 3], + np.zeros((3,3)).astype(bool), + DoesNotRaise(), + ), # mask with background only (mask with only False values) + ( + [0, 9], + [3, 3], + np.ones((3,3)).astype(bool), + DoesNotRaise(), + ), # mask with foreground only (mask with only True values) + ( + [6, 3, 2, 1, 1, 1, 2, 3, 6], + [5, 5], + np.array( + [[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + ).astype(bool), + DoesNotRaise(), + ), # mask where foreground object has hole + ( + [0, 5, 5, 5, 5, 5], + [5, 5], + np.array( + [[1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1]] + ).astype(bool), + DoesNotRaise(), + ), # mask where foreground consists of 3 separate components + ], +) +def test_rle_to_mask_convertion( + rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int],expected_mask: npt.NDArray[np.bool_], exception: Exception +) -> None: + with exception: + result = rle_to_mask(rle=rle, resolution_wh=resolution_wh) + assert np.all(result == expected_mask) From 6b5dacd8e3d4bfe8742c193d68fe4bbf235a7966 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 22:22:47 +0000 Subject: [PATCH 12/51] =?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 --- test/dataset/test_utils.py | 65 ++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index 9cefa438..58f2ec22 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -10,10 +10,10 @@ from supervision import Detections from supervision.dataset.utils import ( build_class_index_mapping, map_detections_class_id, - merge_class_lists, - train_test_split, mask_to_rle, + merge_class_lists, rle_to_mask, + train_test_split, ) T = TypeVar("T") @@ -239,33 +239,37 @@ def test_map_detections_class_id( "mask, expected_rle, exception", [ ( - np.zeros((3,3)).astype(bool), + np.zeros((3, 3)).astype(bool), [9], DoesNotRaise(), ), # mask with background only (mask with only False values) ( - np.ones((3,3)).astype(bool), + np.ones((3, 3)).astype(bool), [0, 9], DoesNotRaise(), ), # mask with foreground only (mask with only True values) ( np.array( - [[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 0, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 0]] + [ + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0], + ] ).astype(bool), [6, 3, 2, 1, 1, 1, 2, 3, 6], DoesNotRaise(), ), # mask where foreground object has hole ( np.array( - [[1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1]] + [ + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + ] ).astype(bool), [0, 5, 5, 5, 5, 5], DoesNotRaise(), @@ -286,24 +290,26 @@ def test_mask_to_rle_convertion( ( [9], [3, 3], - np.zeros((3,3)).astype(bool), + np.zeros((3, 3)).astype(bool), DoesNotRaise(), ), # mask with background only (mask with only False values) ( [0, 9], [3, 3], - np.ones((3,3)).astype(bool), + np.ones((3, 3)).astype(bool), DoesNotRaise(), ), # mask with foreground only (mask with only True values) ( [6, 3, 2, 1, 1, 1, 2, 3, 6], [5, 5], np.array( - [[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 0, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 0]] + [ + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0], + ] ).astype(bool), DoesNotRaise(), ), # mask where foreground object has hole @@ -311,18 +317,23 @@ def test_mask_to_rle_convertion( [0, 5, 5, 5, 5, 5], [5, 5], np.array( - [[1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1], - [1, 0, 1, 0, 1]] + [ + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + ] ).astype(bool), DoesNotRaise(), ), # mask where foreground consists of 3 separate components ], ) def test_rle_to_mask_convertion( - rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int],expected_mask: npt.NDArray[np.bool_], exception: Exception + rle: npt.NDArray[np.int_], + resolution_wh: Tuple[int, int], + expected_mask: npt.NDArray[np.bool_], + exception: Exception, ) -> None: with exception: result = rle_to_mask(rle=rle, resolution_wh=resolution_wh) From a9f821c28a98430972441fd14bfe80051bdc6631 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Tue, 7 May 2024 17:34:13 +0200 Subject: [PATCH 13/51] Assertion error when number of pixel in RLE does not match the nuber of pixels computed as width*height --- supervision/dataset/utils.py | 6 ++++++ test/dataset/test_utils.py | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 53593a35..96f6a54b 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -149,12 +149,18 @@ def rle_to_mask( npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), where the foreground object is marked with `True`'s and the rest is filled with `False`'s. + Raises: + AssertionError: If the sum of pixels encoded in RLE differs from the + number of pixels in the expected mask (computed based on resolution_wh). + Examples: rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], [False, True, False]] """ width, height = resolution_wh + assert width*height == np.sum(rle), "the sum of the number of pixels in the RLE must be the same as the number of pixels in the expected mask" + zero_one_values = np.zeros_like(rle) zero_one_values[1::2] = 1 diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index 9cefa438..d88e8349 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -272,7 +272,7 @@ def test_map_detections_class_id( ), # mask where foreground consists of 3 separate components ], ) -def test_mask_to_rle_convertion( +def test_mask_to_rle_conversion( mask: npt.NDArray[np.bool_], expected_rle: List[int], exception: Exception ) -> None: with exception: @@ -319,9 +319,15 @@ def test_mask_to_rle_convertion( ).astype(bool), DoesNotRaise(), ), # mask where foreground consists of 3 separate components + ( + [0, 5, 5, 5, 5, 5], + [5, 5], + None, + pytest.raises(AssertionError), + ), # mask where foreground consists of 3 separate components ], ) -def test_rle_to_mask_convertion( +def test_rle_to_mask_conversion( rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int],expected_mask: npt.NDArray[np.bool_], exception: Exception ) -> None: with exception: From d59ec0f2237616b188e1c30201904713385f9734 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 7 May 2024 15:36:45 +0000 Subject: [PATCH 14/51] =?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/dataset/utils.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 96f6a54b..0bb432f4 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -150,16 +150,18 @@ def rle_to_mask( is marked with `True`'s and the rest is filled with `False`'s. Raises: - AssertionError: If the sum of pixels encoded in RLE differs from the + AssertionError: If the sum of pixels encoded in RLE differs from the number of pixels in the expected mask (computed based on resolution_wh). - + Examples: rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], [False, True, False]] """ width, height = resolution_wh - assert width*height == np.sum(rle), "the sum of the number of pixels in the RLE must be the same as the number of pixels in the expected mask" + assert ( + width * height == np.sum(rle) + ), "the sum of the number of pixels in the RLE must be the same as the number of pixels in the expected mask" zero_one_values = np.zeros_like(rle) zero_one_values[1::2] = 1 From aac1d8862a35c8c1b741b224cf5db8fed64a3cec Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Tue, 7 May 2024 18:01:14 +0200 Subject: [PATCH 15/51] assertion for valid mask in mask_to_rle function --- supervision/dataset/utils.py | 6 ++++++ test/dataset/test_utils.py | 19 +++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 0bb432f4..0167dc39 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -182,6 +182,9 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: List[int]: the run-length encoded mask. Values of a list with even indices represent the number of pixels assigned as background (`False`), values of a list with odd indices represent the number of pixels assigned as foreground object (`True`). + Raises: + AssertionError: If imput mask is not 2D or is empty. + Examples: mask = [[False, True, True], -> rle = [2, 4] [False, True, True]] @@ -189,6 +192,9 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: mask = [[True, True, True], -> rle = [0, 6] [True, True, True]] """ + assert mask.ndim == 2, "Input mask must be 2D" + assert mask.size != 0, "Input mask cannot be empty" + rle = [] if mask[0][0] == 1: rle = [0] diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index b810f204..0bf8ecb4 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -274,6 +274,20 @@ def test_map_detections_class_id( [0, 5, 5, 5, 5, 5], DoesNotRaise(), ), # mask where foreground consists of 3 separate components + ( + np.array( + [[[]]] + ).astype(bool), + None, + pytest.raises(AssertionError), + ), # raises AssertionError because mask dimentionality is not 2D + ( + np.array( + [[]] + ).astype(bool), + None, + pytest.raises(AssertionError), + ), # raises AssertionError because mask is empty ], ) def test_mask_to_rle_conversion( @@ -329,10 +343,11 @@ def test_mask_to_rle_conversion( ), # mask where foreground consists of 3 separate components ( [0, 5, 5, 5, 5, 5], - [5, 5], + [2, 2], None, pytest.raises(AssertionError), - ), # mask where foreground consists of 3 separate components + ), # raises AssertionError because number of pixels in RLE does not match + # number of pixels in expected mask (width x height). ], ) def test_rle_to_mask_convertion( From 36a301e7fccbb1ffe78aef984046e70f56170279 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 7 May 2024 16:01:35 +0000 Subject: [PATCH 16/51] =?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 --- test/dataset/test_utils.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index 0bf8ecb4..e269dde7 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -275,19 +275,15 @@ def test_map_detections_class_id( DoesNotRaise(), ), # mask where foreground consists of 3 separate components ( - np.array( - [[[]]] - ).astype(bool), + np.array([[[]]]).astype(bool), None, pytest.raises(AssertionError), - ), # raises AssertionError because mask dimentionality is not 2D + ), # raises AssertionError because mask dimentionality is not 2D ( - np.array( - [[]] - ).astype(bool), + np.array([[]]).astype(bool), None, pytest.raises(AssertionError), - ), # raises AssertionError because mask is empty + ), # raises AssertionError because mask is empty ], ) def test_mask_to_rle_conversion( @@ -346,8 +342,8 @@ def test_mask_to_rle_conversion( [2, 2], None, pytest.raises(AssertionError), - ), # raises AssertionError because number of pixels in RLE does not match - # number of pixels in expected mask (width x height). + ), # raises AssertionError because number of pixels in RLE does not match + # number of pixels in expected mask (width x height). ], ) def test_rle_to_mask_convertion( From 649e27323dbd8c282cc14c245a48b4f27d372357 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Wed, 8 May 2024 12:49:25 +0200 Subject: [PATCH 17/51] fix the line lengths --- supervision/dataset/formats/coco.py | 3 ++- supervision/dataset/utils.py | 29 ++++++++++++++++++----------- test/dataset/formats/test_coco.py | 12 ++++++++---- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index febeb8d6..0489cd08 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -123,7 +123,8 @@ def detections_to_coco_annotations( )[0].flatten() ) # todo: flag for when to use RLE? - # segmentation = {"counts": mask_to_rle(binary_mask=mask), "size": list(mask.shape[:2])} + # segmentation = {"counts": mask_to_rle(binary_mask=mask), + # "size": list(mask.shape[:2])} coco_annotation = { "id": annotation_id, "image_id": image_id, diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 0167dc39..bd7d7b57 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -140,14 +140,18 @@ def rle_to_mask( Converts run-length encoding (RLE) to a binary mask. Args: - rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO dataset (column-wise encoding, - values of an array with even indices represent the number of pixels assigned as background, - values of an array with odd indices represent the number of pixels assigned as foreground object). - resolution_wh (Tuple[int, int]): The width (w) and height (h) of the desired binary mask resolution. + rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO + dataset (column-wise encoding, values of an array with even indices + represent the number of pixels assigned as background, + values of an array with odd indices represent the number of pixels + assigned as foreground object). + resolution_wh (Tuple[int, int]): The width (w) and height (h) + of the desired binary mask resolution. Returns: - npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), where the foreground object - is marked with `True`'s and the rest is filled with `False`'s. + npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), + where the foreground object is marked with `True`'s and the rest + is filled with `False`'s. Raises: AssertionError: If the sum of pixels encoded in RLE differs from the @@ -161,7 +165,8 @@ def rle_to_mask( assert ( width * height == np.sum(rle) - ), "the sum of the number of pixels in the RLE must be the same as the number of pixels in the expected mask" + ), ("the sum of the number of pixels in the RLE must be the same " + "as the number of pixels in the expected mask") zero_one_values = np.zeros_like(rle) zero_one_values[1::2] = 1 @@ -175,12 +180,14 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: Converts a binary mask into a run-length encoding (RLE). Args: - mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object - and `False` indicates background. + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground + object and `False` indicates background. Returns: - List[int]: the run-length encoded mask. Values of a list with even indices represent the number of pixels assigned as background (`False`), - values of a list with odd indices represent the number of pixels assigned as foreground object (`True`). + List[int]: the run-length encoded mask. Values of a list with even indices + represent the number of pixels assigned as background (`False`), values + of a list with odd indices represent the number of pixels assigned + as foreground object (`True`). Raises: AssertionError: If imput mask is not 2D or is empty. diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index bb4a6e64..12ff4f00 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -252,7 +252,8 @@ def test_group_coco_annotations_by_image_id( ).reshape((1, 20, 20)), ), DoesNotRaise(), - ), # single image annotations with mask, segmentation mask in L-like shape, like below: + ), # single image annotations with mask, segmentation mask in L-like shape, + # like below: # 1 0 0 0 # 1 1 0 0 # 0 0 0 0 @@ -306,7 +307,8 @@ def test_group_coco_annotations_by_image_id( ).reshape((1, 20, 20)), ), DoesNotRaise(), - ), # single image annotations with mask, RLE segmentation mask in L-like shape, like below: + ), # single image annotations with mask, RLE segmentation mask in L-like shape, + # like below: # 1 0 0 0 # 1 1 0 0 # 0 0 0 0 @@ -355,7 +357,8 @@ def test_group_coco_annotations_by_image_id( ), ), DoesNotRaise(), - ), # two image annotations with mask, one mask as polygon in in L-like shape, second as RLE in shape of square, like below (P = polygon, R = RLE): + ), # two image annotations with mask, one mask as polygon in in L-like shape, + # second as RLE in shape of square, like below (P = polygon, R = RLE): # P R 0 0 # P P 0 0 # 0 0 0 0 @@ -404,7 +407,8 @@ def test_group_coco_annotations_by_image_id( ), ), DoesNotRaise(), - ), # two image annotations with mask, first mask as RLE in shape of square, second as polygon in in L-like shape, like below (P = polygon, R = RLE): + ), # two image annotations with mask, first mask as RLE in shape of square, + # second as polygon in in L-like shape, like below (P = polygon, R = RLE): # P R 0 0 # P P 0 0 # 0 0 0 0 From 008711aac479453496b0ee9f7655d0b427670bdc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 8 May 2024 10:50:30 +0000 Subject: [PATCH 18/51] =?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/dataset/formats/coco.py | 2 +- supervision/dataset/utils.py | 28 ++++++++++++++-------------- test/dataset/formats/test_coco.py | 8 ++++---- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 0489cd08..4beb1dcd 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -123,7 +123,7 @@ def detections_to_coco_annotations( )[0].flatten() ) # todo: flag for when to use RLE? - # segmentation = {"counts": mask_to_rle(binary_mask=mask), + # segmentation = {"counts": mask_to_rle(binary_mask=mask), # "size": list(mask.shape[:2])} coco_annotation = { "id": annotation_id, diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index bd7d7b57..93242e2b 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -140,17 +140,17 @@ def rle_to_mask( Converts run-length encoding (RLE) to a binary mask. Args: - rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO - dataset (column-wise encoding, values of an array with even indices + rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO + dataset (column-wise encoding, values of an array with even indices represent the number of pixels assigned as background, - values of an array with odd indices represent the number of pixels + values of an array with odd indices represent the number of pixels assigned as foreground object). - resolution_wh (Tuple[int, int]): The width (w) and height (h) + resolution_wh (Tuple[int, int]): The width (w) and height (h) of the desired binary mask resolution. Returns: - npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), - where the foreground object is marked with `True`'s and the rest + npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), + where the foreground object is marked with `True`'s and the rest is filled with `False`'s. Raises: @@ -163,10 +163,10 @@ def rle_to_mask( """ width, height = resolution_wh - assert ( - width * height == np.sum(rle) - ), ("the sum of the number of pixels in the RLE must be the same " - "as the number of pixels in the expected mask") + assert width * height == np.sum(rle), ( + "the sum of the number of pixels in the RLE must be the same " + "as the number of pixels in the expected mask" + ) zero_one_values = np.zeros_like(rle) zero_one_values[1::2] = 1 @@ -180,13 +180,13 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: Converts a binary mask into a run-length encoding (RLE). Args: - mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object and `False` indicates background. Returns: - List[int]: the run-length encoded mask. Values of a list with even indices - represent the number of pixels assigned as background (`False`), values - of a list with odd indices represent the number of pixels assigned + List[int]: the run-length encoded mask. Values of a list with even indices + represent the number of pixels assigned as background (`False`), values + of a list with odd indices represent the number of pixels assigned as foreground object (`True`). Raises: diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 12ff4f00..f47e796d 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -252,7 +252,7 @@ def test_group_coco_annotations_by_image_id( ).reshape((1, 20, 20)), ), DoesNotRaise(), - ), # single image annotations with mask, segmentation mask in L-like shape, + ), # single image annotations with mask, segmentation mask in L-like shape, # like below: # 1 0 0 0 # 1 1 0 0 @@ -307,7 +307,7 @@ def test_group_coco_annotations_by_image_id( ).reshape((1, 20, 20)), ), DoesNotRaise(), - ), # single image annotations with mask, RLE segmentation mask in L-like shape, + ), # single image annotations with mask, RLE segmentation mask in L-like shape, # like below: # 1 0 0 0 # 1 1 0 0 @@ -357,7 +357,7 @@ def test_group_coco_annotations_by_image_id( ), ), DoesNotRaise(), - ), # two image annotations with mask, one mask as polygon in in L-like shape, + ), # two image annotations with mask, one mask as polygon in in L-like shape, # second as RLE in shape of square, like below (P = polygon, R = RLE): # P R 0 0 # P P 0 0 @@ -407,7 +407,7 @@ def test_group_coco_annotations_by_image_id( ), ), DoesNotRaise(), - ), # two image annotations with mask, first mask as RLE in shape of square, + ), # two image annotations with mask, first mask as RLE in shape of square, # second as polygon in in L-like shape, like below (P = polygon, R = RLE): # P R 0 0 # P P 0 0 From e4e66f8a9a9ab132776285cde21107e4c69dba6e Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 10 May 2024 10:16:34 +0200 Subject: [PATCH 19/51] faster mask to rle --- supervision/dataset/utils.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index bd7d7b57..6789d17a 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -202,11 +202,18 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: assert mask.ndim == 2, "Input mask must be 2D" assert mask.size != 0, "Input mask cannot be empty" - rle = [] - if mask[0][0] == 1: - rle = [0] + on_value_change_indices = np.where(mask.ravel(order='F') != + np.roll(mask.ravel(order='F'),1))[0] + + on_value_change_indices = np.append(on_value_change_indices, mask.size) + # need to add 0 at the beginning when the same value is in the first and + # last element of the flattened mask + if on_value_change_indices[0] != 0: + on_value_change_indices = np.insert(on_value_change_indices, 0, 0) - for _, group in groupby(mask.ravel(order="F")): - rle.append(len(list(group))) + rle = np.diff(on_value_change_indices) - return rle + if mask[0][0]==1: + rle = np.insert(rle, 0, 0) + + return list(rle) From 7bd92b096fbe5a4a6377884ca7c78fd3a9fe556c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 10 May 2024 08:18:35 +0000 Subject: [PATCH 20/51] =?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/dataset/utils.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 4fbd1230..9b5ae3cd 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -1,7 +1,6 @@ import copy import os import random -from itertools import groupby from pathlib import Path from typing import Dict, List, Optional, Tuple, TypeVar @@ -202,18 +201,19 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: assert mask.ndim == 2, "Input mask must be 2D" assert mask.size != 0, "Input mask cannot be empty" - on_value_change_indices = np.where(mask.ravel(order='F') != - np.roll(mask.ravel(order='F'),1))[0] - + on_value_change_indices = np.where( + mask.ravel(order="F") != np.roll(mask.ravel(order="F"), 1) + )[0] + on_value_change_indices = np.append(on_value_change_indices, mask.size) - # need to add 0 at the beginning when the same value is in the first and + # need to add 0 at the beginning when the same value is in the first and # last element of the flattened mask - if on_value_change_indices[0] != 0: - on_value_change_indices = np.insert(on_value_change_indices, 0, 0) + if on_value_change_indices[0] != 0: + on_value_change_indices = np.insert(on_value_change_indices, 0, 0) rle = np.diff(on_value_change_indices) - if mask[0][0]==1: - rle = np.insert(rle, 0, 0) + if mask[0][0] == 1: + rle = np.insert(rle, 0, 0) return list(rle) From 8c857dd9a61999b3d7d7c26568a855f617eb6f43 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Sun, 12 May 2024 23:02:22 +0200 Subject: [PATCH 21/51] speed up rle to mask --- supervision/dataset/utils.py | 6 ++++-- test/dataset/test_utils.py | 10 +++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 4fbd1230..82491871 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -168,10 +168,12 @@ def rle_to_mask( "as the number of pixels in the expected mask" ) - zero_one_values = np.zeros_like(rle) + zero_one_values = np.zeros(shape = (rle.size,1), dtype=np.uint8) zero_one_values[1::2] = 1 - decoded_rle = np.repeat(zero_one_values, rle) + decoded_rle = np.repeat(zero_one_values, rle, axis=0) + decoded_rle = np.append(decoded_rle, + np.zeros(width * height - len(decoded_rle), dtype=np.uint8)) return decoded_rle.reshape((height, width), order="F") diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index e269dde7..e30b4e5f 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -298,19 +298,19 @@ def test_mask_to_rle_conversion( "rle, resolution_wh, expected_mask, exception", [ ( - [9], + np.array([9]), [3, 3], np.zeros((3, 3)).astype(bool), DoesNotRaise(), ), # mask with background only (mask with only False values) ( - [0, 9], + np.array([0, 9]), [3, 3], np.ones((3, 3)).astype(bool), DoesNotRaise(), ), # mask with foreground only (mask with only True values) ( - [6, 3, 2, 1, 1, 1, 2, 3, 6], + np.array([6, 3, 2, 1, 1, 1, 2, 3, 6]), [5, 5], np.array( [ @@ -324,7 +324,7 @@ def test_mask_to_rle_conversion( DoesNotRaise(), ), # mask where foreground object has hole ( - [0, 5, 5, 5, 5, 5], + np.array([0, 5, 5, 5, 5, 5]), [5, 5], np.array( [ @@ -338,7 +338,7 @@ def test_mask_to_rle_conversion( DoesNotRaise(), ), # mask where foreground consists of 3 separate components ( - [0, 5, 5, 5, 5, 5], + np.array([0, 5, 5, 5, 5, 5]), [2, 2], None, pytest.raises(AssertionError), From 14b57345a763a0a4e414a64649882b6054571b78 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 12 May 2024 21:31:16 +0000 Subject: [PATCH 22/51] =?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/dataset/utils.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 61f3b1c8..b0b5577e 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -167,12 +167,13 @@ def rle_to_mask( "as the number of pixels in the expected mask" ) - zero_one_values = np.zeros(shape = (rle.size,1), dtype=np.uint8) + zero_one_values = np.zeros(shape=(rle.size, 1), dtype=np.uint8) zero_one_values[1::2] = 1 decoded_rle = np.repeat(zero_one_values, rle, axis=0) - decoded_rle = np.append(decoded_rle, - np.zeros(width * height - len(decoded_rle), dtype=np.uint8)) + decoded_rle = np.append( + decoded_rle, np.zeros(width * height - len(decoded_rle), dtype=np.uint8) + ) return decoded_rle.reshape((height, width), order="F") From d21c98a4d2fda92300d4931f952fcc0e91669959 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 13 May 2024 12:06:38 +0200 Subject: [PATCH 23/51] docs updated; `rle_to_mask` and `mask_to_rle` added to `__init__.py` --- docs/{datasets.md => datasets/core.md} | 1 + docs/datasets/utils.md | 18 ++++++++ mkdocs.yml | 4 +- supervision/__init__.py | 4 ++ supervision/dataset/utils.py | 60 ++++++++++++++++++-------- test/dataset/test_utils.py | 12 ++++-- 6 files changed, 76 insertions(+), 23 deletions(-) rename docs/{datasets.md => datasets/core.md} (97%) create mode 100644 docs/datasets/utils.md diff --git a/docs/datasets.md b/docs/datasets/core.md similarity index 97% rename from docs/datasets.md rename to docs/datasets/core.md index 73931515..03d0c196 100644 --- a/docs/datasets.md +++ b/docs/datasets/core.md @@ -1,5 +1,6 @@ --- comments: true +status: new --- # Datasets diff --git a/docs/datasets/utils.md b/docs/datasets/utils.md new file mode 100644 index 00000000..6be56303 --- /dev/null +++ b/docs/datasets/utils.md @@ -0,0 +1,18 @@ +--- +comments: true +status: new +--- + +# Datasets Utils + + + +:::supervision.dataset.utils.rle_to_mask + + + +:::supervision.dataset.utils.mask_to_rle diff --git a/mkdocs.yml b/mkdocs.yml index cf206a82..281c40c9 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -61,7 +61,9 @@ nav: - Detection Smoother: detection/tools/smoother.md - Save Detections: detection/tools/save_detections.md - Trackers: trackers.md - - Datasets: datasets.md + - Datasets: + - Core: datasets/core.md + - Utils: datasets/utils.md - Utils: - Video: utils/video.md - Image: utils/image.md diff --git a/supervision/__init__.py b/supervision/__init__.py index bb526514..b7f7a5e8 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -34,6 +34,10 @@ from supervision.dataset.core import ( ClassificationDataset, DetectionDataset, ) +from supervision.dataset.utils import ( + rle_to_mask, + mask_to_rle, +) from supervision.detection.annotate import BoxAnnotator from supervision.detection.core import Detections from supervision.detection.line_zone import LineZone, LineZoneAnnotator diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index b0b5577e..ed7062b9 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -2,7 +2,7 @@ import copy import os import random from pathlib import Path -from typing import Dict, List, Optional, Tuple, TypeVar +from typing import Dict, List, Optional, Tuple, Union, TypeVar import cv2 import numpy as np @@ -133,33 +133,42 @@ def train_test_split( def rle_to_mask( - rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int] + rle: Union[npt.NDArray[np.int_], List[int]], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]: """ Converts run-length encoding (RLE) to a binary mask. Args: - rle (npt.NDArray[np.int_]): The 1D RLE array, the format used in the COCO - dataset (column-wise encoding, values of an array with even indices - represent the number of pixels assigned as background, + rle (Union[npt.NDArray[np.int_], List[int]]): The 1D RLE array, the format + used in the COCO dataset (column-wise encoding, values of an array with + even indices represent the number of pixels assigned as background, values of an array with odd indices represent the number of pixels assigned as foreground object). resolution_wh (Tuple[int, int]): The width (w) and height (h) - of the desired binary mask resolution. + of the desired binary mask. Returns: - npt.NDArray[np.bool_]: The generated 2D Boolean mask of shape (h,w), - where the foreground object is marked with `True`'s and the rest - is filled with `False`'s. + The generated 2D Boolean mask of shape `(h, w)`, where the foreground object is + marked with `True`'s and the rest is filled with `False`'s. Raises: AssertionError: If the sum of pixels encoded in RLE differs from the - number of pixels in the expected mask (computed based on resolution_wh). + number of pixels in the expected mask (computed based on resolution_wh). Examples: - rle = [2, 2, 2], resolution_wh = [3, 2] -> mask = [[False, True, False], - [False, True, False]] + ```python + import supervision as sv + + sv.rle_to_mask([2, 2, 2], (3, 2)) + # array([ + # [False, True, False], + # [False, True, False] + # ]) + ``` """ + if isinstance(rle, list): + rle = np.array(rle, dtype=int) + width, height = resolution_wh assert width * height == np.sum(rle), ( @@ -186,20 +195,33 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: object and `False` indicates background. Returns: - List[int]: the run-length encoded mask. Values of a list with even indices + The run-length encoded mask. Values of a list with even indices represent the number of pixels assigned as background (`False`), values of a list with odd indices represent the number of pixels assigned as foreground object (`True`). Raises: - AssertionError: If imput mask is not 2D or is empty. + AssertionError: If input mask is not 2D or is empty. - Examples: - mask = [[False, True, True], -> rle = [2, 4] - [False, True, True]] + Examples: + ```python + import numpy as np + import supervision as sv - mask = [[True, True, True], -> rle = [0, 6] - [True, True, True]] + mask = np.array([ + [False, True, True], + [False, True, True] + ]) + sv.mask_to_rle(mask) + # [2, 4] + + mask = np.array([ + [True, True, True], + [True, True, True] + ]) + sv.mask_to_rle(mask) + # [0, 6] + ``` """ assert mask.ndim == 2, "Input mask must be 2D" assert mask.size != 0, "Input mask cannot be empty" diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py index e30b4e5f..41e1da5b 100644 --- a/test/dataset/test_utils.py +++ b/test/dataset/test_utils.py @@ -286,7 +286,7 @@ def test_map_detections_class_id( ), # raises AssertionError because mask is empty ], ) -def test_mask_to_rle_conversion( +def test_mask_to_rle( mask: npt.NDArray[np.bool_], expected_rle: List[int], exception: Exception ) -> None: with exception: @@ -302,7 +302,13 @@ def test_mask_to_rle_conversion( [3, 3], np.zeros((3, 3)).astype(bool), DoesNotRaise(), - ), # mask with background only (mask with only False values) + ), # mask with background only (mask with only False values); rle as array + ( + [9], + [3, 3], + np.zeros((3, 3)).astype(bool), + DoesNotRaise(), + ), # mask with background only (mask with only False values); rle as list ( np.array([0, 9]), [3, 3], @@ -346,7 +352,7 @@ def test_mask_to_rle_conversion( # number of pixels in expected mask (width x height). ], ) -def test_rle_to_mask_convertion( +def test_rle_to_mask( rle: npt.NDArray[np.int_], resolution_wh: Tuple[int, int], expected_mask: npt.NDArray[np.bool_], From 9a1c11218c8c247a3203ba76c501fe2aac08e1ba Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 13 May 2024 10:06:55 +0000 Subject: [PATCH 24/51] =?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 | 5 +---- supervision/dataset/utils.py | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index b7f7a5e8..2bc72944 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -34,10 +34,7 @@ from supervision.dataset.core import ( ClassificationDataset, DetectionDataset, ) -from supervision.dataset.utils import ( - rle_to_mask, - mask_to_rle, -) +from supervision.dataset.utils import mask_to_rle, rle_to_mask from supervision.detection.annotate import BoxAnnotator from supervision.detection.core import Detections from supervision.detection.line_zone import LineZone, LineZoneAnnotator diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index ed7062b9..4efc7194 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -2,7 +2,7 @@ import copy import os import random from pathlib import Path -from typing import Dict, List, Optional, Tuple, Union, TypeVar +from typing import Dict, List, Optional, Tuple, TypeVar, Union import cv2 import numpy as np From 59b273ba87e30e406e8036560bd0c3348a86287c Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Mon, 13 May 2024 12:25:25 +0200 Subject: [PATCH 25/51] small refactor --- supervision/dataset/formats/coco.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 4beb1dcd..fc62ac66 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -5,6 +5,7 @@ from typing import Dict, List, Tuple import cv2 import numpy as np +import numpy.typing as npt from supervision.dataset.utils import ( approximate_mask_with_polygons, @@ -58,7 +59,10 @@ def group_coco_annotations_by_image_id( return annotations -def _annotations_to_mask(image_annotations: List[dict], resolution_wh: Tuple[int, int]): +def coco_annotations_to_masks( + image_annotations: List[dict], + resolution_wh: Tuple[int, int] +) -> npt.NDArray[np.bool_]: return np.array( [ rle_to_mask( @@ -93,7 +97,10 @@ def coco_annotations_to_detections( xyxy[:, 2:4] += xyxy[:, 0:2] if with_masks: - mask = _annotations_to_mask(image_annotations, resolution_wh) + mask = coco_annotations_to_masks( + image_annotations=image_annotations, + resolution_wh=resolution_wh + ) return Detections( class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask ) From cccacab62143010e75be4217a9af3c26e4ea3ffc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 13 May 2024 10:25:46 +0000 Subject: [PATCH 26/51] =?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/dataset/formats/coco.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index fc62ac66..b6b2490a 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -60,8 +60,7 @@ def group_coco_annotations_by_image_id( def coco_annotations_to_masks( - image_annotations: List[dict], - resolution_wh: Tuple[int, int] + image_annotations: List[dict], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]: return np.array( [ @@ -98,8 +97,7 @@ def coco_annotations_to_detections( if with_masks: mask = coco_annotations_to_masks( - image_annotations=image_annotations, - resolution_wh=resolution_wh + image_annotations=image_annotations, resolution_wh=resolution_wh ) return Detections( class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask From aab861c2db5ae2b641285a225fbeafe6206a6d02 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Wed, 15 May 2024 08:55:47 +0200 Subject: [PATCH 27/51] test_coco_annotations_to_detections result matrices defined in place --- test/dataset/formats/test_coco.py | 216 +++++++++++------------------- 1 file changed, 79 insertions(+), 137 deletions(-) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index f47e796d..bfde8495 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -233,186 +233,128 @@ def test_group_coco_annotations_by_image_id( [ mock_cock_coco_annotation( category_id=0, - bbox=(0, 0, 10, 10), - area=10 * 10, - segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], + bbox=(0, 0, 5, 5), + area= 5 * 5, + segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ) ], - (20, 20), + (5, 5), True, Detections( - xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask=np.array( - [ - 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((1, 20, 20)), + mask=np.array([[[1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]]]), ), DoesNotRaise(), - ), # single image annotations with mask, segmentation mask in L-like shape, - # like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 + ), # single image annotations with mask as polygon ( [ mock_cock_coco_annotation( category_id=0, - bbox=(0, 0, 10, 10), - area=10 * 10, - segmentation={ - "size": [20, 20], - "counts": [ - 0, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 15, - 5, - 15, - 5, - 15, - 5, - 15, - 5, - 15, - 5, - 210, - ], - }, - iscrowd=True, - ) - ], - (20, 20), - True, - Detections( - xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), - class_id=np.array([0], dtype=int), - mask=np.array( - [ - 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((1, 20, 20)), - ), - DoesNotRaise(), - ), # single image annotations with mask, RLE segmentation mask in L-like shape, - # like below: - # 1 0 0 0 - # 1 1 0 0 - # 0 0 0 0 - # 0 0 0 0 - ( - [ - mock_cock_coco_annotation( - category_id=0, - bbox=(0, 0, 10, 10), - area=10 * 10, - segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], - ), - mock_cock_coco_annotation( - category_id=0, - bbox=(5, 0, 5, 5), + bbox=(0, 0, 5, 5), area=5 * 5, segmentation={ - "size": [20, 20], - "counts": [100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215], + "size": [5, 5], + "counts": [0, 15, 2, 3, 2, 3], + }, + iscrowd=True, + ) + ], + (5, 5), + True, + Detections( + xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask=np.array([[[1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]]]), + ), + DoesNotRaise(), + ), # single image annotations with mask, RLE segmentation mask + ( + [ + mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 5, 5), + area= 5 * 5, + segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], + ), + mock_cock_coco_annotation( + category_id=0, + bbox=(3, 0, 2, 2), + area=2 * 2, + segmentation={ + "size": [5, 5], + "counts": [15, 2, 3, 2, 3], }, iscrowd=True, ), ], - (20, 20), + (5, 5), True, Detections( - xyxy=np.array([[0, 0, 10, 10], [5, 0, 10, 5]], dtype=np.float32), + xyxy=np.array([[0, 0, 5, 5], [3, 0, 5, 2]], dtype=np.float32), class_id=np.array([0, 0], dtype=int), - mask=np.array( - [ - np.array( - [ - 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((20, 20)), - np.array( - [ - 1 if j > 4 and j < 10 and i < 5 else 0 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((20, 20)), - ] - ), + mask=np.array([ [[1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]], + [[0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]]) ), DoesNotRaise(), - ), # two image annotations with mask, one mask as polygon in in L-like shape, - # second as RLE in shape of square, like below (P = polygon, R = RLE): - # P R 0 0 - # P P 0 0 - # 0 0 0 0 - # 0 0 0 0 + ), # two image annotations with mask, one mask as polygon ans second as RLE ( [ mock_cock_coco_annotation( category_id=0, - bbox=(5, 0, 5, 5), - area=5 * 5, + bbox=(3, 0, 2, 2), + area=2 * 2, segmentation={ - "size": [20, 20], - "counts": [100, 5, 15, 5, 15, 5, 15, 5, 15, 5, 215], + "size": [5, 5], + "counts": [15, 2, 3, 2, 3], }, iscrowd=True, ), mock_cock_coco_annotation( category_id=1, - bbox=(0, 0, 10, 10), - area=10 * 10, - segmentation=[[0, 0, 4, 0, 4, 5, 9, 5, 9, 9, 0, 9]], + bbox=(0, 0, 5, 5), + area= 5 * 5, + segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ), ], - (20, 20), + (5, 5), True, Detections( - xyxy=np.array([[5, 0, 10, 5], [0, 0, 10, 10]], dtype=np.float32), + xyxy=np.array([[3, 0, 5, 2], [0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0, 1], dtype=int), mask=np.array( [ - np.array( - [ - 1 if j > 4 and j < 10 and i < 5 else 0 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((20, 20)), - np.array( - [ - 0 if i >= 10 or j >= 10 or (i < 5 and j >= 5) else 1 - for i in range(0, 20) - for j in range(0, 20) - ] - ).reshape((20, 20)), + [[0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], + [[1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]] ] ), ), DoesNotRaise(), - ), # two image annotations with mask, first mask as RLE in shape of square, - # second as polygon in in L-like shape, like below (P = polygon, R = RLE): - # P R 0 0 - # P P 0 0 - # 0 0 0 0 - # 0 0 0 0 + ), # two image annotations with mask, first mask as RLE and second as polygon ], ) def test_coco_annotations_to_detections( From f08404eb7d73b001e860c4b56ccc799cdfa6ce8e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 15 May 2024 06:56:06 +0000 Subject: [PATCH 28/51] =?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 --- test/dataset/formats/test_coco.py | 92 +++++++++++++++++++------------ 1 file changed, 58 insertions(+), 34 deletions(-) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index bfde8495..66e73c0e 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -234,7 +234,7 @@ def test_group_coco_annotations_by_image_id( mock_cock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), - area= 5 * 5, + area=5 * 5, segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ) ], @@ -243,14 +243,20 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask=np.array([[[1, 1, 1, 0, 0], - [1, 1, 1, 0, 0], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1]]]), + mask=np.array( + [ + [ + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ] + ] + ), ), DoesNotRaise(), - ), # single image annotations with mask as polygon + ), # single image annotations with mask as polygon ( [ mock_cock_coco_annotation( @@ -269,11 +275,17 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0], dtype=int), - mask=np.array([[[1, 1, 1, 0, 0], - [1, 1, 1, 0, 0], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1]]]), + mask=np.array( + [ + [ + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ] + ] + ), ), DoesNotRaise(), ), # single image annotations with mask, RLE segmentation mask @@ -282,7 +294,7 @@ def test_group_coco_annotations_by_image_id( mock_cock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), - area= 5 * 5, + area=5 * 5, segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ), mock_cock_coco_annotation( @@ -301,16 +313,24 @@ def test_group_coco_annotations_by_image_id( Detections( xyxy=np.array([[0, 0, 5, 5], [3, 0, 5, 2]], dtype=np.float32), class_id=np.array([0, 0], dtype=int), - mask=np.array([ [[1, 1, 1, 0, 0], - [1, 1, 1, 0, 0], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1]], - [[0, 0, 0, 1, 1], - [0, 0, 0, 1, 1], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0]]]) + mask=np.array( + [ + [ + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ], + [ + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + ], + ] + ), ), DoesNotRaise(), ), # two image annotations with mask, one mask as polygon ans second as RLE @@ -329,7 +349,7 @@ def test_group_coco_annotations_by_image_id( mock_cock_coco_annotation( category_id=1, bbox=(0, 0, 5, 5), - area= 5 * 5, + area=5 * 5, segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ), ], @@ -340,16 +360,20 @@ def test_group_coco_annotations_by_image_id( class_id=np.array([0, 1], dtype=int), mask=np.array( [ - [[0, 0, 0, 1, 1], - [0, 0, 0, 1, 1], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0]], - [[1, 1, 1, 0, 0], - [1, 1, 1, 0, 0], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1], - [1, 1, 1, 1, 1]] + [ + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ], ] ), ), From d8679d9c46cbf76fd86b64ea11bf2833a9794781 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Thu, 16 May 2024 08:40:28 +0200 Subject: [PATCH 29/51] automatic RLE for masks with holes or in multiple pieces --- supervision/dataset/formats/coco.py | 47 +++++++---- test/dataset/formats/test_coco.py | 116 +++++++++++++++++++++++++++- 2 files changed, 148 insertions(+), 15 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index b6b2490a..2cc442a9 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -11,6 +11,7 @@ from supervision.dataset.utils import ( approximate_mask_with_polygons, map_detections_class_id, rle_to_mask, + mask_to_rle ) from supervision.detection.core import Detections from supervision.detection.utils import polygon_to_mask @@ -106,6 +107,21 @@ def coco_annotations_to_detections( return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) +def _mask_has_holes(mask: np.ndarray)-> bool: + _, hierarchy = cv2.findContours(mask.astype(np.uint8), cv2.RETR_CCOMP, + cv2.CHAIN_APPROX_SIMPLE) + parent_countour_index = 3 + for h in hierarchy[0]: + if h[parent_countour_index] != -1: + return True + return False + + +def _mask_has_multiple_segments(mask: np.ndarray)-> bool: + number_of_labels, _ = cv2.connectedComponents(mask.astype(np.uint8), connectivity=4) + return number_of_labels > 2 + + def detections_to_coco_annotations( detections: Detections, image_id: int, @@ -118,26 +134,31 @@ def detections_to_coco_annotations( for xyxy, mask, _, class_id, _, _ in detections: box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] segmentation = [] + iscrowd = 0 if mask is not None: - segmentation = list( - approximate_mask_with_polygons( - mask=mask, - min_image_area_percentage=min_image_area_percentage, - max_image_area_percentage=max_image_area_percentage, - approximation_percentage=approximation_percentage, - )[0].flatten() - ) - # todo: flag for when to use RLE? - # segmentation = {"counts": mask_to_rle(binary_mask=mask), - # "size": list(mask.shape[:2])} + iscrowd = _mask_has_holes(mask = mask) or \ + _mask_has_multiple_segments(mask = mask) + + if iscrowd: + segmentation = {"counts": mask_to_rle(mask=mask), + "size": list(mask.shape[:2])} + else: + segmentation = [list( + approximate_mask_with_polygons( + mask=mask, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + )[0].flatten() + )] # multicomponent masks supported only for rle format coco_annotation = { "id": annotation_id, "image_id": image_id, "category_id": int(class_id), "bbox": [xyxy[0], xyxy[1], box_width, box_height], "area": box_width * box_height, - "segmentation": [segmentation] if segmentation else [], - "iscrowd": 0, ## todo: iscrowd depends on flag 1 if RLE 0 if polygon + "segmentation": segmentation, + "iscrowd": iscrowd, } coco_annotations.append(coco_annotation) annotation_id += 1 diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 66e73c0e..cecb637d 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -1,5 +1,5 @@ from contextlib import ExitStack as DoesNotRaise -from typing import Dict, List, Tuple +from typing import Dict, List, Tuple, Union import numpy as np import pytest @@ -11,6 +11,7 @@ from supervision.dataset.formats.coco import ( coco_annotations_to_detections, coco_categories_to_classes, group_coco_annotations_by_image_id, + detections_to_coco_annotations ) @@ -20,9 +21,11 @@ def mock_cock_coco_annotation( category_id: int = 0, bbox: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0), area: float = 0.0, - segmentation: List[list] = None, + segmentation: Union[List[list], Dict] = None, iscrowd: bool = False, ) -> dict: + if not segmentation: + segmentation = [] return { "id": annotation_id, "image_id": image_id, @@ -454,3 +457,112 @@ def test_build_coco_class_index_mapping( coco_categories=coco_categories, target_classes=target_classes ) assert result == expected_result + + +@pytest.mark.parametrize( + "detections, image_id, annotation_id, expected_result, exception", + [ + ( + Detections(xyxy=np.array([[0, 0, 100, 100]], dtype=np.float32), + class_id=np.array([0], dtype=int)), + 0, + 0, + [mock_cock_coco_annotation(category_id=0, bbox=(0, 0, 100, 100), area=100 * 100)], + DoesNotRaise(), + ), # no segmentation mask + # ( + # Detections( + # xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), + # class_id=np.array([0], dtype=int), + # mask=np.array( + # [ + # [ + # [1, 1, 1, 0, 0], + # [1, 1, 1, 0, 0], + # [1, 1, 1, 1, 1], + # [1, 1, 1, 1, 1], + # [1, 1, 1, 1, 1], + # ] + # ] + # ), + # ), + # 0, + # 0, + # [mock_cock_coco_annotation( + # category_id=0, + # bbox=(0, 0, 5, 5), + # area=5 * 5, + # segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]])], + # DoesNotRaise(), + # ), # segmentation mask in single component,no holes in mask, expects polygon mask + ( + Detections( + xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask=np.array( + [ + [ + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + ] + ] + ), + ), + 0, + 0, + [mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 5, 5), + area=5 * 5, + segmentation={ + "size": [5, 5], + "counts": [0, 3, 2, 3, 2, 3, 5, 2, 3, 2], + }, + iscrowd=True, )], + DoesNotRaise(), + ), # segmentation mask with 2 components, no holes in mask, expects RLE mask + ( + Detections( + xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask=np.array( + [ + [ + [0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [1, 1, 0, 0, 1], + [1, 1, 0, 0, 1], + [1, 1, 1, 1, 1], + ] + ] + ), + ), + 0, + 0, + [mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 5, 5), + area=5 * 5, + segmentation={ + "size": [5, 5], + "counts": [2, 10, 2, 3, 2, 6], + }, + iscrowd=True, )], + DoesNotRaise(), + ) # segmentation mask in single component, with holes in mask, expects RLE mask + ], +) +def test_detections_to_coco_annotations( + detections: Detections, + image_id: int, + annotation_id: int, + expected_result: List[Dict], + exception: Exception) -> None: + with exception: + result, _ = detections_to_coco_annotations( + detections=detections, image_id=image_id, annotation_id=annotation_id + ) + assert result == expected_result From eefa05cf01c3875f7d21a2b40a71c1fdc4bdc591 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 16 May 2024 06:40:55 +0000 Subject: [PATCH 30/51] =?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/dataset/formats/coco.py | 42 +++++---- test/dataset/formats/test_coco.py | 129 +++++++++++++++------------- 2 files changed, 95 insertions(+), 76 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 2cc442a9..19e7aa3e 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -10,8 +10,8 @@ import numpy.typing as npt from supervision.dataset.utils import ( approximate_mask_with_polygons, map_detections_class_id, + mask_to_rle, rle_to_mask, - mask_to_rle ) from supervision.detection.core import Detections from supervision.detection.utils import polygon_to_mask @@ -107,9 +107,10 @@ def coco_annotations_to_detections( return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) -def _mask_has_holes(mask: np.ndarray)-> bool: - _, hierarchy = cv2.findContours(mask.astype(np.uint8), cv2.RETR_CCOMP, - cv2.CHAIN_APPROX_SIMPLE) +def _mask_has_holes(mask: np.ndarray) -> bool: + _, hierarchy = cv2.findContours( + mask.astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE + ) parent_countour_index = 3 for h in hierarchy[0]: if h[parent_countour_index] != -1: @@ -117,9 +118,9 @@ def _mask_has_holes(mask: np.ndarray)-> bool: return False -def _mask_has_multiple_segments(mask: np.ndarray)-> bool: +def _mask_has_multiple_segments(mask: np.ndarray) -> bool: number_of_labels, _ = cv2.connectedComponents(mask.astype(np.uint8), connectivity=4) - return number_of_labels > 2 + return number_of_labels > 2 def detections_to_coco_annotations( @@ -136,21 +137,26 @@ def detections_to_coco_annotations( segmentation = [] iscrowd = 0 if mask is not None: - iscrowd = _mask_has_holes(mask = mask) or \ - _mask_has_multiple_segments(mask = mask) + iscrowd = _mask_has_holes(mask=mask) or _mask_has_multiple_segments( + mask=mask + ) if iscrowd: - segmentation = {"counts": mask_to_rle(mask=mask), - "size": list(mask.shape[:2])} + segmentation = { + "counts": mask_to_rle(mask=mask), + "size": list(mask.shape[:2]), + } else: - segmentation = [list( - approximate_mask_with_polygons( - mask=mask, - min_image_area_percentage=min_image_area_percentage, - max_image_area_percentage=max_image_area_percentage, - approximation_percentage=approximation_percentage, - )[0].flatten() - )] # multicomponent masks supported only for rle format + segmentation = [ + list( + approximate_mask_with_polygons( + mask=mask, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + )[0].flatten() + ) + ] # multicomponent masks supported only for rle format coco_annotation = { "id": annotation_id, "image_id": image_id, diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index cecb637d..139c74f8 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -10,8 +10,8 @@ from supervision.dataset.formats.coco import ( classes_to_coco_categories, coco_annotations_to_detections, coco_categories_to_classes, + detections_to_coco_annotations, group_coco_annotations_by_image_id, - detections_to_coco_annotations ) @@ -463,40 +463,46 @@ def test_build_coco_class_index_mapping( "detections, image_id, annotation_id, expected_result, exception", [ ( - Detections(xyxy=np.array([[0, 0, 100, 100]], dtype=np.float32), - class_id=np.array([0], dtype=int)), - 0, - 0, - [mock_cock_coco_annotation(category_id=0, bbox=(0, 0, 100, 100), area=100 * 100)], - DoesNotRaise(), - ), # no segmentation mask - # ( - # Detections( - # xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), - # class_id=np.array([0], dtype=int), - # mask=np.array( - # [ - # [ - # [1, 1, 1, 0, 0], - # [1, 1, 1, 0, 0], - # [1, 1, 1, 1, 1], - # [1, 1, 1, 1, 1], - # [1, 1, 1, 1, 1], - # ] - # ] - # ), - # ), - # 0, - # 0, - # [mock_cock_coco_annotation( - # category_id=0, - # bbox=(0, 0, 5, 5), - # area=5 * 5, - # segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]])], - # DoesNotRaise(), - # ), # segmentation mask in single component,no holes in mask, expects polygon mask - ( - Detections( + Detections( + xyxy=np.array([[0, 0, 100, 100]], dtype=np.float32), + class_id=np.array([0], dtype=int), + ), + 0, + 0, + [ + mock_cock_coco_annotation( + category_id=0, bbox=(0, 0, 100, 100), area=100 * 100 + ) + ], + DoesNotRaise(), + ), # no segmentation mask + # ( + # Detections( + # xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), + # class_id=np.array([0], dtype=int), + # mask=np.array( + # [ + # [ + # [1, 1, 1, 0, 0], + # [1, 1, 1, 0, 0], + # [1, 1, 1, 1, 1], + # [1, 1, 1, 1, 1], + # [1, 1, 1, 1, 1], + # ] + # ] + # ), + # ), + # 0, + # 0, + # [mock_cock_coco_annotation( + # category_id=0, + # bbox=(0, 0, 5, 5), + # area=5 * 5, + # segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]])], + # DoesNotRaise(), + # ), # segmentation mask in single component,no holes in mask, expects polygon mask + ( + Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0], dtype=int), mask=np.array( @@ -511,21 +517,24 @@ def test_build_coco_class_index_mapping( ] ), ), - 0, - 0, - [mock_cock_coco_annotation( - category_id=0, - bbox=(0, 0, 5, 5), - area=5 * 5, - segmentation={ + 0, + 0, + [ + mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 5, 5), + area=5 * 5, + segmentation={ "size": [5, 5], "counts": [0, 3, 2, 3, 2, 3, 5, 2, 3, 2], }, - iscrowd=True, )], - DoesNotRaise(), - ), # segmentation mask with 2 components, no holes in mask, expects RLE mask - ( - Detections( + iscrowd=True, + ) + ], + DoesNotRaise(), + ), # segmentation mask with 2 components, no holes in mask, expects RLE mask + ( + Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), class_id=np.array([0], dtype=int), mask=np.array( @@ -540,19 +549,22 @@ def test_build_coco_class_index_mapping( ] ), ), - 0, - 0, - [mock_cock_coco_annotation( - category_id=0, - bbox=(0, 0, 5, 5), - area=5 * 5, - segmentation={ + 0, + 0, + [ + mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 5, 5), + area=5 * 5, + segmentation={ "size": [5, 5], "counts": [2, 10, 2, 3, 2, 6], }, - iscrowd=True, )], - DoesNotRaise(), - ) # segmentation mask in single component, with holes in mask, expects RLE mask + iscrowd=True, + ) + ], + DoesNotRaise(), + ), # segmentation mask in single component, with holes in mask, expects RLE mask ], ) def test_detections_to_coco_annotations( @@ -560,7 +572,8 @@ def test_detections_to_coco_annotations( image_id: int, annotation_id: int, expected_result: List[Dict], - exception: Exception) -> None: + exception: Exception, +) -> None: with exception: result, _ = detections_to_coco_annotations( detections=detections, image_id=image_id, annotation_id=annotation_id From 1e8ee47db25b01ed09f413f88624a3f86e8eb55b Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Thu, 16 May 2024 08:56:58 +0200 Subject: [PATCH 31/51] craete copies of mask in _has_holes and _mask_has_multiple_segments --- supervision/dataset/formats/coco.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 19e7aa3e..db65ed57 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -108,9 +108,8 @@ def coco_annotations_to_detections( def _mask_has_holes(mask: np.ndarray) -> bool: - _, hierarchy = cv2.findContours( - mask.astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE - ) + mask_uint8 = mask.astype(np.uint8) + _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) parent_countour_index = 3 for h in hierarchy[0]: if h[parent_countour_index] != -1: @@ -119,7 +118,8 @@ def _mask_has_holes(mask: np.ndarray) -> bool: def _mask_has_multiple_segments(mask: np.ndarray) -> bool: - number_of_labels, _ = cv2.connectedComponents(mask.astype(np.uint8), connectivity=4) + mask_uint8 = mask.astype(np.uint8) + number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) return number_of_labels > 2 From ce05a0c5441afb0a604ce9dc30997297952157c0 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 16 May 2024 06:57:24 +0000 Subject: [PATCH 32/51] =?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/dataset/formats/coco.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index db65ed57..5a55532c 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -108,7 +108,7 @@ def coco_annotations_to_detections( def _mask_has_holes(mask: np.ndarray) -> bool: - mask_uint8 = mask.astype(np.uint8) + mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) parent_countour_index = 3 for h in hierarchy[0]: @@ -118,7 +118,7 @@ def _mask_has_holes(mask: np.ndarray) -> bool: def _mask_has_multiple_segments(mask: np.ndarray) -> bool: - mask_uint8 = mask.astype(np.uint8) + mask_uint8 = mask.astype(np.uint8) number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) return number_of_labels > 2 From 3ee72e38c35982983cd3fc971b31499a56d76f58 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Thu, 16 May 2024 09:20:26 +0200 Subject: [PATCH 33/51] check for empty mask --- supervision/dataset/formats/coco.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index db65ed57..91e11dcb 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -109,7 +109,8 @@ def coco_annotations_to_detections( def _mask_has_holes(mask: np.ndarray) -> bool: mask_uint8 = mask.astype(np.uint8) - _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + _, hierarchy = cv2.findContours( + mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) parent_countour_index = 3 for h in hierarchy[0]: if h[parent_countour_index] != -1: @@ -118,6 +119,8 @@ def _mask_has_holes(mask: np.ndarray) -> bool: def _mask_has_multiple_segments(mask: np.ndarray) -> bool: + if mask.size == 0: + return False mask_uint8 = mask.astype(np.uint8) number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) return number_of_labels > 2 From b3b745508bf05895d4061fb8a8018a489e8dde2d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 16 May 2024 07:23:53 +0000 Subject: [PATCH 34/51] =?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/dataset/formats/coco.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 73b5b32a..0e80afb5 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -120,7 +120,7 @@ def _mask_has_holes(mask: np.ndarray) -> bool: def _mask_has_multiple_segments(mask: np.ndarray) -> bool: if mask.size == 0: return False - mask_uint8 = mask.astype(np.uint8) + mask_uint8 = mask.astype(np.uint8) number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) return number_of_labels > 2 From 879ae9416a6598440c39fa8eaaf77f32916e4d51 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 17 May 2024 10:34:53 +0200 Subject: [PATCH 35/51] test polygon mask when mask in single component and no holes --- supervision/dataset/formats/coco.py | 2 -- test/dataset/formats/test_coco.py | 55 +++++++++++++++-------------- 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 73b5b32a..723ad463 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -118,8 +118,6 @@ def _mask_has_holes(mask: np.ndarray) -> bool: def _mask_has_multiple_segments(mask: np.ndarray) -> bool: - if mask.size == 0: - return False mask_uint8 = mask.astype(np.uint8) number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) return number_of_labels > 2 diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 139c74f8..11085a90 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -476,31 +476,32 @@ def test_build_coco_class_index_mapping( ], DoesNotRaise(), ), # no segmentation mask - # ( - # Detections( - # xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), - # class_id=np.array([0], dtype=int), - # mask=np.array( - # [ - # [ - # [1, 1, 1, 0, 0], - # [1, 1, 1, 0, 0], - # [1, 1, 1, 1, 1], - # [1, 1, 1, 1, 1], - # [1, 1, 1, 1, 1], - # ] - # ] - # ), - # ), - # 0, - # 0, - # [mock_cock_coco_annotation( - # category_id=0, - # bbox=(0, 0, 5, 5), - # area=5 * 5, - # segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]])], - # DoesNotRaise(), - # ), # segmentation mask in single component,no holes in mask, expects polygon mask + ( + Detections( + xyxy=np.array([[0, 0, 4, 5]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask=np.array( + [ + [ + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + ] + ] + ), + ), + 0, + 0, + [mock_cock_coco_annotation( + category_id=0, + bbox=(0, 0, 4, 5), + area=4 * 5, + segmentation=[[0, 0, 0, 4, 3, 4, 3, 0]])], + DoesNotRaise(), + ), # segmentation mask in single component,no holes in mask, + # expects polygon mask ( Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), @@ -564,7 +565,7 @@ def test_build_coco_class_index_mapping( ) ], DoesNotRaise(), - ), # segmentation mask in single component, with holes in mask, expects RLE mask + ), # segmentation mask in single component, with holes in mask, expects RLE mask ], ) def test_detections_to_coco_annotations( @@ -576,6 +577,6 @@ def test_detections_to_coco_annotations( ) -> None: with exception: result, _ = detections_to_coco_annotations( - detections=detections, image_id=image_id, annotation_id=annotation_id + detections=detections, image_id=image_id, annotation_id=annotation_id, ) assert result == expected_result From ab775d9f76c7487ffbf74b5dc978479a218b7341 Mon Sep 17 00:00:00 2001 From: Linas Kondrackis Date: Fri, 17 May 2024 11:45:00 +0300 Subject: [PATCH 36/51] Attempt to fix SegFault * https://github.com/opencv/opencv-python/issues/706 --- supervision/dataset/formats/coco.py | 3 ++- test/dataset/formats/test_coco.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 0e80afb5..4f6c169e 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -121,7 +121,8 @@ def _mask_has_multiple_segments(mask: np.ndarray) -> bool: if mask.size == 0: return False mask_uint8 = mask.astype(np.uint8) - number_of_labels, _ = cv2.connectedComponents(mask_uint8, connectivity=4) + labels = np.zeros_like(mask_uint8, dtype=np.int32) + number_of_labels, _ = cv2.connectedComponents(mask_uint8, labels, connectivity=4) return number_of_labels > 2 diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 139c74f8..af6b31bc 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -500,7 +500,7 @@ def test_build_coco_class_index_mapping( # area=5 * 5, # segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]])], # DoesNotRaise(), - # ), # segmentation mask in single component,no holes in mask, expects polygon mask + # ), # seg mask in single component,no holes in mask, expects polygon ( Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), @@ -564,7 +564,7 @@ def test_build_coco_class_index_mapping( ) ], DoesNotRaise(), - ), # segmentation mask in single component, with holes in mask, expects RLE mask + ), # seg mask in single component, with holes in mask, expects RLE mask ], ) def test_detections_to_coco_annotations( From 0cd2c9d1464d2de77db97b7fc5550d05955477eb Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Fri, 17 May 2024 11:16:37 +0200 Subject: [PATCH 37/51] documentation change for as_coco --- supervision/dataset/core.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 551e96da..fbbbe6b7 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -430,6 +430,10 @@ class DetectionDataset(BaseDataset): """ Exports the dataset to COCO format. This method saves the images and their corresponding annotations in COCO format. + The format of the mask is determined automatically: + when a mask consists of multiple disconnected elements + or has holes the RLE format is used, + otherwise, the mask is encoded as a polygon. Args: images_directory_path (Optional[str]): The path to the directory From 8d432c78b1cb02d62a8051c972d92454a1cecd54 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 17 May 2024 09:16:57 +0000 Subject: [PATCH 38/51] =?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/dataset/core.py | 4 ++-- test/dataset/formats/test_coco.py | 37 ++++++++++++++++++------------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index fbbbe6b7..6ae5844a 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -430,8 +430,8 @@ class DetectionDataset(BaseDataset): """ Exports the dataset to COCO format. This method saves the images and their corresponding annotations in COCO format. - The format of the mask is determined automatically: - when a mask consists of multiple disconnected elements + The format of the mask is determined automatically: + when a mask consists of multiple disconnected elements or has holes the RLE format is used, otherwise, the mask is encoded as a polygon. diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 6be0fa2c..8da8ccc8 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -478,30 +478,33 @@ def test_build_coco_class_index_mapping( ), # no segmentation mask ( Detections( - xyxy=np.array([[0, 0, 4, 5]], dtype=np.float32), - class_id=np.array([0], dtype=int), - mask=np.array( + xyxy=np.array([[0, 0, 4, 5]], dtype=np.float32), + class_id=np.array([0], dtype=int), + mask=np.array( + [ [ - [ - [1, 1, 1, 1, 0], - [1, 1, 1, 1, 0], - [1, 1, 1, 1, 0], - [1, 1, 1, 1, 0], - [1, 1, 1, 1, 0], - ] + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], ] - ), + ] ), + ), 0, 0, - [mock_cock_coco_annotation( + [ + mock_cock_coco_annotation( category_id=0, bbox=(0, 0, 4, 5), area=4 * 5, - segmentation=[[0, 0, 0, 4, 3, 4, 3, 0]])], + segmentation=[[0, 0, 0, 4, 3, 4, 3, 0]], + ) + ], DoesNotRaise(), - ), # segmentation mask in single component,no holes in mask, - # expects polygon mask + ), # segmentation mask in single component,no holes in mask, + # expects polygon mask ( Detections( xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32), @@ -577,6 +580,8 @@ def test_detections_to_coco_annotations( ) -> None: with exception: result, _ = detections_to_coco_annotations( - detections=detections, image_id=image_id, annotation_id=annotation_id, + detections=detections, + image_id=image_id, + annotation_id=annotation_id, ) assert result == expected_result From a40bf78bb20dcca49ad19c75b808a51d913da9f4 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 18:17:03 +0200 Subject: [PATCH 39/51] coco mock method refactoring --- supervision/dataset/formats/coco.py | 2 +- test/dataset/formats/test_coco.py | 68 ++++++++++++++--------------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index c8b73758..c07c2b52 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -157,7 +157,7 @@ def detections_to_coco_annotations( approximation_percentage=approximation_percentage, )[0].flatten() ) - ] # multicomponent masks supported only for rle format + ] coco_annotation = { "id": annotation_id, "image_id": image_id, diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 6be0fa2c..926a56e8 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -15,7 +15,7 @@ from supervision.dataset.formats.coco import ( ) -def mock_cock_coco_annotation( +def mock_coco_annotation( annotation_id: int = 0, image_id: int = 0, category_id: int = 0, @@ -107,10 +107,10 @@ def test_classes_to_coco_categories_and_back_to_classes( [ ([], {}, DoesNotRaise()), # empty coco annotations ( - [mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0)], + [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)], { 0: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=0, image_id=0, category_id=0 ) ] @@ -119,17 +119,17 @@ def test_classes_to_coco_categories_and_back_to_classes( ), # single coco annotation ( [ - mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0), - mock_cock_coco_annotation(annotation_id=1, image_id=1, category_id=0), + mock_coco_annotation(annotation_id=0, image_id=0, category_id=0), + mock_coco_annotation(annotation_id=1, image_id=1, category_id=0), ], { 0: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=0, image_id=0, category_id=0 ) ], 1: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=1, image_id=1, category_id=0 ) ], @@ -138,41 +138,41 @@ def test_classes_to_coco_categories_and_back_to_classes( ), # two coco annotations ( [ - mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0), - mock_cock_coco_annotation(annotation_id=1, image_id=1, category_id=1), - mock_cock_coco_annotation(annotation_id=2, image_id=1, category_id=2), - mock_cock_coco_annotation(annotation_id=3, image_id=2, category_id=3), - mock_cock_coco_annotation(annotation_id=4, image_id=3, category_id=1), - mock_cock_coco_annotation(annotation_id=5, image_id=3, category_id=2), - mock_cock_coco_annotation(annotation_id=5, image_id=3, category_id=3), + mock_coco_annotation(annotation_id=0, image_id=0, category_id=0), + mock_coco_annotation(annotation_id=1, image_id=1, category_id=1), + mock_coco_annotation(annotation_id=2, image_id=1, category_id=2), + mock_coco_annotation(annotation_id=3, image_id=2, category_id=3), + mock_coco_annotation(annotation_id=4, image_id=3, category_id=1), + mock_coco_annotation(annotation_id=5, image_id=3, category_id=2), + mock_coco_annotation(annotation_id=5, image_id=3, category_id=3), ], { 0: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=0, image_id=0, category_id=0 ), ], 1: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=1, image_id=1, category_id=1 ), - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=2, image_id=1, category_id=2 ), ], 2: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=3, image_id=2, category_id=3 ), ], 3: [ - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=4, image_id=3, category_id=1 ), - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=5, image_id=3, category_id=2 ), - mock_cock_coco_annotation( + mock_coco_annotation( annotation_id=5, image_id=3, category_id=3 ), ], @@ -201,7 +201,7 @@ def test_group_coco_annotations_by_image_id( ), # empty image annotations ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 100, 100), area=100 * 100 ) ], @@ -215,10 +215,10 @@ def test_group_coco_annotations_by_image_id( ), # single image annotations ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 100, 100), area=100 * 100 ), - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(100, 100, 100, 100), area=100 * 100 ), ], @@ -234,7 +234,7 @@ def test_group_coco_annotations_by_image_id( ), # two image annotations ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), area=5 * 5, @@ -262,7 +262,7 @@ def test_group_coco_annotations_by_image_id( ), # single image annotations with mask as polygon ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), area=5 * 5, @@ -294,13 +294,13 @@ def test_group_coco_annotations_by_image_id( ), # single image annotations with mask, RLE segmentation mask ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), area=5 * 5, segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]], ), - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(3, 0, 2, 2), area=2 * 2, @@ -339,7 +339,7 @@ def test_group_coco_annotations_by_image_id( ), # two image annotations with mask, one mask as polygon ans second as RLE ( [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(3, 0, 2, 2), area=2 * 2, @@ -349,7 +349,7 @@ def test_group_coco_annotations_by_image_id( }, iscrowd=True, ), - mock_cock_coco_annotation( + mock_coco_annotation( category_id=1, bbox=(0, 0, 5, 5), area=5 * 5, @@ -470,7 +470,7 @@ def test_build_coco_class_index_mapping( 0, 0, [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 100, 100), area=100 * 100 ) ], @@ -494,7 +494,7 @@ def test_build_coco_class_index_mapping( ), 0, 0, - [mock_cock_coco_annotation( + [mock_coco_annotation( category_id=0, bbox=(0, 0, 4, 5), area=4 * 5, @@ -521,7 +521,7 @@ def test_build_coco_class_index_mapping( 0, 0, [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), area=5 * 5, @@ -553,7 +553,7 @@ def test_build_coco_class_index_mapping( 0, 0, [ - mock_cock_coco_annotation( + mock_coco_annotation( category_id=0, bbox=(0, 0, 5, 5), area=5 * 5, From 2626263ff3f552634b301501b4824df160f2ee47 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 18:54:10 +0200 Subject: [PATCH 40/51] move has_holes and mask_has_multiple_segments to detections utils --- supervision/dataset/formats/coco.py | 25 ++++----------- supervision/detection/utils.py | 47 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index c07c2b52..b1d67fff 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -14,7 +14,11 @@ from supervision.dataset.utils import ( rle_to_mask, ) from supervision.detection.core import Detections -from supervision.detection.utils import polygon_to_mask +from supervision.detection.utils import ( + polygon_to_mask, + mask_has_multiple_segments, + mask_has_holes +) from supervision.utils.file import read_json_file, save_json_file @@ -107,23 +111,6 @@ def coco_annotations_to_detections( return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) -def _mask_has_holes(mask: np.ndarray) -> bool: - mask_uint8 = mask.astype(np.uint8) - _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - parent_countour_index = 3 - for h in hierarchy[0]: - if h[parent_countour_index] != -1: - return True - return False - - -def _mask_has_multiple_segments(mask: np.ndarray) -> bool: - mask_uint8 = mask.astype(np.uint8) - labels = np.zeros_like(mask_uint8, dtype=np.int32) - number_of_labels, _ = cv2.connectedComponents(mask_uint8, labels, connectivity=4) - return number_of_labels > 2 - - def detections_to_coco_annotations( detections: Detections, image_id: int, @@ -138,7 +125,7 @@ def detections_to_coco_annotations( segmentation = [] iscrowd = 0 if mask is not None: - iscrowd = _mask_has_holes(mask=mask) or _mask_has_multiple_segments( + iscrowd = mask_has_holes(mask=mask) or mask_has_multiple_segments( mask=mask ) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 3eeba5b4..1dd208bb 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Tuple, Union import cv2 import numpy as np +import numpy.typing as npt from supervision.config import CLASS_NAME_DATA_FIELD @@ -766,3 +767,49 @@ def get_data_item( raise TypeError(f"Unsupported data type for key '{key}': {type(value)}") return subset_data + + +def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: + """ + Checks if target objects in binary mask contain holes + (A hole is when background pixels are fully enclosed by foreground pixels) + + Args: + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground + object and `False` indicates background. + Returns: + True when holes are detected, False otherwise. + """ + mask_uint8 = mask.astype(np.uint8) + _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + parent_countour_index = 3 + for h in hierarchy[0]: + if h[parent_countour_index] != -1: + return True + return False + + +def mask_has_multiple_segments(mask: npt.NDArray[np.bool_], + connectivity:int = 4) -> bool: + """ + Checks if the binary mask consists of multiple not connected elements representing + the foreground objects. + Args: + mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground + object and `False` indicates background. + connectivity (int) : Default: 4 is 4-way connectivity, which means that + foreground pixels are the part of the same segment/component + if their edges touch. + Alternatively: 8 for 8-way connectivity, when foreground pixels are + connected by their edges or corners touch. + Returns: + True when the mask contains multiple not connected components, False otherwise. + """ + if connectivity!=4 and connectivity!=8: + raise ValueError('''Incorrect connectivity value,''' + ''' possible connectivity values: 4 or 8''') + mask_uint8 = mask.astype(np.uint8) + labels = np.zeros_like(mask_uint8, dtype=np.int32) + number_of_labels, _ = cv2.connectedComponents(mask_uint8, labels, + connectivity=connectivity) + return number_of_labels > 2 From 7ee84c48e02c22c6e51bb42f71372f5851cca65c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 20 May 2024 16:56:46 +0000 Subject: [PATCH 41/51] =?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/dataset/formats/coco.py | 8 ++--- supervision/detection/utils.py | 30 +++++++++-------- test/dataset/formats/test_coco.py | 51 +++++++---------------------- 3 files changed, 32 insertions(+), 57 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index b1d67fff..3c684871 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -15,9 +15,9 @@ from supervision.dataset.utils import ( ) from supervision.detection.core import Detections from supervision.detection.utils import ( - polygon_to_mask, + mask_has_holes, mask_has_multiple_segments, - mask_has_holes + polygon_to_mask, ) from supervision.utils.file import read_json_file, save_json_file @@ -125,9 +125,7 @@ def detections_to_coco_annotations( segmentation = [] iscrowd = 0 if mask is not None: - iscrowd = mask_has_holes(mask=mask) or mask_has_multiple_segments( - mask=mask - ) + iscrowd = mask_has_holes(mask=mask) or mask_has_multiple_segments(mask=mask) if iscrowd: segmentation = { diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 1dd208bb..f00641fb 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -771,7 +771,7 @@ def get_data_item( def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: """ - Checks if target objects in binary mask contain holes + Checks if target objects in binary mask contain holes (A hole is when background pixels are fully enclosed by foreground pixels) Args: @@ -789,27 +789,31 @@ def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: return False -def mask_has_multiple_segments(mask: npt.NDArray[np.bool_], - connectivity:int = 4) -> bool: +def mask_has_multiple_segments( + mask: npt.NDArray[np.bool_], connectivity: int = 4 +) -> bool: """ - Checks if the binary mask consists of multiple not connected elements representing + Checks if the binary mask consists of multiple not connected elements representing the foreground objects. Args: mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object and `False` indicates background. - connectivity (int) : Default: 4 is 4-way connectivity, which means that - foreground pixels are the part of the same segment/component - if their edges touch. - Alternatively: 8 for 8-way connectivity, when foreground pixels are + connectivity (int) : Default: 4 is 4-way connectivity, which means that + foreground pixels are the part of the same segment/component + if their edges touch. + Alternatively: 8 for 8-way connectivity, when foreground pixels are connected by their edges or corners touch. Returns: True when the mask contains multiple not connected components, False otherwise. """ - if connectivity!=4 and connectivity!=8: - raise ValueError('''Incorrect connectivity value,''' - ''' possible connectivity values: 4 or 8''') + if connectivity != 4 and connectivity != 8: + raise ValueError( + """Incorrect connectivity value,""" + """ possible connectivity values: 4 or 8""" + ) mask_uint8 = mask.astype(np.uint8) labels = np.zeros_like(mask_uint8, dtype=np.int32) - number_of_labels, _ = cv2.connectedComponents(mask_uint8, labels, - connectivity=connectivity) + number_of_labels, _ = cv2.connectedComponents( + mask_uint8, labels, connectivity=connectivity + ) return number_of_labels > 2 diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 9c89b964..7e269dae 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -108,13 +108,7 @@ def test_classes_to_coco_categories_and_back_to_classes( ([], {}, DoesNotRaise()), # empty coco annotations ( [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)], - { - 0: [ - mock_coco_annotation( - annotation_id=0, image_id=0, category_id=0 - ) - ] - }, + {0: [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)]}, DoesNotRaise(), ), # single coco annotation ( @@ -123,16 +117,8 @@ def test_classes_to_coco_categories_and_back_to_classes( mock_coco_annotation(annotation_id=1, image_id=1, category_id=0), ], { - 0: [ - mock_coco_annotation( - annotation_id=0, image_id=0, category_id=0 - ) - ], - 1: [ - mock_coco_annotation( - annotation_id=1, image_id=1, category_id=0 - ) - ], + 0: [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)], + 1: [mock_coco_annotation(annotation_id=1, image_id=1, category_id=0)], }, DoesNotRaise(), ), # two coco annotations @@ -148,33 +134,19 @@ def test_classes_to_coco_categories_and_back_to_classes( ], { 0: [ - mock_coco_annotation( - annotation_id=0, image_id=0, category_id=0 - ), + mock_coco_annotation(annotation_id=0, image_id=0, category_id=0), ], 1: [ - mock_coco_annotation( - annotation_id=1, image_id=1, category_id=1 - ), - mock_coco_annotation( - annotation_id=2, image_id=1, category_id=2 - ), + mock_coco_annotation(annotation_id=1, image_id=1, category_id=1), + mock_coco_annotation(annotation_id=2, image_id=1, category_id=2), ], 2: [ - mock_coco_annotation( - annotation_id=3, image_id=2, category_id=3 - ), + mock_coco_annotation(annotation_id=3, image_id=2, category_id=3), ], 3: [ - mock_coco_annotation( - annotation_id=4, image_id=3, category_id=1 - ), - mock_coco_annotation( - annotation_id=5, image_id=3, category_id=2 - ), - mock_coco_annotation( - annotation_id=5, image_id=3, category_id=3 - ), + mock_coco_annotation(annotation_id=4, image_id=3, category_id=1), + mock_coco_annotation(annotation_id=5, image_id=3, category_id=2), + mock_coco_annotation(annotation_id=5, image_id=3, category_id=3), ], }, DoesNotRaise(), @@ -494,7 +466,8 @@ def test_build_coco_class_index_mapping( ), 0, 0, - [mock_coco_annotation( + [ + mock_coco_annotation( category_id=0, bbox=(0, 0, 4, 5), area=4 * 5, From 68f07e18f38c208b5e9177b4a957d511a2eaf247 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 19:23:22 +0200 Subject: [PATCH 42/51] tests for mask_has_holes --- supervision/detection/utils.py | 15 ++++++--- test/detection/test_utils.py | 59 ++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 1dd208bb..b39b7b38 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -782,10 +782,12 @@ def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: """ mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - parent_countour_index = 3 - for h in hierarchy[0]: - if h[parent_countour_index] != -1: - return True + + if hierarchy: # at least one contour was found + parent_countour_index = 3 + for h in hierarchy[0]: + if h[parent_countour_index] != -1: + return True return False @@ -794,6 +796,7 @@ def mask_has_multiple_segments(mask: npt.NDArray[np.bool_], """ Checks if the binary mask consists of multiple not connected elements representing the foreground objects. + Args: mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object and `False` indicates background. @@ -802,8 +805,12 @@ def mask_has_multiple_segments(mask: npt.NDArray[np.bool_], if their edges touch. Alternatively: 8 for 8-way connectivity, when foreground pixels are connected by their edges or corners touch. + Returns: True when the mask contains multiple not connected components, False otherwise. + + Raises: + ValueError: If connectivity(int) parameter value is not 4 or 8. """ if connectivity!=4 and connectivity!=8: raise ValueError('''Incorrect connectivity value,''' diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index 1c4a1d34..1214cfed 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -2,6 +2,7 @@ from contextlib import ExitStack as DoesNotRaise from typing import Any, Dict, List, Optional, Tuple import numpy as np +import numpy.typing as npt import pytest from supervision.config import CLASS_NAME_DATA_FIELD @@ -16,6 +17,8 @@ from supervision.detection.utils import ( move_boxes, process_roboflow_result, scale_boxes, + mask_has_holes, + mask_has_multiple_segments, ) TEST_MASK = np.zeros((1, 1000, 1000), dtype=bool) @@ -1203,3 +1206,59 @@ def test_get_data_item( assert ( result[key] == expected_result[key] ), f"Mismatch in non-array data for key {key}" + + +@pytest.mark.parametrize( + "mask, expected_result, exception", + [ + (np.array([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 1, 0, 0], + [0, 1, 1, 0]]).astype(bool), + False, + DoesNotRaise(), + ), # foreground object in one continuous piece + (np.array([[1, 0, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, 0], + [0, 1, 1, 0]]).astype(bool), + False, + DoesNotRaise(), + ), # foreground object in 2 seperate elements + (np.array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]]).astype(bool), + False, + DoesNotRaise(), + ), # no foreground pixels in mask + (np.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]]).astype(bool), + False, + DoesNotRaise(), + ), # only foreground pixels in mask + (np.array([[1, 1, 1, 0], + [1, 0, 1, 0], + [1, 1, 1, 0], + [0, 0, 0, 0]]).astype(bool), + True, + DoesNotRaise(), + ), # foreground object has 1 hole + (np.array([[1, 1, 1, 0], + [1, 0, 1, 1], + [1, 1, 0, 1], + [0, 1, 1, 1]]).astype(bool), + True, + DoesNotRaise(), + ), # foreground object has 2 holes + ], +) +def test_mask_has_holes( + mask: npt.NDArray[np.bool_], expected_result: bool, exception: Exception +) -> None: + with exception: + result = mask_has_holes(mask) + assert result == expected_result + \ No newline at end of file From c26eb1a70f4271930ca0f17ee3f13aa70892b0be Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 19:52:48 +0200 Subject: [PATCH 43/51] unit tests for test_mask_has_multiple_segments --- test/detection/test_utils.py | 81 +++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index 1214cfed..a9472f85 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -1261,4 +1261,83 @@ def test_mask_has_holes( with exception: result = mask_has_holes(mask) assert result == expected_result - \ No newline at end of file + + +@pytest.mark.parametrize( + "mask, connectivity, expected_result, exception", + [ + (np.array([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 1, 0, 0], + [0, 1, 1, 0]]).astype(bool), + 4, + False, + DoesNotRaise(), + ), # foreground object in one continuous piece + (np.array([[1, 0, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, 0], + [0, 1, 1, 0]]).astype(bool), + 4, + True, + DoesNotRaise(), + ), # foreground object in 2 seperate elements + (np.array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]]).astype(bool), + 4, + False, + DoesNotRaise(), + ), # no foreground pixels in mask + (np.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]]).astype(bool), + 4, + False, + DoesNotRaise(), + ), # only foreground pixels in mask + (np.array([[1, 1, 1, 0], + [1, 0, 1, 1], + [1, 1, 0, 1], + [0, 1, 1, 1]]).astype(bool), + 4, + False, + DoesNotRaise(), + ), # foreground object has 2 holes, but is in single piece + (np.array([[1, 1, 0, 0], + [1, 1, 0, 1], + [1, 0, 1, 1], + [0, 0, 1, 1]]).astype(bool), + 4, + True, + DoesNotRaise(), + ), # foreground object in 2 elements with respect to 4-way connectivity + (np.array([[1, 1, 0, 0], + [1, 1, 0, 1], + [1, 0, 1, 1], + [0, 0, 1, 1]]).astype(bool), + 8, + False, + DoesNotRaise(), + ), # foreground object in single piece with respect to 8-way connectivity + (np.array([[1, 1, 0, 0], + [1, 1, 0, 1], + [1, 0, 1, 1], + [0, 0, 1, 1]]).astype(bool), + 5, + None, + pytest.raises(ValueError), + ), # Incorrect connectivity parameter value, raises ValueError + ], +) +def test_mask_has_multiple_segments( + mask: npt.NDArray[np.bool_], + connectivity: int, + expected_result: bool, + exception: Exception +) -> None: + with exception: + result = mask_has_multiple_segments(mask = mask, connectivity=connectivity) + assert result == expected_result From dfac30cba7eb626236d0c60bf01091e42db82949 Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 20:45:17 +0200 Subject: [PATCH 44/51] change docu for mask_has_multiple_segments and mask_has_holes and add to global __init__.py --- docs/detection/utils.md | 12 ++++++++++++ supervision/__init__.py | 2 ++ 2 files changed, 14 insertions(+) diff --git a/docs/detection/utils.md b/docs/detection/utils.md index abacdc21..9271c23d 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -70,3 +70,15 @@ status: new :::supervision.detection.utils.scale_boxes + + + +:::supervision.detection.utils.mask_has_holes + + + +:::supervision.detection.utils.mask_has_multiple_segments diff --git a/supervision/__init__.py b/supervision/__init__.py index 2bc72944..caa0e5ae 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -56,6 +56,8 @@ from supervision.detection.utils import ( polygon_to_mask, polygon_to_xyxy, scale_boxes, + mask_has_holes, + mask_has_multiple_segments, ) from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( From ab55e810876749e4bc62397c9aa39f1e71d4812c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 20 May 2024 19:41:32 +0000 Subject: [PATCH 45/51] =?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/utils.md | 2 +- supervision/__init__.py | 4 +- supervision/detection/utils.py | 2 +- test/detection/test_utils.py | 228 ++++++++++++++++----------------- 4 files changed, 118 insertions(+), 118 deletions(-) diff --git a/docs/detection/utils.md b/docs/detection/utils.md index 8b9f91f7..0c42a69e 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -99,4 +99,4 @@ status: new

mask_has_multiple_segments

-:::supervision.detection.utils.mask_has_multiple_segments \ No newline at end of file +:::supervision.detection.utils.mask_has_multiple_segments diff --git a/supervision/__init__.py b/supervision/__init__.py index 7f50a7ad..51b43ef0 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -50,6 +50,8 @@ from supervision.detection.utils import ( calculate_masks_centroids, clip_boxes, filter_polygons_by_area, + mask_has_holes, + mask_has_multiple_segments, mask_iou_batch, mask_non_max_suppression, mask_to_polygons, @@ -60,8 +62,6 @@ from supervision.detection.utils import ( polygon_to_mask, polygon_to_xyxy, scale_boxes, - mask_has_holes, - mask_has_multiple_segments, ) from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 9dd3d734..35510060 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -857,7 +857,7 @@ def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - if hierarchy: # at least one contour was found + if hierarchy: # at least one contour was found parent_countour_index = 3 for h in hierarchy[0]: if h[parent_countour_index] != -1: diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index b72ca4bf..2821aed2 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -12,13 +12,13 @@ from supervision.detection.utils import ( clip_boxes, filter_polygons_by_area, get_data_item, + mask_has_holes, + mask_has_multiple_segments, mask_non_max_suppression, merge_data, move_boxes, process_roboflow_result, scale_boxes, - mask_has_holes, - mask_has_multiple_segments, ) TEST_MASK = np.zeros((1, 1000, 1000), dtype=bool) @@ -1273,48 +1273,48 @@ def test_get_data_item( @pytest.mark.parametrize( "mask, expected_result, exception", [ - (np.array([[0, 0, 0, 0], - [0, 1, 1, 0], - [0, 1, 0, 0], - [0, 1, 1, 0]]).astype(bool), - False, - DoesNotRaise(), - ), # foreground object in one continuous piece - (np.array([[1, 0, 0, 0], - [1, 0, 0, 0], - [0, 0, 0, 0], - [0, 1, 1, 0]]).astype(bool), - False, - DoesNotRaise(), - ), # foreground object in 2 seperate elements - (np.array([[0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0]]).astype(bool), - False, - DoesNotRaise(), - ), # no foreground pixels in mask - (np.array([[1, 1, 1, 1], - [1, 1, 1, 1], - [1, 1, 1, 1], - [1, 1, 1, 1]]).astype(bool), - False, - DoesNotRaise(), - ), # only foreground pixels in mask - (np.array([[1, 1, 1, 0], - [1, 0, 1, 0], - [1, 1, 1, 0], - [0, 0, 0, 0]]).astype(bool), - True, - DoesNotRaise(), - ), # foreground object has 1 hole - (np.array([[1, 1, 1, 0], - [1, 0, 1, 1], - [1, 1, 0, 1], - [0, 1, 1, 1]]).astype(bool), - True, - DoesNotRaise(), - ), # foreground object has 2 holes + ( + np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 1, 0]]).astype( + bool + ), + False, + DoesNotRaise(), + ), # foreground object in one continuous piece + ( + np.array([[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]).astype( + bool + ), + False, + DoesNotRaise(), + ), # foreground object in 2 seperate elements + ( + np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]).astype( + bool + ), + False, + DoesNotRaise(), + ), # no foreground pixels in mask + ( + np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]).astype( + bool + ), + False, + DoesNotRaise(), + ), # only foreground pixels in mask + ( + np.array([[1, 1, 1, 0], [1, 0, 1, 0], [1, 1, 1, 0], [0, 0, 0, 0]]).astype( + bool + ), + True, + DoesNotRaise(), + ), # foreground object has 1 hole + ( + np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]).astype( + bool + ), + True, + DoesNotRaise(), + ), # foreground object has 2 holes ], ) def test_mask_has_holes( @@ -1322,84 +1322,84 @@ def test_mask_has_holes( ) -> None: with exception: result = mask_has_holes(mask) - assert result == expected_result + assert result == expected_result @pytest.mark.parametrize( "mask, connectivity, expected_result, exception", [ - (np.array([[0, 0, 0, 0], - [0, 1, 1, 0], - [0, 1, 0, 0], - [0, 1, 1, 0]]).astype(bool), - 4, - False, - DoesNotRaise(), - ), # foreground object in one continuous piece - (np.array([[1, 0, 0, 0], - [1, 0, 0, 0], - [0, 0, 0, 0], - [0, 1, 1, 0]]).astype(bool), - 4, - True, - DoesNotRaise(), - ), # foreground object in 2 seperate elements - (np.array([[0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0]]).astype(bool), - 4, - False, - DoesNotRaise(), - ), # no foreground pixels in mask - (np.array([[1, 1, 1, 1], - [1, 1, 1, 1], - [1, 1, 1, 1], - [1, 1, 1, 1]]).astype(bool), - 4, - False, - DoesNotRaise(), - ), # only foreground pixels in mask - (np.array([[1, 1, 1, 0], - [1, 0, 1, 1], - [1, 1, 0, 1], - [0, 1, 1, 1]]).astype(bool), - 4, - False, - DoesNotRaise(), - ), # foreground object has 2 holes, but is in single piece - (np.array([[1, 1, 0, 0], - [1, 1, 0, 1], - [1, 0, 1, 1], - [0, 0, 1, 1]]).astype(bool), - 4, - True, - DoesNotRaise(), - ), # foreground object in 2 elements with respect to 4-way connectivity - (np.array([[1, 1, 0, 0], - [1, 1, 0, 1], - [1, 0, 1, 1], - [0, 0, 1, 1]]).astype(bool), - 8, - False, - DoesNotRaise(), - ), # foreground object in single piece with respect to 8-way connectivity - (np.array([[1, 1, 0, 0], - [1, 1, 0, 1], - [1, 0, 1, 1], - [0, 0, 1, 1]]).astype(bool), - 5, - None, - pytest.raises(ValueError), - ), # Incorrect connectivity parameter value, raises ValueError + ( + np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 1, 0]]).astype( + bool + ), + 4, + False, + DoesNotRaise(), + ), # foreground object in one continuous piece + ( + np.array([[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]).astype( + bool + ), + 4, + True, + DoesNotRaise(), + ), # foreground object in 2 seperate elements + ( + np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]).astype( + bool + ), + 4, + False, + DoesNotRaise(), + ), # no foreground pixels in mask + ( + np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]).astype( + bool + ), + 4, + False, + DoesNotRaise(), + ), # only foreground pixels in mask + ( + np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]).astype( + bool + ), + 4, + False, + DoesNotRaise(), + ), # foreground object has 2 holes, but is in single piece + ( + np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype( + bool + ), + 4, + True, + DoesNotRaise(), + ), # foreground object in 2 elements with respect to 4-way connectivity + ( + np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype( + bool + ), + 8, + False, + DoesNotRaise(), + ), # foreground object in single piece with respect to 8-way connectivity + ( + np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype( + bool + ), + 5, + None, + pytest.raises(ValueError), + ), # Incorrect connectivity parameter value, raises ValueError ], ) def test_mask_has_multiple_segments( mask: npt.NDArray[np.bool_], - connectivity: int, - expected_result: bool, - exception: Exception + connectivity: int, + expected_result: bool, + exception: Exception, ) -> None: with exception: - result = mask_has_multiple_segments(mask = mask, connectivity=connectivity) - assert result == expected_result + result = mask_has_multiple_segments(mask=mask, connectivity=connectivity) + assert result == expected_result From 6dbf3f61e3e764c56c6152f18088f7624354d1dd Mon Sep 17 00:00:00 2001 From: magda skoczen Date: Mon, 20 May 2024 21:47:04 +0200 Subject: [PATCH 46/51] fix for unit tests for test_mask_has_holes --- supervision/detection/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 35510060..89728c7a 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -857,7 +857,7 @@ def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - if hierarchy: # at least one contour was found + if hierarchy is not None: # at least one contour was found parent_countour_index = 3 for h in hierarchy[0]: if h[parent_countour_index] != -1: From f2716252d59ac60da041f1e3bab1b1744726d79a Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 21 May 2024 11:43:09 +0200 Subject: [PATCH 47/51] small refactor + docs improvements --- docs/detection/utils.md | 10 +-- supervision/__init__.py | 4 +- supervision/dataset/formats/coco.py | 6 +- supervision/detection/utils.py | 106 ++++++++++++++++++++++------ test/detection/test_utils.py | 12 ++-- 5 files changed, 100 insertions(+), 38 deletions(-) diff --git a/docs/detection/utils.md b/docs/detection/utils.md index 0c42a69e..f9c9473b 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -78,7 +78,7 @@ status: new :::supervision.detection.utils.scale_boxes :::supervision.detection.utils.clip_boxes @@ -90,13 +90,13 @@ status: new :::supervision.detection.utils.pad_boxes -:::supervision.detection.utils.mask_has_holes +:::supervision.detection.utils.contains_holes -:::supervision.detection.utils.mask_has_multiple_segments +:::supervision.detection.utils.contains_multiple_segments diff --git a/supervision/__init__.py b/supervision/__init__.py index 51b43ef0..af5f8dcc 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -50,8 +50,8 @@ from supervision.detection.utils import ( calculate_masks_centroids, clip_boxes, filter_polygons_by_area, - mask_has_holes, - mask_has_multiple_segments, + contains_holes, + contains_multiple_segments, mask_iou_batch, mask_non_max_suppression, mask_to_polygons, diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 3c684871..353e33f5 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -15,8 +15,8 @@ from supervision.dataset.utils import ( ) from supervision.detection.core import Detections from supervision.detection.utils import ( - mask_has_holes, - mask_has_multiple_segments, + contains_holes, + contains_multiple_segments, polygon_to_mask, ) from supervision.utils.file import read_json_file, save_json_file @@ -125,7 +125,7 @@ def detections_to_coco_annotations( segmentation = [] iscrowd = 0 if mask is not None: - iscrowd = mask_has_holes(mask=mask) or mask_has_multiple_segments(mask=mask) + iscrowd = contains_holes(mask=mask) or contains_multiple_segments(mask=mask) if iscrowd: segmentation = { diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 89728c7a..5a8e7ba2 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -609,13 +609,16 @@ def move_boxes(xyxy: np.ndarray, offset: np.ndarray) -> np.ndarray: import numpy as np import supervision as sv - boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]]) + xyxy = np.array([ + [10, 10, 20, 20], + [30, 30, 40, 40] + ]) offset = np.array([5, 5]) - moved_box = sv.move_boxes(boxes, offset) - print(moved_box) - # np.array([ + + sv.move_boxes(xyxy=xyxy, offset=offset) + # array([ # [15, 15, 25, 25], - # [35, 35, 45, 45] + # [35, 35, 45, 45] # ]) ``` """ @@ -675,11 +678,13 @@ def scale_boxes(xyxy: np.ndarray, factor: float) -> np.ndarray: import numpy as np import supervision as sv - boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]]) - factor = 1.5 - scaled_bb = sv.scale_boxes(boxes, factor) - print(scaled_bb) - # np.array([ + xyxy = np.array([ + [10, 10, 20, 20], + [30, 30, 40, 40] + ]) + + scaled_bb = sv.scale_boxes(xyxy=xyxy, factor=1.5) + # array([ # [ 7.5, 7.5, 22.5, 22.5], # [27.5, 27.5, 42.5, 42.5] # ]) @@ -843,34 +848,62 @@ def get_data_item( return subset_data -def mask_has_holes(mask: npt.NDArray[np.bool_]) -> bool: +def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: """ - Checks if target objects in binary mask contain holes - (A hole is when background pixels are fully enclosed by foreground pixels) + Checks if the binary mask contains holes (background pixels fully enclosed by + foreground pixels). Args: mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground object and `False` indicates background. + Returns: - True when holes are detected, False otherwise. + True if holes are detected, False otherwise. + + Examples: + ```python + import numpy as np + import supervision as sv + + mask = np.array([ + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0] + ]).astype(bool) + + sv.contains_holes(mask=mask) + # True + + mask = np.array([ + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0] + ]).astype(bool) + + sv.contains_holes(mask=mask) + # False + ``` """ mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - if hierarchy is not None: # at least one contour was found - parent_countour_index = 3 + if hierarchy is not None: + parent_contour_index = 3 for h in hierarchy[0]: - if h[parent_countour_index] != -1: + if h[parent_contour_index] != -1: return True return False -def mask_has_multiple_segments( +def contains_multiple_segments( mask: npt.NDArray[np.bool_], connectivity: int = 4 ) -> bool: """ - Checks if the binary mask consists of multiple not connected elements representing - the foreground objects. + Checks if the binary mask contains multiple unconnected foreground segments. Args: mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground @@ -886,11 +919,40 @@ def mask_has_multiple_segments( Raises: ValueError: If connectivity(int) parameter value is not 4 or 8. + + Examples: + ```python + import numpy as np + import supervision as sv + + mask = np.array([ + [0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 1], + [0, 1, 1, 0, 1, 1], + [0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 0, 0] + ]).astype(bool) + + sv.contains_multiple_segments(mask=mask, connectivity=4) + # True + + mask = np.array([ + [0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0] + ]).astype(bool) + + sv.contains_multiple_segments(mask=mask, connectivity=4) + # False + ``` """ if connectivity != 4 and connectivity != 8: raise ValueError( - """Incorrect connectivity value,""" - """ possible connectivity values: 4 or 8""" + "Incorrect connectivity value. Possible connectivity values: 4 or 8." ) mask_uint8 = mask.astype(np.uint8) labels = np.zeros_like(mask_uint8, dtype=np.int32) diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index 2821aed2..c7ed674a 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -12,8 +12,8 @@ from supervision.detection.utils import ( clip_boxes, filter_polygons_by_area, get_data_item, - mask_has_holes, - mask_has_multiple_segments, + contains_holes, + contains_multiple_segments, mask_non_max_suppression, merge_data, move_boxes, @@ -1317,11 +1317,11 @@ def test_get_data_item( ), # foreground object has 2 holes ], ) -def test_mask_has_holes( +def test_contains_holes( mask: npt.NDArray[np.bool_], expected_result: bool, exception: Exception ) -> None: with exception: - result = mask_has_holes(mask) + result = contains_holes(mask) assert result == expected_result @@ -1394,12 +1394,12 @@ def test_mask_has_holes( ), # Incorrect connectivity parameter value, raises ValueError ], ) -def test_mask_has_multiple_segments( +def test_contains_multiple_segments( mask: npt.NDArray[np.bool_], connectivity: int, expected_result: bool, exception: Exception, ) -> None: with exception: - result = mask_has_multiple_segments(mask=mask, connectivity=connectivity) + result = contains_multiple_segments(mask=mask, connectivity=connectivity) assert result == expected_result From 996b0a3af346f15fb0e692b6d58bcbf98a2de3ba Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 May 2024 09:43:28 +0000 Subject: [PATCH 48/51] =?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 | 2 +- test/detection/test_utils.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/supervision/__init__.py b/supervision/__init__.py index af5f8dcc..abe63390 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -49,9 +49,9 @@ from supervision.detection.utils import ( box_non_max_suppression, calculate_masks_centroids, clip_boxes, - filter_polygons_by_area, contains_holes, contains_multiple_segments, + filter_polygons_by_area, mask_iou_batch, mask_non_max_suppression, mask_to_polygons, diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index c7ed674a..6a2070da 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -10,10 +10,10 @@ from supervision.detection.utils import ( box_non_max_suppression, calculate_masks_centroids, clip_boxes, - filter_polygons_by_area, - get_data_item, contains_holes, contains_multiple_segments, + filter_polygons_by_area, + get_data_item, mask_non_max_suppression, merge_data, move_boxes, From 1d43042c55418ecba8fcfbfe7973e65e15147f03 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 21 May 2024 12:01:05 +0200 Subject: [PATCH 49/51] small refactor + docs improvements --- supervision/dataset/core.py | 38 ++++++++++++++++++++-------------- supervision/detection/utils.py | 4 ++-- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 6ae5844a..c8863df3 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -116,13 +116,12 @@ class DetectionDataset(BaseDataset): Tuple[DetectionDataset, DetectionDataset]: A tuple containing the training and testing datasets. - Example: + Examples: ```python import supervision as sv ds = sv.DetectionDataset(...) - train_ds, test_ds = ds.split(split_ratio=0.7, - random_state=42, shuffle=True) + train_ds, test_ds = ds.split(split_ratio=0.7, random_state=42, shuffle=True) len(train_ds), len(test_ds) # (700, 300) ``` @@ -229,7 +228,7 @@ class DetectionDataset(BaseDataset): DetectionDataset: A DetectionDataset instance containing the loaded images and annotations. - Example: + Examples: ```python import roboflow from roboflow import Roboflow @@ -286,7 +285,7 @@ class DetectionDataset(BaseDataset): DetectionDataset: A DetectionDataset instance containing the loaded images and annotations. - Example: + Examples: ```python import roboflow from roboflow import Roboflow @@ -391,7 +390,7 @@ class DetectionDataset(BaseDataset): DetectionDataset: A DetectionDataset instance containing the loaded images and annotations. - Example: + Examples: ```python import roboflow from roboflow import Roboflow @@ -430,10 +429,20 @@ class DetectionDataset(BaseDataset): """ Exports the dataset to COCO format. This method saves the images and their corresponding annotations in COCO format. - The format of the mask is determined automatically: - when a mask consists of multiple disconnected elements - or has holes the RLE format is used, - otherwise, the mask is encoded as a polygon. + + !!! tip + + The format of the mask is determined automatically based on its structure: + + - If a mask contains multiple disconnected components or holes, it will be + saved using the Run-Length Encoding (RLE) format for efficient storage and + processing. + - If a mask consists of a single, contiguous region without any holes, it + will be encoded as a polygon, preserving the outline of the object. + + This automatic selection ensures that the masks are stored in the most + appropriate and space-efficient format, complying with COCO dataset + standards. Args: images_directory_path (Optional[str]): The path to the directory @@ -486,7 +495,7 @@ class DetectionDataset(BaseDataset): (DetectionDataset): A single `DetectionDataset` object containing the merged data from the input list. - Example: + Examples: ```python import supervision as sv @@ -571,13 +580,12 @@ class ClassificationDataset(BaseDataset): Tuple[ClassificationDataset, ClassificationDataset]: A tuple containing the training and testing datasets. - Example: + Examples: ```python import supervision as sv cd = sv.ClassificationDataset(...) - train_cd,test_cd = cd.split(split_ratio=0.7, - random_state=42,shuffle=True) + train_cd,test_cd = cd.split(split_ratio=0.7, random_state=42,shuffle=True) len(train_cd), len(test_cd) # (700, 300) ``` @@ -639,7 +647,7 @@ class ClassificationDataset(BaseDataset): Returns: ClassificationDataset: The dataset. - Example: + Examples: ```python import roboflow from roboflow import Roboflow diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 5a8e7ba2..f1e77883 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -604,7 +604,7 @@ def move_boxes(xyxy: np.ndarray, offset: np.ndarray) -> np.ndarray: Returns: np.ndarray: Repositioned bounding boxes. - Example: + Examples: ```python import numpy as np import supervision as sv @@ -673,7 +673,7 @@ def scale_boxes(xyxy: np.ndarray, factor: float) -> np.ndarray: Returns: np.ndarray: Scaled bounding boxes. - Example: + Examples: ```python import numpy as np import supervision as sv From c3855c982847f6a74d69da3062ee76ed98690997 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 21 May 2024 13:08:02 +0200 Subject: [PATCH 50/51] small refactor + docs improvements --- supervision/dataset/utils.py | 28 ++++++++++++++++++---------- supervision/detection/utils.py | 8 ++++++-- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index 4efc7194..a43fbe5a 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -159,10 +159,12 @@ def rle_to_mask( ```python import supervision as sv - sv.rle_to_mask([2, 2, 2], (3, 2)) + sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4)) # array([ - # [False, True, False], - # [False, True, False] + # [False, False, False, False], + # [False, True, True, False], + # [False, True, True, False], + # [False, False, False, False], # ]) ``` """ @@ -209,20 +211,26 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: import supervision as sv mask = np.array([ - [False, True, True], - [False, True, True] + [True, True, True, True], + [True, True, True, True], + [True, True, True, True], + [True, True, True, True], ]) sv.mask_to_rle(mask) - # [2, 4] + # [0, 16] mask = np.array([ - [True, True, True], - [True, True, True] + [False, False, False, False], + [False, True, True, False], + [False, True, True, False], + [False, False, False, False], ]) sv.mask_to_rle(mask) - # [0, 6] + # [5, 2, 2, 2, 5] ``` - """ + + ![mask_to_rle](https://media.roboflow.com/supervision-docs/mask-to-rle.png){ align=center width="800" } + """ # noqa E501 // docs assert mask.ndim == 2, "Input mask must be 2D" assert mask.size != 0, "Input mask cannot be empty" diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index f1e77883..f9f71f98 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -887,7 +887,9 @@ def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: sv.contains_holes(mask=mask) # False ``` - """ + + ![contains_holes](https://media.roboflow.com/supervision-docs/contains-holes.png){ align=center width="800" } + """ # noqa E501 // docs mask_uint8 = mask.astype(np.uint8) _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) @@ -949,7 +951,9 @@ def contains_multiple_segments( sv.contains_multiple_segments(mask=mask, connectivity=4) # False ``` - """ + + ![contains_multiple_segments](https://media.roboflow.com/supervision-docs/contains-multiple-segments.png){ align=center width="800" } + """ # noqa E501 // docs if connectivity != 4 and connectivity != 8: raise ValueError( "Incorrect connectivity value. Possible connectivity values: 4 or 8." From 58408898180f9dc5370c5a17e043aa31db44c7a5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 May 2024 11:08:19 +0000 Subject: [PATCH 51/51] =?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/dataset/utils.py | 2 +- supervision/detection/utils.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py index a43fbe5a..32ece6bf 100644 --- a/supervision/dataset/utils.py +++ b/supervision/dataset/utils.py @@ -228,7 +228,7 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]: sv.mask_to_rle(mask) # [5, 2, 2, 2, 5] ``` - + ![mask_to_rle](https://media.roboflow.com/supervision-docs/mask-to-rle.png){ align=center width="800" } """ # noqa E501 // docs assert mask.ndim == 2, "Input mask must be 2D" diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index f9f71f98..742f94f6 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -887,7 +887,7 @@ def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: sv.contains_holes(mask=mask) # False ``` - + ![contains_holes](https://media.roboflow.com/supervision-docs/contains-holes.png){ align=center width="800" } """ # noqa E501 // docs mask_uint8 = mask.astype(np.uint8) @@ -951,7 +951,7 @@ def contains_multiple_segments( sv.contains_multiple_segments(mask=mask, connectivity=4) # False ``` - + ![contains_multiple_segments](https://media.roboflow.com/supervision-docs/contains-multiple-segments.png){ align=center width="800" } """ # noqa E501 // docs if connectivity != 4 and connectivity != 8: