From d7e08d42eb0ebf0acf47bbdbb07a7342e43140b7 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 10:20:47 +0200 Subject: [PATCH 01/24] add load_pascal_voc_annotations v2 --- supervision/dataset/formats/pascal_voc.py | 93 ++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index a3005eb9..bca886d4 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -1,12 +1,16 @@ -from typing import List, Optional, Tuple +import os +from pathlib import Path +from typing import Dict, List, Optional, Tuple from xml.dom.minidom import parseString from xml.etree.ElementTree import Element, SubElement, parse, tostring +import cv2 import numpy as np from supervision.dataset.utils import approximate_mask_with_polygons from supervision.detection.core import Detections from supervision.detection.utils import polygon_to_xyxy +from supervision.utils.file import list_files_with_extensions def object_to_pascal_voc( @@ -120,6 +124,93 @@ def detections_to_pascal_voc( def load_pascal_voc_annotations( + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, +) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: + """ + Loads PASCAL VOC XML annotations and returns the image name, a Detections instance, and a list of class names. + + Args: + annotation_path (str): The path to the PASCAL VOC XML annotations file. + + Returns: + Tuple[str, Detections, List[str]]: A tuple containing the image name, a Detections instance, and a list of class names of objects in the detections. + """ + + image_paths = list_files_with_extensions( + directory=images_directory_path, extensions=["jpg", "jpeg", "png"] + ) + + classes = [] + images = {} + annotations = {} + + for image_path in image_paths: + image_name = Path(image_path).stem + image = cv2.imread(str(image_path)) + + annotation_path = os.path.join(annotations_directory_path, f"{image_name}.xml") + if not os.path.exists(annotation_path): + images[image_path.name] = image + annotations[image_path.name] = Detections.empty() + continue + + tree = parse(annotation_path) + root = tree.getroot() + + xyxy = [] + class_names = [] + masks = [] + for obj in root.findall("object"): + class_name = obj.find("name").text + class_names.append(class_name) + + bbox = obj.find("bndbox") + x1 = int(bbox.find("xmin").text) + y1 = int(bbox.find("ymin").text) + x2 = int(bbox.find("xmax").text) + y2 = int(bbox.find("ymax").text) + + xyxy.append([x1, y1, x2, y2]) + + with_masks = obj.find("polygon") is not None + with_masks = force_masks if force_masks else with_masks + + for polygon in obj.findall("polygon"): + polygon_points = [] + coords = polygon.findall(".//*") + for i in range(0, len(coords), 2): + x = int(coords[i].text) + y = int(coords[i + 1].text) + polygon_points.append([x, y]) + + mask_from_polygon = polygon_to_mask( + polygon=np.array(polygon_points), + resolution_wh=(image.shape[0], image.shape[1]), + ) + masks.append(mask_from_polygon) + + xyxy = np.array(xyxy) + masks = np.array(masks) + annotation = Detections(xyxy=xyxy, mask=masks, class_id=np.array(class_names)) + + images[image_path.name] = image + annotations[image_path.name] = annotation + classes += class_names + + classes = list(set(classes)) + + return classes, images, annotations + + +def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: + mask = np.zeros(resolution_wh, dtype=np.uint8) + cv2.fillPoly(mask, pts=[polygon], color=1) + return mask + + +def load_pascal_voc_annotations_v1( annotation_path: str, ) -> Tuple[str, Detections, List[str]]: """ From 3723eae50c385fc2cbbf4e3cd97b68d5056e28ef Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 10:21:17 +0200 Subject: [PATCH 02/24] update from_pascal_voc to match v2 loader --- supervision/dataset/core.py | 38 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index ce7e0edb..4bd80c1b 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -197,7 +197,10 @@ class DetectionDataset(BaseDataset): @classmethod def from_pascal_voc( - cls, images_directory_path: str, annotations_directory_path: str + cls, + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, ) -> DetectionDataset: """ Creates a Dataset instance from PASCAL VOC formatted data. @@ -231,34 +234,17 @@ class DetectionDataset(BaseDataset): ['dog', 'person'] ``` """ - image_paths = list_files_with_extensions( - directory=images_directory_path, extensions=["jpg", "jpeg", "png"] - ) - annotation_paths = list_files_with_extensions( - directory=annotations_directory_path, extensions=["xml"] + + classes, images, annotations = load_pascal_voc_annotations( + images_directory_path=images_directory_path, + annotations_directory_path=annotations_directory_path, + force_masks=force_masks, ) - raw_annotations: List[Tuple[str, Detections, List[str]]] = [ - load_pascal_voc_annotations(annotation_path=str(annotation_path)) - for annotation_path in annotation_paths - ] + for annotation in annotations.values(): + class_id = [classes.index(class_name) for class_name in annotation.class_id] + annotation.class_id = np.array(class_id) - classes = [] - for annotation in raw_annotations: - classes.extend(annotation[2]) - classes = list(set(classes)) - - for annotation in raw_annotations: - class_id = [classes.index(class_name) for class_name in annotation[2]] - annotation[1].class_id = np.array(class_id) - - images = { - image_path.name: cv2.imread(str(image_path)) for image_path in image_paths - } - - annotations = { - image_name: detections for image_name, detections, _ in raw_annotations - } return DetectionDataset(classes=classes, images=images, annotations=annotations) @classmethod From 86b33ed55801d33d1c14dd89d1a95f6784228d83 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 10:39:45 +0200 Subject: [PATCH 03/24] add test_pascal template --- test/dataset/formats/test_pascal.py | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 test/dataset/formats/test_pascal.py diff --git a/test/dataset/formats/test_pascal.py b/test/dataset/formats/test_pascal.py new file mode 100644 index 00000000..30bbc05e --- /dev/null +++ b/test/dataset/formats/test_pascal.py @@ -0,0 +1,32 @@ +from contextlib import ExitStack as DoesNotRaise +from typing import List, Optional, Tuple + +import numpy as np +import pytest + +from supervision.dataset.formats.pascal_voc import ( + detections_to_pascal_voc, + load_pascal_voc_annotations, + object_to_pascal_voc, +) +from supervision.detection.core import Detections + +# TODO + + +def test_detections_to_pascal_voc( + expected_result, exception: Exception +): + ... + + +def test_load_pascal_voc_annotations( + expected_result, exception: Exception +): + ... + + +def test_object_to_pascal_voc( + expected_result, exception: Exception +): + ... From a91118322b84ebf9c01b1b94a410490c18983e35 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 10:45:46 +0200 Subject: [PATCH 04/24] update docstrings --- supervision/dataset/core.py | 2 +- supervision/dataset/formats/pascal_voc.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 4bd80c1b..d40728e4 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -225,7 +225,7 @@ class DetectionDataset(BaseDataset): >>> project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) >>> dataset = project.version(PROJECT_VERSION).download("voc") - >>> ds = sv.DetectionDataset.from_yolo( + >>> ds = sv.DetectionDataset.from_pascal_voc( ... images_directory_path=f"{dataset.location}/train/images", ... annotations_directory_path=f"{dataset.location}/train/labels" ... ) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index bca886d4..90501be3 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -129,13 +129,15 @@ def load_pascal_voc_annotations( force_masks: bool = False, ) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: """ - Loads PASCAL VOC XML annotations and returns the image name, a Detections instance, and a list of class names. + Loads PASCAL VOC annotations and returns class names, images, and their corresponding detections. Args: - annotation_path (str): The path to the PASCAL VOC XML annotations file. + images_directory_path (str): The path to the directory containing the images. + annotations_directory_path (str): The path to the directory containing the PASCAL VOC annotation files. + force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: - Tuple[str, Detections, List[str]]: A tuple containing the image name, a Detections instance, and a list of class names of objects in the detections. + Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: A tuple containing a list of class names, a dictionary with image names as keys and images as values, and a dictionary with image names as keys and corresponding Detections instances as values. """ image_paths = list_files_with_extensions( From 6dde70eb0c7ffcfa97191b9276bbbc77c82471ce Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 10:46:31 +0200 Subject: [PATCH 05/24] move fixing of class_ids to load_pascal_voc_annotations --- supervision/dataset/core.py | 4 ---- supervision/dataset/formats/pascal_voc.py | 4 ++++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index d40728e4..15d92aa0 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -241,10 +241,6 @@ class DetectionDataset(BaseDataset): force_masks=force_masks, ) - for annotation in annotations.values(): - class_id = [classes.index(class_name) for class_name in annotation.class_id] - annotation.class_id = np.array(class_id) - return DetectionDataset(classes=classes, images=images, annotations=annotations) @classmethod diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 90501be3..8f3fb090 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -203,6 +203,10 @@ def load_pascal_voc_annotations( classes = list(set(classes)) + for annotation in annotations.values(): + class_id = [classes.index(class_name) for class_name in annotation.class_id] + annotation.class_id = np.array(class_id) + return classes, images, annotations From 277a9cb6b9d3d073b1232e167b3edfddebeee696 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Wed, 26 Jul 2023 12:36:49 +0200 Subject: [PATCH 06/24] import polygon_to_mask from supervision --- supervision/dataset/formats/pascal_voc.py | 8 +------- .../formats/{test_pascal.py => test_pascal_voc.py} | 0 2 files changed, 1 insertion(+), 7 deletions(-) rename test/dataset/formats/{test_pascal.py => test_pascal_voc.py} (100%) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 8f3fb090..8cc3cef2 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -9,7 +9,7 @@ import numpy as np from supervision.dataset.utils import approximate_mask_with_polygons from supervision.detection.core import Detections -from supervision.detection.utils import polygon_to_xyxy +from supervision.detection.utils import polygon_to_mask, polygon_to_xyxy from supervision.utils.file import list_files_with_extensions @@ -210,12 +210,6 @@ def load_pascal_voc_annotations( return classes, images, annotations -def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray: - mask = np.zeros(resolution_wh, dtype=np.uint8) - cv2.fillPoly(mask, pts=[polygon], color=1) - return mask - - def load_pascal_voc_annotations_v1( annotation_path: str, ) -> Tuple[str, Detections, List[str]]: diff --git a/test/dataset/formats/test_pascal.py b/test/dataset/formats/test_pascal_voc.py similarity index 100% rename from test/dataset/formats/test_pascal.py rename to test/dataset/formats/test_pascal_voc.py From b0e0d074af503ad8c7d35276ebf99b8ce5fe24d1 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Fri, 28 Jul 2023 22:21:47 +0200 Subject: [PATCH 07/24] fixes patch --- supervision/dataset/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 15d92aa0..6e47d747 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -31,7 +31,6 @@ from supervision.dataset.utils import ( train_test_split, ) from supervision.detection.core import Detections -from supervision.utils.file import list_files_with_extensions @dataclass @@ -208,6 +207,7 @@ class DetectionDataset(BaseDataset): Args: images_directory_path (str): The path to the directory containing the images. annotations_directory_path (str): The path to the directory containing the PASCAL VOC XML annotations. + force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: DetectionDataset: A DetectionDataset instance containing the loaded images and annotations. From 0a1212f23d532aecf01a99a44e8dec079a25d473 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Fri, 28 Jul 2023 22:22:03 +0200 Subject: [PATCH 08/24] fix with_masks defined but not used --- supervision/dataset/formats/pascal_voc.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 8cc3cef2..71a929a6 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -164,6 +164,7 @@ def load_pascal_voc_annotations( xyxy = [] class_names = [] masks = [] + with_masks = False for obj in root.findall("object"): class_name = obj.find("name").text class_names.append(class_name) @@ -194,8 +195,14 @@ def load_pascal_voc_annotations( masks.append(mask_from_polygon) xyxy = np.array(xyxy) - masks = np.array(masks) - annotation = Detections(xyxy=xyxy, mask=masks, class_id=np.array(class_names)) + + if with_masks: + masks = np.array(masks) + annotation = Detections( + xyxy=xyxy, mask=masks, class_id=np.array(class_names) + ) + else: + annotation = Detections(xyxy=xyxy, class_id=np.array(class_names)) images[image_path.name] = image annotations[image_path.name] = annotation From a181826527d7929604c7f3348f60be0e99a9fd9d Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Fri, 28 Jul 2023 23:13:11 +0200 Subject: [PATCH 09/24] add test_object_to_pascal_voc --- test/dataset/formats/test_pascal_voc.py | 73 ++++++++++++++++++++----- 1 file changed, 59 insertions(+), 14 deletions(-) diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index 30bbc05e..f5a953a2 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -1,4 +1,6 @@ +import xml.etree.ElementTree as ET from contextlib import ExitStack as DoesNotRaise +from test.utils import mock_detections from typing import List, Optional, Tuple import numpy as np @@ -11,22 +13,65 @@ from supervision.dataset.formats.pascal_voc import ( ) from supervision.detection.core import Detections -# TODO - - -def test_detections_to_pascal_voc( - expected_result, exception: Exception -): - ... - - -def test_load_pascal_voc_annotations( - expected_result, exception: Exception -): - ... + +def are_xml_elements_equal(elem1, elem2): + if ( + elem1.tag != elem2.tag + or elem1.attrib != elem2.attrib + or elem1.text != elem2.text + or len(elem1) != len(elem2) + ): + return False + + for child1, child2 in zip(elem1, elem2): + if not are_xml_elements_equal(child1, child2): + return False + + return True +@pytest.mark.parametrize( + "xyxy, name, polygon, expected_result, exception", + [ + ( + [0, 0, 10, 10], + "test", + None, + ET.fromstring( + """test001010""" + ), + DoesNotRaise(), + ), + ( + [0, 0, 10, 10], + "test", + [[0, 0], [10, 0], [10, 10], [0, 10]], + ET.fromstring( + """test001010001001010010""" + ), + DoesNotRaise(), + ), + ], +) def test_object_to_pascal_voc( - expected_result, exception: Exception + xyxy: np.ndarray, + name: str, + polygon: Optional[np.ndarray], + expected_result, + exception: Exception, ): + with exception: + result = object_to_pascal_voc(xyxy=xyxy, name=name, polygon=polygon) + with open("/tmp/test.xml", "w") as f: + f.write(ET.tostring(result).decode()) + with open("/tmp/exptest.xml", "w") as f: + f.write(ET.tostring(expected_result).decode()) + assert are_xml_elements_equal(result, expected_result) + + +def test_load_pascal_voc_annotations(expected_result, exception: Exception): + ... + + +def test_detections_to_pascal_voc(expected_result, exception: Exception): ... From 446ae23d99a7eeadd9497806f70e62bd9d037d9b Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 00:38:08 +0200 Subject: [PATCH 10/24] fix registering of empty detection --- supervision/dataset/formats/pascal_voc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 71a929a6..9dc15bbb 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -194,7 +194,7 @@ def load_pascal_voc_annotations( ) masks.append(mask_from_polygon) - xyxy = np.array(xyxy) + xyxy = np.array(xyxy) if len(xyxy) > 0 else np.empty((0, 4)) if with_masks: masks = np.array(masks) From 9a9d0c5259cda8961e0346ccbdb10ce7a54880e7 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 00:39:11 +0200 Subject: [PATCH 11/24] refactor class_id assignment to Detections in VOC --- supervision/dataset/formats/pascal_voc.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 9dc15bbb..ad78246b 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -195,24 +195,18 @@ def load_pascal_voc_annotations( masks.append(mask_from_polygon) xyxy = np.array(xyxy) if len(xyxy) > 0 else np.empty((0, 4)) + for k in set(class_names): + if k not in classes: + classes.append(k) + class_id = np.array([classes.index(class_name) for class_name in class_names]) if with_masks: - masks = np.array(masks) - annotation = Detections( - xyxy=xyxy, mask=masks, class_id=np.array(class_names) - ) + annotation = Detections(xyxy=xyxy, mask=np.array(masks), class_id=class_id) else: - annotation = Detections(xyxy=xyxy, class_id=np.array(class_names)) + annotation = Detections(xyxy=xyxy, class_id=class_id) images[image_path.name] = image annotations[image_path.name] = annotation - classes += class_names - - classes = list(set(classes)) - - for annotation in annotations.values(): - class_id = [classes.index(class_name) for class_name in annotation.class_id] - annotation.class_id = np.array(class_id) return classes, images, annotations From 1febd715e2df897b8b3cdcbc84d4029228f15596 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 22:53:24 +0200 Subject: [PATCH 12/24] remove test_detections_to_pascal_voc. conversion to XML is tested, and approx of masks should be in another test suite --- test/dataset/formats/test_pascal_voc.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index f5a953a2..0d316d95 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -71,7 +71,3 @@ def test_object_to_pascal_voc( def test_load_pascal_voc_annotations(expected_result, exception: Exception): ... - - -def test_detections_to_pascal_voc(expected_result, exception: Exception): - ... From 16424325417f160269c5854c7142262e89001a8b Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 23:08:50 +0200 Subject: [PATCH 13/24] add test_parse_polygon_points --- supervision/dataset/formats/pascal_voc.py | 17 +++++++++++------ test/dataset/formats/test_pascal_voc.py | 23 +++++++++++++++++++++-- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index ad78246b..1cc0bfbf 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -181,12 +181,7 @@ def load_pascal_voc_annotations( with_masks = force_masks if force_masks else with_masks for polygon in obj.findall("polygon"): - polygon_points = [] - coords = polygon.findall(".//*") - for i in range(0, len(coords), 2): - x = int(coords[i].text) - y = int(coords[i + 1].text) - polygon_points.append([x, y]) + polygon_points = parse_polygon_points(polygon) mask_from_polygon = polygon_to_mask( polygon=np.array(polygon_points), @@ -211,6 +206,16 @@ def load_pascal_voc_annotations( return classes, images, annotations +def parse_polygon_points(polygon: Element): + polygon_points = [] + coords = polygon.findall(".//*") + for i in range(0, len(coords), 2): + x = int(coords[i].text) + y = int(coords[i + 1].text) + polygon_points.append([x, y]) + return polygon_points + + def load_pascal_voc_annotations_v1( annotation_path: str, ) -> Tuple[str, Detections, List[str]]: diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index 0d316d95..5d1dae69 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -10,6 +10,7 @@ from supervision.dataset.formats.pascal_voc import ( detections_to_pascal_voc, load_pascal_voc_annotations, object_to_pascal_voc, + parse_polygon_points, ) from supervision.detection.core import Detections @@ -69,5 +70,23 @@ def test_object_to_pascal_voc( assert are_xml_elements_equal(result, expected_result) -def test_load_pascal_voc_annotations(expected_result, exception: Exception): - ... +@pytest.mark.parametrize( + "polygon_element, expected_result, exception", + [ + ( + ET.fromstring( + """001001010010""" + ), + [[0, 0], [10, 0], [10, 10], [0, 10]], + DoesNotRaise(), + ) + ], +) +def test_parse_polygon_points( + polygon_element, + expected_result: List[list], + exception, +): + with exception: + result = parse_polygon_points(polygon_element) + assert result == expected_result From e4ef57ec2d6a5c455ff7cc50869f0254c5ca56e8 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 23:27:33 +0200 Subject: [PATCH 14/24] add test_detections_from_xml_obj --- supervision/dataset/formats/pascal_voc.py | 87 +++++++++++++---------- test/dataset/formats/test_pascal_voc.py | 23 ++++++ 2 files changed, 72 insertions(+), 38 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 1cc0bfbf..c325e80a 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -161,44 +161,10 @@ def load_pascal_voc_annotations( tree = parse(annotation_path) root = tree.getroot() - xyxy = [] - class_names = [] - masks = [] - with_masks = False - for obj in root.findall("object"): - class_name = obj.find("name").text - class_names.append(class_name) - - bbox = obj.find("bndbox") - x1 = int(bbox.find("xmin").text) - y1 = int(bbox.find("ymin").text) - x2 = int(bbox.find("xmax").text) - y2 = int(bbox.find("ymax").text) - - xyxy.append([x1, y1, x2, y2]) - - with_masks = obj.find("polygon") is not None - with_masks = force_masks if force_masks else with_masks - - for polygon in obj.findall("polygon"): - polygon_points = parse_polygon_points(polygon) - - mask_from_polygon = polygon_to_mask( - polygon=np.array(polygon_points), - resolution_wh=(image.shape[0], image.shape[1]), - ) - masks.append(mask_from_polygon) - - xyxy = np.array(xyxy) if len(xyxy) > 0 else np.empty((0, 4)) - for k in set(class_names): - if k not in classes: - classes.append(k) - class_id = np.array([classes.index(class_name) for class_name in class_names]) - - if with_masks: - annotation = Detections(xyxy=xyxy, mask=np.array(masks), class_id=class_id) - else: - annotation = Detections(xyxy=xyxy, class_id=class_id) + resolution_wh = (image.shape[0], image.shape[1]) + annotation, classes = detections_from_xml_obj( + root, classes, resolution_wh, force_masks + ) images[image_path.name] = image annotations[image_path.name] = annotation @@ -206,6 +172,51 @@ def load_pascal_voc_annotations( return classes, images, annotations +def detections_from_xml_obj(root, classes, resolution_wh, force_masks=False): + xyxy = [] + class_names = [] + masks = [] + with_masks = False + extended_classes = classes[:] + for obj in root.findall("object"): + class_name = obj.find("name").text + class_names.append(class_name) + + bbox = obj.find("bndbox") + x1 = int(bbox.find("xmin").text) + y1 = int(bbox.find("ymin").text) + x2 = int(bbox.find("xmax").text) + y2 = int(bbox.find("ymax").text) + + xyxy.append([x1, y1, x2, y2]) + + with_masks = obj.find("polygon") is not None + with_masks = force_masks if force_masks else with_masks + + for polygon in obj.findall("polygon"): + polygon_points = parse_polygon_points(polygon) + + mask_from_polygon = polygon_to_mask( + polygon=np.array(polygon_points), + resolution_wh=resolution_wh, + ) + masks.append(mask_from_polygon) + + xyxy = np.array(xyxy) if len(xyxy) > 0 else np.empty((0, 4)) + for k in set(class_names): + if k not in extended_classes: + extended_classes.append(k) + class_id = np.array( + [extended_classes.index(class_name) for class_name in class_names] + ) + + if with_masks: + annotation = Detections(xyxy=xyxy, mask=np.array(masks), class_id=class_id) + else: + annotation = Detections(xyxy=xyxy, class_id=class_id) + return annotation, extended_classes + + def parse_polygon_points(polygon: Element): polygon_points = [] coords = polygon.findall(".//*") diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index 5d1dae69..fa900f1c 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -7,6 +7,7 @@ import numpy as np import pytest from supervision.dataset.formats.pascal_voc import ( + detections_from_xml_obj, detections_to_pascal_voc, load_pascal_voc_annotations, object_to_pascal_voc, @@ -90,3 +91,25 @@ def test_parse_polygon_points( with exception: result = parse_polygon_points(polygon_element) assert result == expected_result + + +@pytest.mark.parametrize( + "xml_string, classes, resolution_wh, force_masks, expected_result, exception", + [ + ( + """test.jpg100100test001010""", + ["test"], + (100, 100), + False, + mock_detections(np.array([[0, 0, 10, 10]]), None, [0]), + DoesNotRaise(), + ) + ], +) +def test_detections_from_xml_obj( + xml_string, classes, resolution_wh, force_masks, expected_result, exception +): + with exception: + root = ET.fromstring(xml_string) + result, _ = detections_from_xml_obj(root, classes, resolution_wh, force_masks) + assert result == expected_result From f8005b268b86c661350feb818a87ea6768fb7cfd Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 23:39:42 +0200 Subject: [PATCH 15/24] add docstrings --- supervision/dataset/formats/pascal_voc.py | 34 +++++++++++++++++++++-- test/dataset/formats/test_pascal_voc.py | 2 +- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index c325e80a..53834d34 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -172,7 +172,36 @@ def load_pascal_voc_annotations( return classes, images, annotations -def detections_from_xml_obj(root, classes, resolution_wh, force_masks=False): +def detections_from_xml_obj( + root: Element, classes: List[str], resolution_wh, force_masks: bool = False +) -> Tuple[Detections, List[str]]: + """ + Converts an XML object in Pascal VOC format to a Detections object. + Expected XML format: + + ... + + dog + + 48 + 240 + 195 + 371 + + + 48 + 240 + 195 + 240 + 195 + 371 + 48 + 371 + + + + + """ xyxy = [] class_names = [] masks = [] @@ -217,7 +246,8 @@ def detections_from_xml_obj(root, classes, resolution_wh, force_masks=False): return annotation, extended_classes -def parse_polygon_points(polygon: Element): +def parse_polygon_points(polygon: Element) -> List[List[int]]: + # Parses polygon points in format: ............... polygon_points = [] coords = polygon.findall(".//*") for i in range(0, len(coords), 2): diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index fa900f1c..d1f25bd7 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -97,7 +97,7 @@ def test_parse_polygon_points( "xml_string, classes, resolution_wh, force_masks, expected_result, exception", [ ( - """test.jpg100100test001010""", + """test001010""", ["test"], (100, 100), False, From e8f616ba2fe4fef84aa5fdd2a487210e6be97e0e Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 23:41:02 +0200 Subject: [PATCH 16/24] cleanup imports --- test/dataset/formats/test_pascal_voc.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index d1f25bd7..b12f2964 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -1,19 +1,16 @@ import xml.etree.ElementTree as ET from contextlib import ExitStack as DoesNotRaise from test.utils import mock_detections -from typing import List, Optional, Tuple +from typing import List, Optional import numpy as np import pytest from supervision.dataset.formats.pascal_voc import ( detections_from_xml_obj, - detections_to_pascal_voc, - load_pascal_voc_annotations, object_to_pascal_voc, parse_polygon_points, ) -from supervision.detection.core import Detections def are_xml_elements_equal(elem1, elem2): From 12b3def032142b0a466e3847a19f60ac5ec4224a Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Sat, 29 Jul 2023 23:42:59 +0200 Subject: [PATCH 17/24] upd docstring --- supervision/dataset/formats/pascal_voc.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 53834d34..e915159c 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -201,6 +201,8 @@ def detections_from_xml_obj( + Returns: + Tuple[Detections, List[str]]: A tuple containing a Detections object and an updated list of class names, extended with the class names from the XML object. """ xyxy = [] class_names = [] From 95c8576aaf74a52f15afd769a5d08031d39b06bb Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 13:09:35 +0200 Subject: [PATCH 18/24] fix mask shape (N, W, H) -> (N, H, W) --- supervision/dataset/formats/pascal_voc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index e915159c..93e90927 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -161,7 +161,7 @@ def load_pascal_voc_annotations( tree = parse(annotation_path) root = tree.getroot() - resolution_wh = (image.shape[0], image.shape[1]) + resolution_wh = (image.shape[1], image.shape[0]) annotation, classes = detections_from_xml_obj( root, classes, resolution_wh, force_masks ) From 77c2afe55917526b201263de6012759a9382e43f Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 13:13:32 +0200 Subject: [PATCH 19/24] fix mask dtype --- supervision/detection/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 63206ddc..cdca3ff7 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -17,8 +17,9 @@ def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.n np.ndarray: The generated 2D mask, where the polygon is marked with `1`'s and the rest is filled with `0`'s. """ width, height = resolution_wh - mask = np.zeros((height, width), dtype=np.uint8) + mask = np.zeros((height, width)) cv2.fillPoly(mask, [polygon], color=1) + mask = mask.astype(bool) return mask From 9462a3058d3bf57cc428afc28f454ce645cf0d9e Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 13:15:40 +0200 Subject: [PATCH 20/24] cast masks to bool only when creating a Detection obj --- supervision/dataset/formats/pascal_voc.py | 3 +-- supervision/detection/utils.py | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 93e90927..18f130c7 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -242,14 +242,13 @@ def detections_from_xml_obj( ) if with_masks: - annotation = Detections(xyxy=xyxy, mask=np.array(masks), class_id=class_id) + annotation = Detections(xyxy=xyxy, mask=np.array(masks).astype(bool), class_id=class_id) else: annotation = Detections(xyxy=xyxy, class_id=class_id) return annotation, extended_classes def parse_polygon_points(polygon: Element) -> List[List[int]]: - # Parses polygon points in format: ............... polygon_points = [] coords = polygon.findall(".//*") for i in range(0, len(coords), 2): diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index cdca3ff7..e30e6a05 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -19,7 +19,6 @@ def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.n width, height = resolution_wh mask = np.zeros((height, width)) cv2.fillPoly(mask, [polygon], color=1) - mask = mask.astype(bool) return mask From c0c292ef8270196eac2752893c38047fc8de78f7 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 15:19:39 +0200 Subject: [PATCH 21/24] lint --- supervision/dataset/formats/pascal_voc.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 18f130c7..17223d31 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -242,7 +242,9 @@ def detections_from_xml_obj( ) if with_masks: - annotation = Detections(xyxy=xyxy, mask=np.array(masks).astype(bool), class_id=class_id) + annotation = Detections( + xyxy=xyxy, mask=np.array(masks).astype(bool), class_id=class_id + ) else: annotation = Detections(xyxy=xyxy, class_id=class_id) return annotation, extended_classes From e2d1fe7695a98a1e7fb69da96cd9326b41a20fba Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 19:42:53 +0200 Subject: [PATCH 22/24] remove artifacts --- test/dataset/formats/test_pascal_voc.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index b12f2964..8ae38801 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -61,10 +61,6 @@ def test_object_to_pascal_voc( ): with exception: result = object_to_pascal_voc(xyxy=xyxy, name=name, polygon=polygon) - with open("/tmp/test.xml", "w") as f: - f.write(ET.tostring(result).decode()) - with open("/tmp/exptest.xml", "w") as f: - f.write(ET.tostring(expected_result).decode()) assert are_xml_elements_equal(result, expected_result) From 26289e37439186ad18c39aedcff525d7cdb15340 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 19:43:32 +0200 Subject: [PATCH 23/24] drop load_pascal_voc_annotations_v1 --- supervision/dataset/formats/pascal_voc.py | 37 ----------------------- 1 file changed, 37 deletions(-) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 17223d31..4efb2917 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -258,40 +258,3 @@ def parse_polygon_points(polygon: Element) -> List[List[int]]: y = int(coords[i + 1].text) polygon_points.append([x, y]) return polygon_points - - -def load_pascal_voc_annotations_v1( - annotation_path: str, -) -> Tuple[str, Detections, List[str]]: - """ - Loads PASCAL VOC XML annotations and returns the image name, a Detections instance, and a list of class names. - - Args: - annotation_path (str): The path to the PASCAL VOC XML annotations file. - - Returns: - Tuple[str, Detections, List[str]]: A tuple containing the image name, a Detections instance, and a list of class names of objects in the detections. - """ - tree = parse(annotation_path) - root = tree.getroot() - - image_name = root.find("filename").text - - xyxy = [] - class_names = [] - for obj in root.findall("object"): - class_name = obj.find("name").text - class_names.append(class_name) - - bbox = obj.find("bndbox") - x1 = int(bbox.find("xmin").text) - y1 = int(bbox.find("ymin").text) - x2 = int(bbox.find("xmax").text) - y2 = int(bbox.find("ymax").text) - - xyxy.append([x1, y1, x2, y2]) - - xyxy = np.array(xyxy) - detections = Detections(xyxy=xyxy) - - return image_name, detections, class_names From 6fdabf0a964e5eda445256070c025a7797de5269 Mon Sep 17 00:00:00 2001 From: kirilllzaitsev Date: Mon, 31 Jul 2023 20:10:20 +0200 Subject: [PATCH 24/24] extend tests for test_detections_from_xml_obj --- test/dataset/formats/test_pascal_voc.py | 43 +++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py index 8ae38801..fa3f1124 100644 --- a/test/dataset/formats/test_pascal_voc.py +++ b/test/dataset/formats/test_pascal_voc.py @@ -86,17 +86,56 @@ def test_parse_polygon_points( assert result == expected_result +ONE_CLASS_N_BBOX = """test001010test10102020""" + + +ONE_CLASS_ONE_BBOX = """test001010""" + + +N_CLASS_N_BBOX = """test001010test20303040test210102020""" + +NO_DETECTIONS = """""" + + @pytest.mark.parametrize( "xml_string, classes, resolution_wh, force_masks, expected_result, exception", [ ( - """test001010""", + ONE_CLASS_ONE_BBOX, ["test"], (100, 100), False, mock_detections(np.array([[0, 0, 10, 10]]), None, [0]), DoesNotRaise(), - ) + ), + ( + ONE_CLASS_N_BBOX, + ["test"], + (100, 100), + False, + mock_detections(np.array([[0, 0, 10, 10], [10, 10, 20, 20]]), None, [0, 0]), + DoesNotRaise(), + ), + ( + N_CLASS_N_BBOX, + ["test", "test2"], + (100, 100), + False, + mock_detections( + np.array([[0, 0, 10, 10], [20, 30, 30, 40], [10, 10, 20, 20]]), + None, + [0, 0, 1], + ), + DoesNotRaise(), + ), + ( + NO_DETECTIONS, + [], + (100, 100), + False, + mock_detections(np.empty((0, 4)), None, []), + DoesNotRaise(), + ), ], ) def test_detections_from_xml_obj(