From 3b2902c87cb4cb75bcae1036c4a81c95c2f8a296 Mon Sep 17 00:00:00 2001 From: hd Date: Sat, 24 Jun 2023 15:48:57 +0200 Subject: [PATCH 01/13] COCO dataset import export interface, working for object detection --- supervision/dataset/core.py | 97 ++++++++++++++++ supervision/dataset/formats/coco.py | 174 ++++++++++++++++++++++++++++ supervision/utils/file.py | 29 +++++ 3 files changed, 300 insertions(+) create mode 100644 supervision/dataset/formats/coco.py diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 96c0be2b..23d3142c 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -19,6 +19,12 @@ from supervision.dataset.formats.yolo import ( save_data_yaml, save_yolo_annotations, ) + +from supervision.dataset.formats.coco import ( + load_coco_annotations, + save_coco_annotations +) + from supervision.dataset.ultils import save_dataset_images, train_test_split from supervision.detection.core import Detections from supervision.utils.file import list_files_with_extensions @@ -333,6 +339,97 @@ class DetectionDataset(BaseDataset): if data_yaml_path is not None: save_data_yaml(data_yaml_path=data_yaml_path, classes=self.classes) + @classmethod + def from_coco( + cls, + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, + ) -> DetectionDataset: + """ + Creates a Dataset instance from YOLO formatted data. + + Args: + images_directory_path (str): The path to the directory containing the images. + annotations_directory_path (str): The path to the directory containing the YOLO annotation files. + data_yaml_path (str): The path to the data YAML file containing class information. + 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. + + Example: + ```python + >>> import roboflow + >>> from roboflow import Roboflow + >>> import supervision as sv + + >>> roboflow.login() + + >>> rf = Roboflow() + + >>> project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + >>> dataset = project.version(PROJECT_VERSION).download("yolov5") + + >>> ds = sv.DetectionDataset.from_coco( + ... images_directory_path=f"{dataset.location}/train/images", + ... annotations_directory_path=f"{dataset.location}/train/labels", + ... data_yaml_path=f"{dataset.location}/data.yaml" + ... ) + + >>> ds.classes + ['dog', 'person'] + ``` + """ + classes, images, annotations = load_coco_annotations( + images_directory_path=images_directory_path, + annotations_path=annotations_path, + force_masks=force_masks, + ) + return DetectionDataset(classes=classes, images=images, annotations=annotations) + + def as_coco( + self, + images_directory_path: Optional[str] = None, + annotations_path: Optional[str] = None, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + ) -> None: + """ + Exports the dataset to COCO format. This method saves the images and their corresponding + annotations in COCO format, which is a simple json file that describes an object in the image. + Annotation json file also include category maps. + + The method allows filtering the detections based on their area percentage and offers an option for polygon approximation. + + Args: + images_directory_path (Optional[str]): The path to the directory where the images should be saved. + If not provided, images will not be saved. + annotations_directory_path (Optional[str]): The path to the directory where the annotations in + YOLO format should be saved. If not provided, annotations will not be saved. + min_image_area_percentage (float): The minimum percentage of detection area relative to + the image area for a detection to be included. + max_image_area_percentage (float): The maximum percentage of detection area relative to + the image area for a detection to be included. + approximation_percentage (float): The percentage of polygon points to be removed from the input polygon, + in the range [0, 1). This is useful for simplifying the annotations. + """ + if images_directory_path is not None: + save_dataset_images( + images_directory_path=images_directory_path, images=self.images + ) + if annotations_path is not None: + save_coco_annotations( + annotation_path=annotations_path, + images=self.images, + annotations=self.annotations, + classes=self.classes, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + @dataclass class ClassificationDataset(BaseDataset): diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py new file mode 100644 index 00000000..240320af --- /dev/null +++ b/supervision/dataset/formats/coco.py @@ -0,0 +1,174 @@ +import os +from datetime import datetime +from typing import Dict, List, Tuple + +import cv2 +import numpy as np + +from supervision.detection.core import Detections +from supervision.utils.file import ( + save_json_file, + read_json_file +) + +""" +COCO Format Information: +coco: dict[info, licenses, categories, images, annotations] +info: dict [] +licenses: dict['id', 'url', 'name'] +categories: dict['id', 'name', 'supercategory'] +images: dict['id', 'license', 'file_name', 'height', 'width', 'date_captured'] +annotations: dict['id', 'image_id', 'category_id', 'bbox', 'area', 'segmentation', 'iscrowd'] +bbox are in [x1, y1, w, h] in original scale +""" + + +def _extract_class_names(annotation_data: dict) -> List[str]: + names = [] + categories = annotation_data.get("categories", None) + if categories: + for cat in categories: + names.append(cat["name"]) + return names + + +def _extract_image_info(annotation_data: dict) -> List[dict]: + image_infos = annotation_data.get("images", None) + return image_infos + + +def _extract_image_names(image_infos: dict) -> List[dict]: + image_names = [] + for image_info in image_infos: + image_names.append(image_info["file_name"]) + return image_names + + +def _annotations_dict_to_numpy(annotation_data: dict) -> np.ndarray: + annotations_infos = annotation_data.get("annotations", None) + # TODO: Add segmentation parser + # image id, label-id, category_id, bbox[0], bbox[1], bbox[2], bbox[3], segmentaions + annotations = np.zeros((0, 7)) + for anno in annotations_infos: + _info = np.array([[anno["image_id"], anno["id"], anno["category_id"], + anno["bbox"][0], anno["bbox"][1], anno["bbox"][2], anno["bbox"][3]]]) + annotations = np.append(annotations, _info, axis=0) + return annotations + + +def coco_annotations_to_detections(coco_annotations: np.ndarray, with_masks: bool) -> Detections: + """ + Returns: + object: detections + """ + detections = Detections.empty() + if coco_annotations.shape[0] > 0: + coco_annotations[:, 5] += coco_annotations[:, 3] + coco_annotations[:, 6] += coco_annotations[:, 4] + detections = Detections(xyxy=coco_annotations[:, 3:], class_id=coco_annotations[:, 2].astype(int)) + return detections + + + + + +def load_coco_annotations( + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, +) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: + """ + Loads YOLO annotations and returns class names, images, and their corresponding detections. + + Args: + images_directory_path (str): The path to the directory containing the images. + annotations__path (str): The path to the coco json annotation file. + force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. + + Returns: + 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. + """ + annotation_data = read_json_file(file_path=annotations_path) + + classes = _extract_class_names(annotation_data=annotation_data) + images_infos = _extract_image_info(annotation_data=annotation_data) + annotations_np = _annotations_dict_to_numpy(annotation_data=annotation_data) + + images = {} + annotations = {} + + for images_info in images_infos: + image_path = os.path.join(images_directory_path, images_info["file_name"]) + image = cv2.imread(str(image_path)) + + # Filter annotations based on image id + image_annotations = annotations_np[annotations_np[:, 0] == images_info["id"]] + + annotation = coco_annotations_to_detections(coco_annotations=image_annotations, with_masks=False) + images[images_info["file_name"]] = image + annotations[images_info["file_name"]] = annotation + return classes, images, annotations + + +def save_coco_annotations( + annotation_path: str, + images: Dict[str, np.ndarray], + annotations: Dict[str, Detections], + classes: List[str], + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, +) -> None: + # Path(annotation_path).mkdir(parents=True, exist_ok=True) + + license = {'id': 1, 'url': 'https://creativecommons.org/licenses/by/4.0/', 'name': 'CC BY 4.0'} + licenses = [license] # TODO: accept as optional parameter + + annotations_data = [] + image_infos = [] + infos = {} # TODO: accept as optional parameter + + categories = [] + for class_id, class_name in enumerate(classes): + cate_dict = {'id': class_id, 'name': class_name, "supercategory": "common-objects"} + categories.append(cate_dict) + + image_id = 0 + label_id = 0 + for image_name, image in images.items(): + image_height, image_width, _ = image.shape + + # TODO: Modify datetime format + image_info = {'id': image_id, 'license': 1, 'file_name': image_name, + 'height': image_height, 'width': image_width, + 'date_captured': datetime.now().strftime("%m/%d/%Y, %H:%M:%S") + } + + image_infos.append(image_info) + detections = annotations[image_name] + for xyxy, mask, confidence, class_id, tracker_id in detections: + # for class_id, x1, y1, x2, y2 in detections.class_id, detections.xyxy: + per_label_dict = {} + per_label_dict['id'] = label_id + per_label_dict['image_id'] = image_id + per_label_dict['category_id'] = int(class_id) + w, h = xyxy[2]-xyxy[0], xyxy[3]-xyxy[1] + per_label_dict['bbox'] = [xyxy[0], xyxy[1], w, h] + per_label_dict['area'] = w * h # width x height + per_label_dict['segmentation'] = [] + per_label_dict['iscrowd'] = 0 + print(per_label_dict) + annotations_data.append(per_label_dict) + label_id += 1 + + image_id += 1 + + + annotation_dict = { + 'info': infos, + 'licenses': licenses, + 'categories': categories, + 'images': image_infos, + 'annotations': annotations_data + } + save_json_file(annotation_dict, file_path=annotation_path) diff --git a/supervision/utils/file.py b/supervision/utils/file.py index c24af4f8..e0dc53bc 100644 --- a/supervision/utils/file.py +++ b/supervision/utils/file.py @@ -1,3 +1,4 @@ +import json from pathlib import Path from typing import List, Optional, Union @@ -66,3 +67,31 @@ def save_text_file(lines: List[str], file_path: str): with open(file_path, "w") as file: for line in lines: file.write(line + "\n") + + +def read_json_file(file_path: str) -> dict: + """ + Read a json file and return a dict. + + Args: + file_path (str): The path to the json file. + + Returns: + dict: A dict of annotations information + """ + with open(file_path, "r") as file: + data = json.load(file) + return data + + +def save_json_file(data: dict, file_path: str, indent=3): + """ + Write a dict to a json file. + + Args: + data (dict): dict with unique keys and value as pair. + file_path (str): The path to the json file. + """ + with open(file_path, 'w') as fp: + json.dump(data, fp, indent=indent) + From 253113fa88bc5a3798e538d0ddb2511ee7bc5bcb Mon Sep 17 00:00:00 2001 From: hd Date: Sat, 24 Jun 2023 18:33:18 +0200 Subject: [PATCH 02/13] refactored code --- supervision/dataset/core.py | 2 + supervision/dataset/formats/coco.py | 105 ++++++++++++++++++++-------- 2 files changed, 77 insertions(+), 30 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 23d3142c..ca52a38a 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -416,10 +416,12 @@ class DetectionDataset(BaseDataset): in the range [0, 1). This is useful for simplifying the annotations. """ if images_directory_path is not None: + Path(images_directory_path).mkdir(parents=True, exist_ok=True) save_dataset_images( images_directory_path=images_directory_path, images=self.images ) if annotations_path is not None: + # Path(annotations_path).mkdir(parents=True, exist_ok=True) save_coco_annotations( annotation_path=annotations_path, images=self.images, diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 240320af..7884f04d 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -1,11 +1,14 @@ import os from datetime import datetime +from pathlib import Path from typing import Dict, List, Tuple import cv2 import numpy as np +from supervision.dataset.ultils import approximate_mask_with_polygons from supervision.detection.core import Detections +from supervision.detection.utils import polygon_to_mask from supervision.utils.file import ( save_json_file, read_json_file @@ -44,32 +47,61 @@ def _extract_image_names(image_infos: dict) -> List[dict]: return image_names -def _annotations_dict_to_numpy(annotation_data: dict) -> np.ndarray: +def _annotations_dict(annotation_data: dict, with_masks: bool) -> Tuple[np.ndarray, dict]: annotations_infos = annotation_data.get("annotations", None) - # TODO: Add segmentation parser # image id, label-id, category_id, bbox[0], bbox[1], bbox[2], bbox[3], segmentaions - annotations = np.zeros((0, 7)) + image_id_label_id_pair = np.zeros((0, 2)) + annotations = {} for anno in annotations_infos: - _info = np.array([[anno["image_id"], anno["id"], anno["category_id"], - anno["bbox"][0], anno["bbox"][1], anno["bbox"][2], anno["bbox"][3]]]) - annotations = np.append(annotations, _info, axis=0) - return annotations + _annotations = {} + for key, item in anno.items(): + _annotations[key] = anno[key] + id_pair = np.array([[anno["image_id"], anno["id"]]]) + image_id_label_id_pair = np.append(image_id_label_id_pair, id_pair, axis=0) + annotations[anno['id']] = _annotations + + return image_id_label_id_pair, annotations -def coco_annotations_to_detections(coco_annotations: np.ndarray, with_masks: bool) -> Detections: +def _polygons_to_masks( + polygons: List[np.ndarray], resolution_wh: Tuple[int, int] +) -> np.ndarray: + return np.array( + [ + polygon_to_mask(polygon=polygon, resolution_wh=resolution_wh) + for polygon in polygons + ], + dtype=bool, + ) + + +def coco_annotations_to_detections(image_annotations: List[dict], with_masks: bool) -> Detections: """ Returns: object: detections """ - detections = Detections.empty() - if coco_annotations.shape[0] > 0: - coco_annotations[:, 5] += coco_annotations[:, 3] - coco_annotations[:, 6] += coco_annotations[:, 4] - detections = Detections(xyxy=coco_annotations[:, 3:], class_id=coco_annotations[:, 2].astype(int)) - return detections + masks = [] if with_masks else None + class_ids = [] + xyxy = [] + polygons = [] + for image_annotation in image_annotations: + bbox = image_annotation['bbox'] + xyxy.append(bbox) + class_ids.append(image_annotation['category_id']) + _polygons = image_annotation['segmentation'] + if len(_polygons) > 0 and with_masks: + _polygon = np.asarray(_polygons[0]).reshape((-1, 2)).astype(int) + polygons.append(_polygon) + xyxy = np.array(xyxy) + xyxy[:, 2] += xyxy[:, 0] + xyxy[:, 3] += xyxy[:, 1] + class_ids = np.asarray(class_ids, dtype=int) + if len(polygons) > 0: + masks = _polygons_to_masks(polygons=polygons, resolution_wh=(640, 640)) + return Detections(xyxy=xyxy, class_id=class_ids, mask=masks) def load_coco_annotations( @@ -82,7 +114,7 @@ def load_coco_annotations( Args: images_directory_path (str): The path to the directory containing the images. - annotations__path (str): The path to the coco json annotation file. + annotations_path (str): The path to the coco json annotation file. force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: @@ -92,7 +124,7 @@ def load_coco_annotations( classes = _extract_class_names(annotation_data=annotation_data) images_infos = _extract_image_info(annotation_data=annotation_data) - annotations_np = _annotations_dict_to_numpy(annotation_data=annotation_data) + image_id_label_id_pair, annotation_dict = _annotations_dict(annotation_data=annotation_data, with_masks=force_masks) images = {} annotations = {} @@ -102,9 +134,14 @@ def load_coco_annotations( image = cv2.imread(str(image_path)) # Filter annotations based on image id - image_annotations = annotations_np[annotations_np[:, 0] == images_info["id"]] + per_image_label_ids = image_id_label_id_pair[image_id_label_id_pair[:, 0] == images_info["id"]][:, 1] + + image_annotations = [] + for per_image_label_id in per_image_label_ids: + image_annotations.append(annotation_dict[int(per_image_label_id)]) + + annotation = coco_annotations_to_detections(image_annotations=image_annotations, with_masks=force_masks) - annotation = coco_annotations_to_detections(coco_annotations=image_annotations, with_masks=False) images[images_info["file_name"]] = image annotations[images_info["file_name"]] = annotation return classes, images, annotations @@ -118,17 +155,19 @@ def save_coco_annotations( min_image_area_percentage: float = 0.0, max_image_area_percentage: float = 1.0, approximation_percentage: float = 0.75, + licenses: List[dict] = None, + info: dict = None ) -> None: - # Path(annotation_path).mkdir(parents=True, exist_ok=True) - - license = {'id': 1, 'url': 'https://creativecommons.org/licenses/by/4.0/', 'name': 'CC BY 4.0'} - licenses = [license] # TODO: accept as optional parameter + Path(annotation_path).parents[2].mkdir(parents=True, exist_ok=True) + if not info: + info = {} + if not licenses: + licenses = [{'id': 1, 'url': 'https://creativecommons.org/licenses/by/4.0/', 'name': 'CC BY 4.0'}] annotations_data = [] image_infos = [] - infos = {} # TODO: accept as optional parameter - categories = [] + for class_id, class_name in enumerate(classes): cate_dict = {'id': class_id, 'name': class_name, "supercategory": "common-objects"} categories.append(cate_dict) @@ -147,25 +186,31 @@ def save_coco_annotations( image_infos.append(image_info) detections = annotations[image_name] for xyxy, mask, confidence, class_id, tracker_id in detections: - # for class_id, x1, y1, x2, y2 in detections.class_id, detections.xyxy: + polygons = [] + if mask is not None: + polygons = 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, + ) + per_label_dict = {} per_label_dict['id'] = label_id per_label_dict['image_id'] = image_id per_label_dict['category_id'] = int(class_id) - w, h = xyxy[2]-xyxy[0], xyxy[3]-xyxy[1] + w, h = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] per_label_dict['bbox'] = [xyxy[0], xyxy[1], w, h] per_label_dict['area'] = w * h # width x height - per_label_dict['segmentation'] = [] + per_label_dict['segmentation'] = polygons per_label_dict['iscrowd'] = 0 - print(per_label_dict) annotations_data.append(per_label_dict) label_id += 1 image_id += 1 - annotation_dict = { - 'info': infos, + 'info': info, 'licenses': licenses, 'categories': categories, 'images': image_infos, From 769b6b967c783257c8ce652ba60ed30a822ff277 Mon Sep 17 00:00:00 2001 From: hd Date: Sun, 25 Jun 2023 13:31:55 +0200 Subject: [PATCH 03/13] Tested and working version --- supervision/dataset/core.py | 1 - supervision/dataset/formats/coco.py | 24 +++++++++--------------- supervision/utils/file.py | 16 +++++++++++++++- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index ca52a38a..50cb1dd1 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -421,7 +421,6 @@ class DetectionDataset(BaseDataset): images_directory_path=images_directory_path, images=self.images ) if annotations_path is not None: - # Path(annotations_path).mkdir(parents=True, exist_ok=True) save_coco_annotations( annotation_path=annotations_path, images=self.images, diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 7884f04d..449b2626 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -80,28 +80,22 @@ def coco_annotations_to_detections(image_annotations: List[dict], with_masks: bo Returns: object: detections """ + detection = Detections.empty() masks = [] if with_masks else None class_ids = [] xyxy = [] - polygons = [] for image_annotation in image_annotations: bbox = image_annotation['bbox'] xyxy.append(bbox) class_ids.append(image_annotation['category_id']) - _polygons = image_annotation['segmentation'] - if len(_polygons) > 0 and with_masks: - _polygon = np.asarray(_polygons[0]).reshape((-1, 2)).astype(int) - polygons.append(_polygon) - - xyxy = np.array(xyxy) - xyxy[:, 2] += xyxy[:, 0] - xyxy[:, 3] += xyxy[:, 1] - class_ids = np.asarray(class_ids, dtype=int) - - if len(polygons) > 0: - masks = _polygons_to_masks(polygons=polygons, resolution_wh=(640, 640)) - - return Detections(xyxy=xyxy, class_id=class_ids, mask=masks) + # _polygons = image_annotation['segmentation'] + xyxy = np.asarray(xyxy) + if xyxy.shape[0] > 0: + xyxy[:, 2] += xyxy[:, 0] + xyxy[:, 3] += xyxy[:, 1] + class_ids = np.asarray(class_ids, dtype=int) + detection = Detections(xyxy=xyxy, class_id=class_ids) + return detection def load_coco_annotations( diff --git a/supervision/utils/file.py b/supervision/utils/file.py index e0dc53bc..4c2b92d4 100644 --- a/supervision/utils/file.py +++ b/supervision/utils/file.py @@ -2,6 +2,20 @@ import json from pathlib import Path from typing import List, Optional, Union +import numpy as np + + +class NpEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, np.integer): + return int(obj) + if isinstance(obj, np.floating): + return float(obj) + if isinstance(obj, np.ndarray): + return obj.tolist() + return super(NpEncoder, self).default(obj) + + def list_files_with_extensions( directory: Union[str, Path], extensions: Optional[List[str]] = None @@ -93,5 +107,5 @@ def save_json_file(data: dict, file_path: str, indent=3): file_path (str): The path to the json file. """ with open(file_path, 'w') as fp: - json.dump(data, fp, indent=indent) + json.dump(data, fp, cls=NpEncoder, indent=indent) From ab9728cca23e723109f8e35ff12b60915027c6da Mon Sep 17 00:00:00 2001 From: hd Date: Sun, 25 Jun 2023 13:40:41 +0200 Subject: [PATCH 04/13] Updated doc-strings --- supervision/dataset/core.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 50cb1dd1..6a1cd83b 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -369,12 +369,11 @@ class DetectionDataset(BaseDataset): >>> rf = Roboflow() >>> project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) - >>> dataset = project.version(PROJECT_VERSION).download("yolov5") + >>> dataset = project.version(PROJECT_VERSION).download("coco") >>> ds = sv.DetectionDataset.from_coco( ... images_directory_path=f"{dataset.location}/train/images", - ... annotations_directory_path=f"{dataset.location}/train/labels", - ... data_yaml_path=f"{dataset.location}/data.yaml" + ... annotations_directory_path=f"{dataset.location}/train/annotations.json", ... ) >>> ds.classes From 484e3d4afde95b8e3958f0f05f76a069b1888b4e Mon Sep 17 00:00:00 2001 From: hd Date: Mon, 26 Jun 2023 13:08:33 +0200 Subject: [PATCH 05/13] COCO segmentation support added --- supervision/dataset/core.py | 9 +++-- supervision/dataset/formats/coco.py | 56 ++++++++++++++++------------- 2 files changed, 39 insertions(+), 26 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 6a1cd83b..85f2b63e 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -351,8 +351,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 YOLO annotation files. - data_yaml_path (str): The path to the data YAML file containing class information. + annotations_path (str): The path to the json annotation files. force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: @@ -394,6 +393,8 @@ class DetectionDataset(BaseDataset): min_image_area_percentage: float = 0.0, max_image_area_percentage: float = 1.0, approximation_percentage: float = 0.0, + licenses: Optional[list] = None, + info: Optional[dict] = None ) -> None: """ Exports the dataset to COCO format. This method saves the images and their corresponding @@ -413,6 +414,8 @@ class DetectionDataset(BaseDataset): the image area for a detection to be included. approximation_percentage (float): The percentage of polygon points to be removed from the input polygon, in the range [0, 1). This is useful for simplifying the annotations. + licenses (Optional[str]): List of licenses for images + info (Optional[dict]): Information of Dataset as dictionary """ if images_directory_path is not None: Path(images_directory_path).mkdir(parents=True, exist_ok=True) @@ -428,6 +431,8 @@ class DetectionDataset(BaseDataset): min_image_area_percentage=min_image_area_percentage, max_image_area_percentage=max_image_area_percentage, approximation_percentage=approximation_percentage, + licenses=licenses, + info=info ) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 449b2626..061b36e0 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -14,17 +14,6 @@ from supervision.utils.file import ( read_json_file ) -""" -COCO Format Information: -coco: dict[info, licenses, categories, images, annotations] -info: dict [] -licenses: dict['id', 'url', 'name'] -categories: dict['id', 'name', 'supercategory'] -images: dict['id', 'license', 'file_name', 'height', 'width', 'date_captured'] -annotations: dict['id', 'image_id', 'category_id', 'bbox', 'area', 'segmentation', 'iscrowd'] -bbox are in [x1, y1, w, h] in original scale -""" - def _extract_class_names(annotation_data: dict) -> List[str]: names = [] @@ -47,7 +36,7 @@ def _extract_image_names(image_infos: dict) -> List[dict]: return image_names -def _annotations_dict(annotation_data: dict, with_masks: bool) -> Tuple[np.ndarray, dict]: +def _annotations_dict(annotation_data: dict) -> Tuple[np.ndarray, dict]: annotations_infos = annotation_data.get("annotations", None) # image id, label-id, category_id, bbox[0], bbox[1], bbox[2], bbox[3], segmentaions image_id_label_id_pair = np.zeros((0, 2)) @@ -75,26 +64,39 @@ def _polygons_to_masks( ) -def coco_annotations_to_detections(image_annotations: List[dict], with_masks: bool) -> Detections: +def coco_annotations_to_detections(image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool) \ + -> Detections: """ Returns: object: detections """ detection = Detections.empty() - masks = [] if with_masks else None class_ids = [] xyxy = [] + polygons = [] + for image_annotation in image_annotations: bbox = image_annotation['bbox'] xyxy.append(bbox) class_ids.append(image_annotation['category_id']) - # _polygons = image_annotation['segmentation'] + if with_masks: + _polygons = image_annotation['segmentation'] + _polygons = np.asarray(_polygons, dtype=np.int32) + _polygons = np.reshape(_polygons, (-1, 2)) + polygons.append(_polygons) + xyxy = np.asarray(xyxy) if xyxy.shape[0] > 0: xyxy[:, 2] += xyxy[:, 0] xyxy[:, 3] += xyxy[:, 1] class_ids = np.asarray(class_ids, dtype=int) - detection = Detections(xyxy=xyxy, class_id=class_ids) + + if with_masks: + mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + detection = Detections(class_id=class_ids, xyxy=xyxy, mask=mask) + else: + detection = Detections(xyxy=xyxy, class_id=class_ids) + return detection @@ -118,12 +120,13 @@ def load_coco_annotations( classes = _extract_class_names(annotation_data=annotation_data) images_infos = _extract_image_info(annotation_data=annotation_data) - image_id_label_id_pair, annotation_dict = _annotations_dict(annotation_data=annotation_data, with_masks=force_masks) + image_id_label_id_pair, annotation_dict = _annotations_dict(annotation_data=annotation_data) images = {} annotations = {} for images_info in images_infos: + image_path = os.path.join(images_directory_path, images_info["file_name"]) image = cv2.imread(str(image_path)) @@ -134,10 +137,14 @@ def load_coco_annotations( for per_image_label_id in per_image_label_ids: image_annotations.append(annotation_dict[int(per_image_label_id)]) - annotation = coco_annotations_to_detections(image_annotations=image_annotations, with_masks=force_masks) + w, h = images_info["width"], images_info["height"] + + annotation = coco_annotations_to_detections(image_annotations=image_annotations, resolution_wh=(w, h), + with_masks=force_masks) images[images_info["file_name"]] = image annotations[images_info["file_name"]] = annotation + return classes, images, annotations @@ -171,23 +178,23 @@ def save_coco_annotations( for image_name, image in images.items(): image_height, image_width, _ = image.shape - # TODO: Modify datetime format image_info = {'id': image_id, 'license': 1, 'file_name': image_name, 'height': image_height, 'width': image_width, - 'date_captured': datetime.now().strftime("%m/%d/%Y, %H:%M:%S") + 'date_captured': datetime.now().strftime("%m/%d/%Y,%H:%M:%S") } image_infos.append(image_info) detections = annotations[image_name] + for xyxy, mask, confidence, class_id, tracker_id in detections: - polygons = [] + polygon = [] if mask is not None: - polygons = approximate_mask_with_polygons( + polygon = 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()) per_label_dict = {} per_label_dict['id'] = label_id @@ -196,7 +203,8 @@ def save_coco_annotations( w, h = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] per_label_dict['bbox'] = [xyxy[0], xyxy[1], w, h] per_label_dict['area'] = w * h # width x height - per_label_dict['segmentation'] = polygons + + per_label_dict['segmentation'] = polygon per_label_dict['iscrowd'] = 0 annotations_data.append(per_label_dict) label_id += 1 From beea21a97d152d2582b69e9521758e9cf16458e7 Mon Sep 17 00:00:00 2001 From: hd Date: Mon, 26 Jun 2023 20:05:15 +0200 Subject: [PATCH 06/13] Resolved issue, code quality checked, ready for review --- supervision/dataset/core.py | 38 +++--- supervision/dataset/formats/coco.py | 179 +++++++++++++++++----------- supervision/utils/file.py | 12 +- 3 files changed, 132 insertions(+), 97 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 85f2b63e..5411ea7f 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -10,6 +10,10 @@ import cv2 import numpy as np from supervision.classification.core import Classifications +from supervision.dataset.formats.coco import ( + load_coco_annotations, + save_coco_annotations, +) from supervision.dataset.formats.pascal_voc import ( detections_to_pascal_voc, load_pascal_voc_annotations, @@ -19,12 +23,6 @@ from supervision.dataset.formats.yolo import ( save_data_yaml, save_yolo_annotations, ) - -from supervision.dataset.formats.coco import ( - load_coco_annotations, - save_coco_annotations -) - from supervision.dataset.ultils import save_dataset_images, train_test_split from supervision.detection.core import Detections from supervision.utils.file import list_files_with_extensions @@ -341,10 +339,10 @@ class DetectionDataset(BaseDataset): @classmethod def from_coco( - cls, - images_directory_path: str, - annotations_path: str, - force_masks: bool = False, + cls, + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, ) -> DetectionDataset: """ Creates a Dataset instance from YOLO formatted data. @@ -372,7 +370,7 @@ class DetectionDataset(BaseDataset): >>> ds = sv.DetectionDataset.from_coco( ... images_directory_path=f"{dataset.location}/train/images", - ... annotations_directory_path=f"{dataset.location}/train/annotations.json", + ... annotations_path=f"{dataset.location}/train/_annotations.coco.json", ... ) >>> ds.classes @@ -387,14 +385,14 @@ class DetectionDataset(BaseDataset): return DetectionDataset(classes=classes, images=images, annotations=annotations) def as_coco( - self, - images_directory_path: Optional[str] = None, - annotations_path: Optional[str] = None, - min_image_area_percentage: float = 0.0, - max_image_area_percentage: float = 1.0, - approximation_percentage: float = 0.0, - licenses: Optional[list] = None, - info: Optional[dict] = None + self, + images_directory_path: Optional[str] = None, + annotations_path: Optional[str] = None, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + licenses: Optional[list] = None, + info: Optional[dict] = None, ) -> None: """ Exports the dataset to COCO format. This method saves the images and their corresponding @@ -432,7 +430,7 @@ class DetectionDataset(BaseDataset): max_image_area_percentage=max_image_area_percentage, approximation_percentage=approximation_percentage, licenses=licenses, - info=info + info=info, ) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 061b36e0..7d344de5 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -9,10 +9,7 @@ import numpy as np from supervision.dataset.ultils import approximate_mask_with_polygons from supervision.detection.core import Detections from supervision.detection.utils import polygon_to_mask -from supervision.utils.file import ( - save_json_file, - read_json_file -) +from supervision.utils.file import read_json_file, save_json_file def _extract_class_names(annotation_data: dict) -> List[str]: @@ -38,7 +35,6 @@ def _extract_image_names(image_infos: dict) -> List[dict]: def _annotations_dict(annotation_data: dict) -> Tuple[np.ndarray, dict]: annotations_infos = annotation_data.get("annotations", None) - # image id, label-id, category_id, bbox[0], bbox[1], bbox[2], bbox[3], segmentaions image_id_label_id_pair = np.zeros((0, 2)) annotations = {} for anno in annotations_infos: @@ -47,13 +43,13 @@ def _annotations_dict(annotation_data: dict) -> Tuple[np.ndarray, dict]: _annotations[key] = anno[key] id_pair = np.array([[anno["image_id"], anno["id"]]]) image_id_label_id_pair = np.append(image_id_label_id_pair, id_pair, axis=0) - annotations[anno['id']] = _annotations + annotations[anno["id"]] = _annotations return image_id_label_id_pair, annotations def _polygons_to_masks( - polygons: List[np.ndarray], resolution_wh: Tuple[int, int] + polygons: List[np.ndarray], resolution_wh: Tuple[int, int] ) -> np.ndarray: return np.array( [ @@ -64,23 +60,20 @@ def _polygons_to_masks( ) -def coco_annotations_to_detections(image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool) \ - -> Detections: - """ - Returns: - object: detections - """ +def coco_annotations_to_detections( + image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool +) -> Detections: detection = Detections.empty() class_ids = [] xyxy = [] polygons = [] for image_annotation in image_annotations: - bbox = image_annotation['bbox'] + bbox = image_annotation["bbox"] xyxy.append(bbox) - class_ids.append(image_annotation['category_id']) + class_ids.append(image_annotation["category_id"]) if with_masks: - _polygons = image_annotation['segmentation'] + _polygons = image_annotation["segmentation"] _polygons = np.asarray(_polygons, dtype=np.int32) _polygons = np.reshape(_polygons, (-1, 2)) polygons.append(_polygons) @@ -100,10 +93,57 @@ def coco_annotations_to_detections(image_annotations: List[dict], resolution_wh: return detection +def detections_to_coco_annotations( + detections: Detections, + image_id: int, + label_id: int, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, +) -> Tuple[List[Dict], int]: + annotations_data = [] + for xyxy, mask, confidence, class_id, tracker_id in detections: + polygon = [] + if mask is not None: + polygon = 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() + ) + + per_label_dict = {} + per_label_dict["id"] = label_id + per_label_dict["image_id"] = image_id + per_label_dict["category_id"] = int(class_id) + box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] + per_label_dict["bbox"] = [xyxy[0], xyxy[1], box_width, box_height] + per_label_dict["area"] = box_width * box_height + per_label_dict["segmentation"] = polygon + per_label_dict["iscrowd"] = 0 + annotations_data.append(per_label_dict) + label_id += 1 + return annotations_data, label_id + + +def classes_to_coco_category_map(classes: List[str]) -> List[Dict]: + categories = [] + for class_id, class_name in enumerate(classes): + cate_dict = { + "id": class_id, + "name": class_name, + "supercategory": "common-objects", + } + categories.append(cate_dict) + return categories + + def load_coco_annotations( - images_directory_path: str, - annotations_path: str, - force_masks: bool = False, + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, ) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: """ Loads YOLO annotations and returns class names, images, and their corresponding detections. @@ -120,18 +160,21 @@ def load_coco_annotations( classes = _extract_class_names(annotation_data=annotation_data) images_infos = _extract_image_info(annotation_data=annotation_data) - image_id_label_id_pair, annotation_dict = _annotations_dict(annotation_data=annotation_data) + image_id_label_id_pair, annotation_dict = _annotations_dict( + annotation_data=annotation_data + ) images = {} annotations = {} for images_info in images_infos: - image_path = os.path.join(images_directory_path, images_info["file_name"]) image = cv2.imread(str(image_path)) # Filter annotations based on image id - per_image_label_ids = image_id_label_id_pair[image_id_label_id_pair[:, 0] == images_info["id"]][:, 1] + per_image_label_ids = image_id_label_id_pair[ + image_id_label_id_pair[:, 0] == images_info["id"] + ][:, 1] image_annotations = [] for per_image_label_id in per_image_label_ids: @@ -139,8 +182,11 @@ def load_coco_annotations( w, h = images_info["width"], images_info["height"] - annotation = coco_annotations_to_detections(image_annotations=image_annotations, resolution_wh=(w, h), - with_masks=force_masks) + annotation = coco_annotations_to_detections( + image_annotations=image_annotations, + resolution_wh=(w, h), + with_masks=force_masks, + ) images[images_info["file_name"]] = image annotations[images_info["file_name"]] = annotation @@ -149,73 +195,66 @@ def load_coco_annotations( def save_coco_annotations( - annotation_path: str, - images: Dict[str, np.ndarray], - annotations: Dict[str, Detections], - classes: List[str], - min_image_area_percentage: float = 0.0, - max_image_area_percentage: float = 1.0, - approximation_percentage: float = 0.75, - licenses: List[dict] = None, - info: dict = None + annotation_path: str, + images: Dict[str, np.ndarray], + annotations: Dict[str, Detections], + classes: List[str], + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, + licenses: List[dict] = None, + info: dict = None, ) -> None: Path(annotation_path).parents[2].mkdir(parents=True, exist_ok=True) if not info: info = {} if not licenses: - licenses = [{'id': 1, 'url': 'https://creativecommons.org/licenses/by/4.0/', 'name': 'CC BY 4.0'}] + licenses = [ + { + "id": 1, + "url": "https://creativecommons.org/licenses/by/4.0/", + "name": "CC BY 4.0", + } + ] annotations_data = [] image_infos = [] - categories = [] - - for class_id, class_name in enumerate(classes): - cate_dict = {'id': class_id, 'name': class_name, "supercategory": "common-objects"} - categories.append(cate_dict) + categories = classes_to_coco_category_map(classes=classes) image_id = 0 label_id = 0 for image_name, image in images.items(): image_height, image_width, _ = image.shape - image_info = {'id': image_id, 'license': 1, 'file_name': image_name, - 'height': image_height, 'width': image_width, - 'date_captured': datetime.now().strftime("%m/%d/%Y,%H:%M:%S") - } + image_info = { + "id": image_id, + "license": 1, + "file_name": image_name, + "height": image_height, + "width": image_width, + "date_captured": datetime.now().strftime("%m/%d/%Y,%H:%M:%S"), + } image_infos.append(image_info) detections = annotations[image_name] - for xyxy, mask, confidence, class_id, tracker_id in detections: - polygon = [] - if mask is not None: - polygon = 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()) - - per_label_dict = {} - per_label_dict['id'] = label_id - per_label_dict['image_id'] = image_id - per_label_dict['category_id'] = int(class_id) - w, h = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] - per_label_dict['bbox'] = [xyxy[0], xyxy[1], w, h] - per_label_dict['area'] = w * h # width x height - - per_label_dict['segmentation'] = polygon - per_label_dict['iscrowd'] = 0 - annotations_data.append(per_label_dict) - label_id += 1 + per_image_labels, label_id = detections_to_coco_annotations( + detections=detections, + image_id=image_id, + label_id=label_id, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + annotations_data.extend(per_image_labels) image_id += 1 annotation_dict = { - 'info': info, - 'licenses': licenses, - 'categories': categories, - 'images': image_infos, - 'annotations': annotations_data + "info": info, + "licenses": licenses, + "categories": categories, + "images": image_infos, + "annotations": annotations_data, } save_json_file(annotation_dict, file_path=annotation_path) diff --git a/supervision/utils/file.py b/supervision/utils/file.py index 4c2b92d4..7af669ca 100644 --- a/supervision/utils/file.py +++ b/supervision/utils/file.py @@ -5,7 +5,7 @@ from typing import List, Optional, Union import numpy as np -class NpEncoder(json.JSONEncoder): +class NumpyJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) @@ -13,8 +13,7 @@ class NpEncoder(json.JSONEncoder): return float(obj) if isinstance(obj, np.ndarray): return obj.tolist() - return super(NpEncoder, self).default(obj) - + return super(NumpyJsonEncoder, self).default(obj) def list_files_with_extensions( @@ -98,7 +97,7 @@ def read_json_file(file_path: str) -> dict: return data -def save_json_file(data: dict, file_path: str, indent=3): +def save_json_file(data: dict, file_path: str, indent: int = 3) -> None: """ Write a dict to a json file. @@ -106,6 +105,5 @@ def save_json_file(data: dict, file_path: str, indent=3): data (dict): dict with unique keys and value as pair. file_path (str): The path to the json file. """ - with open(file_path, 'w') as fp: - json.dump(data, fp, cls=NpEncoder, indent=indent) - + with open(file_path, "w") as fp: + json.dump(data, fp, cls=NumpyJsonEncoder, indent=indent) From 540efc80ce2cfcd37539d35a621575db1f536764 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 01:50:58 +0200 Subject: [PATCH 07/13] classes_to_coco_categories, coco_categories_to_classes refactor + tests --- supervision/dataset/formats/coco.py | 54 +++++------- test/dataset/formats/test_coco.py | 132 ++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 31 deletions(-) create mode 100644 test/dataset/formats/test_coco.py diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 7d344de5..091bb19e 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -12,13 +12,23 @@ from supervision.detection.utils import polygon_to_mask from supervision.utils.file import read_json_file, save_json_file -def _extract_class_names(annotation_data: dict) -> List[str]: - names = [] - categories = annotation_data.get("categories", None) - if categories: - for cat in categories: - names.append(cat["name"]) - return names +def coco_categories_to_classes(coco_categories: List[dict]) -> List[str]: + return [ + category["name"] + for category in sorted(coco_categories, key=lambda category: category["id"]) + if category["supercategory"] != "none" + ] + + +def classes_to_coco_categories(classes: List[str]) -> List[dict]: + return [ + { + "id": class_id, + "name": class_name, + "supercategory": "common-objects", + } + for class_id, class_name in enumerate(classes) + ] def _extract_image_info(annotation_data: dict) -> List[dict]: @@ -26,13 +36,6 @@ def _extract_image_info(annotation_data: dict) -> List[dict]: return image_infos -def _extract_image_names(image_infos: dict) -> List[dict]: - image_names = [] - for image_info in image_infos: - image_names.append(image_info["file_name"]) - return image_names - - def _annotations_dict(annotation_data: dict) -> Tuple[np.ndarray, dict]: annotations_infos = annotation_data.get("annotations", None) image_id_label_id_pair = np.zeros((0, 2)) @@ -128,18 +131,6 @@ def detections_to_coco_annotations( return annotations_data, label_id -def classes_to_coco_category_map(classes: List[str]) -> List[Dict]: - categories = [] - for class_id, class_name in enumerate(classes): - cate_dict = { - "id": class_id, - "name": class_name, - "supercategory": "common-objects", - } - categories.append(cate_dict) - return categories - - def load_coco_annotations( images_directory_path: str, annotations_path: str, @@ -158,7 +149,7 @@ def load_coco_annotations( """ annotation_data = read_json_file(file_path=annotations_path) - classes = _extract_class_names(annotation_data=annotation_data) + classes = coco_categories_to_classes(coco_categories=annotation_data["categories"]) images_infos = _extract_image_info(annotation_data=annotation_data) image_id_label_id_pair, annotation_dict = _annotations_dict( annotation_data=annotation_data @@ -168,7 +159,8 @@ def load_coco_annotations( annotations = {} for images_info in images_infos: - image_path = os.path.join(images_directory_path, images_info["file_name"]) + image_name = images_info["file_name"] + image_path = os.path.join(images_directory_path, image_name) image = cv2.imread(str(image_path)) # Filter annotations based on image id @@ -188,8 +180,8 @@ def load_coco_annotations( with_masks=force_masks, ) - images[images_info["file_name"]] = image - annotations[images_info["file_name"]] = annotation + images[image_name] = image + annotations[image_name] = annotation return classes, images, annotations @@ -219,7 +211,7 @@ def save_coco_annotations( annotations_data = [] image_infos = [] - categories = classes_to_coco_category_map(classes=classes) + categories = classes_to_coco_categories(classes=classes) image_id = 0 label_id = 0 diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py new file mode 100644 index 00000000..f0ed80b5 --- /dev/null +++ b/test/dataset/formats/test_coco.py @@ -0,0 +1,132 @@ +from contextlib import ExitStack as DoesNotRaise +from typing import List + +import pytest + +from supervision.dataset.formats.coco import classes_to_coco_categories, coco_categories_to_classes + + +@pytest.mark.parametrize( + "coco_categories, expected_result, exception", + [ + ( + [], + [], + DoesNotRaise() + ), # empty coco categories + ( + [ + { + "id": 0, + "name": "fashion-assistant", + "supercategory": "none" + } + ], + [], + DoesNotRaise() + ), # single coco category with supercategory == "none" + ( + [ + { + "id": 0, + "name": "fashion-assistant", + "supercategory": "none" + }, + { + "id": 1, + "name": "baseball cap", + "supercategory": "fashion-assistant" + } + ], + [ + "baseball cap" + ], + DoesNotRaise() + ), # two coco categories; one with supercategory == "none" and one with supercategory != "none" + ( + [ + { + "id": 0, + "name": "fashion-assistant", + "supercategory": "none" + }, + { + "id": 1, + "name": "baseball cap", + "supercategory": "fashion-assistant" + }, + { + "id": 2, + "name": "hoodie", + "supercategory": "fashion-assistant" + } + ], + [ + "baseball cap", + "hoodie" + ], + DoesNotRaise() + ), # three coco categories; one with supercategory == "none" and two with supercategory != "none" + ( + [ + { + "id": 0, + "name": "fashion-assistant", + "supercategory": "none" + }, + { + "id": 2, + "name": "hoodie", + "supercategory": "fashion-assistant" + }, + { + "id": 1, + "name": "baseball cap", + "supercategory": "fashion-assistant" + } + ], + [ + "baseball cap", + "hoodie" + ], + DoesNotRaise() + ), # three coco categories; one with supercategory == "none" and two with supercategory != "none" (different order) + ] +) +def test_coco_categories_to_classes( + coco_categories: List[dict], + expected_result: List[str], + exception: Exception +) -> None: + with exception: + result = coco_categories_to_classes(coco_categories=coco_categories) + assert result == expected_result + + +@pytest.mark.parametrize( + "classes, exception", + [ + ( + [], + DoesNotRaise() + ), # empty classes + ( + [ + "baseball cap" + ], + DoesNotRaise() + ), # single class + ( + [ + "baseball cap", + "hoodie" + ], + DoesNotRaise() + ), # two classes + ] +) +def test_classes_to_coco_categories_and_back_to_classes(classes: List[str], exception: Exception) -> None: + with exception: + coco_categories = classes_to_coco_categories(classes=classes) + result = coco_categories_to_classes(coco_categories=coco_categories) + assert result == classes From 4d8246035818d40e7c3e2009b8c7d1b2f83fab26 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 02:09:56 +0200 Subject: [PATCH 08/13] naming refactor --- supervision/dataset/core.py | 3 +-- supervision/dataset/formats/coco.py | 36 ++++++++++++++--------------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 5411ea7f..cf214651 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -369,7 +369,7 @@ class DetectionDataset(BaseDataset): >>> dataset = project.version(PROJECT_VERSION).download("coco") >>> ds = sv.DetectionDataset.from_coco( - ... images_directory_path=f"{dataset.location}/train/images", + ... images_directory_path=f"{dataset.location}/train", ... annotations_path=f"{dataset.location}/train/_annotations.coco.json", ... ) @@ -416,7 +416,6 @@ class DetectionDataset(BaseDataset): info (Optional[dict]): Information of Dataset as dictionary """ if images_directory_path is not None: - Path(images_directory_path).mkdir(parents=True, exist_ok=True) save_dataset_images( images_directory_path=images_directory_path, images=self.images ) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 091bb19e..1c0e6b55 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -150,7 +150,7 @@ def load_coco_annotations( annotation_data = read_json_file(file_path=annotations_path) classes = coco_categories_to_classes(coco_categories=annotation_data["categories"]) - images_infos = _extract_image_info(annotation_data=annotation_data) + coco_images = annotation_data["images"] image_id_label_id_pair, annotation_dict = _annotations_dict( annotation_data=annotation_data ) @@ -158,21 +158,21 @@ def load_coco_annotations( images = {} annotations = {} - for images_info in images_infos: - image_name = images_info["file_name"] + for coco_image in coco_images: + image_name = coco_image["file_name"] image_path = os.path.join(images_directory_path, image_name) image = cv2.imread(str(image_path)) # Filter annotations based on image id per_image_label_ids = image_id_label_id_pair[ - image_id_label_id_pair[:, 0] == images_info["id"] + image_id_label_id_pair[:, 0] == coco_image["id"] ][:, 1] image_annotations = [] for per_image_label_id in per_image_label_ids: image_annotations.append(annotation_dict[int(per_image_label_id)]) - w, h = images_info["width"], images_info["height"] + w, h = coco_image["width"], coco_image["height"] annotation = coco_annotations_to_detections( image_annotations=image_annotations, @@ -197,7 +197,7 @@ def save_coco_annotations( licenses: List[dict] = None, info: dict = None, ) -> None: - Path(annotation_path).parents[2].mkdir(parents=True, exist_ok=True) + Path(annotation_path).parent.mkdir(parents=True, exist_ok=True) if not info: info = {} if not licenses: @@ -209,16 +209,16 @@ def save_coco_annotations( } ] - annotations_data = [] - image_infos = [] - categories = classes_to_coco_categories(classes=classes) + coco_annotations = [] + coco_images = [] + coco_categories = classes_to_coco_categories(classes=classes) image_id = 0 - label_id = 0 + annotation_id = 0 for image_name, image in images.items(): image_height, image_width, _ = image.shape - image_info = { + coco_image = { "id": image_id, "license": 1, "file_name": image_name, @@ -227,26 +227,26 @@ def save_coco_annotations( "date_captured": datetime.now().strftime("%m/%d/%Y,%H:%M:%S"), } - image_infos.append(image_info) + coco_images.append(coco_image) detections = annotations[image_name] - per_image_labels, label_id = detections_to_coco_annotations( + coco_annotation, label_id = detections_to_coco_annotations( detections=detections, image_id=image_id, - label_id=label_id, + label_id=annotation_id, min_image_area_percentage=min_image_area_percentage, max_image_area_percentage=max_image_area_percentage, approximation_percentage=approximation_percentage, ) - annotations_data.extend(per_image_labels) + coco_annotations.extend(coco_annotation) image_id += 1 annotation_dict = { "info": info, "licenses": licenses, - "categories": categories, - "images": image_infos, - "annotations": annotations_data, + "categories": coco_categories, + "images": coco_images, + "annotations": coco_annotations, } save_json_file(annotation_dict, file_path=annotation_path) From f63336a824be74372d66c5bef7acff07fd5ae3ef Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 02:44:40 +0200 Subject: [PATCH 09/13] save_coco_annotations logic simplification --- supervision/dataset/formats/coco.py | 59 +++++++----------- test/dataset/formats/test_coco.py | 97 ++++++++++++++++++++++++++++- 2 files changed, 117 insertions(+), 39 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index 1c0e6b55..b9ea4fdb 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -31,24 +31,16 @@ def classes_to_coco_categories(classes: List[str]) -> List[dict]: ] -def _extract_image_info(annotation_data: dict) -> List[dict]: - image_infos = annotation_data.get("images", None) - return image_infos - - -def _annotations_dict(annotation_data: dict) -> Tuple[np.ndarray, dict]: - annotations_infos = annotation_data.get("annotations", None) - image_id_label_id_pair = np.zeros((0, 2)) +def group_coco_annotations_by_image_id( + coco_annotations: List[dict], +) -> Dict[int, List[dict]]: annotations = {} - for anno in annotations_infos: - _annotations = {} - for key, item in anno.items(): - _annotations[key] = anno[key] - id_pair = np.array([[anno["image_id"], anno["id"]]]) - image_id_label_id_pair = np.append(image_id_label_id_pair, id_pair, axis=0) - annotations[anno["id"]] = _annotations - - return image_id_label_id_pair, annotations + for annotation in coco_annotations: + image_id = annotation["image_id"] + if image_id not in annotations: + annotations[image_id] = [] + annotations[image_id].append(annotation) + return annotations def _polygons_to_masks( @@ -147,36 +139,29 @@ def load_coco_annotations( Returns: 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. """ - annotation_data = read_json_file(file_path=annotations_path) - - classes = coco_categories_to_classes(coco_categories=annotation_data["categories"]) - coco_images = annotation_data["images"] - image_id_label_id_pair, annotation_dict = _annotations_dict( - annotation_data=annotation_data + coco_data = read_json_file(file_path=annotations_path) + classes = coco_categories_to_classes(coco_categories=coco_data["categories"]) + coco_images = coco_data["images"] + coco_annotations_groups = group_coco_annotations_by_image_id( + coco_annotations=coco_data["annotations"] ) images = {} annotations = {} for coco_image in coco_images: - image_name = coco_image["file_name"] + image_name, image_width, image_height = ( + coco_image["file_name"], + coco_image["width"], + coco_image["height"], + ) + image_annotations = coco_annotations_groups.get(coco_image["id"]) image_path = os.path.join(images_directory_path, image_name) + image = cv2.imread(str(image_path)) - - # Filter annotations based on image id - per_image_label_ids = image_id_label_id_pair[ - image_id_label_id_pair[:, 0] == coco_image["id"] - ][:, 1] - - image_annotations = [] - for per_image_label_id in per_image_label_ids: - image_annotations.append(annotation_dict[int(per_image_label_id)]) - - w, h = coco_image["width"], coco_image["height"] - annotation = coco_annotations_to_detections( image_annotations=image_annotations, - resolution_wh=(w, h), + resolution_wh=(image_width, image_height), with_masks=force_masks, ) diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index f0ed80b5..0a75d2aa 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -1,9 +1,27 @@ from contextlib import ExitStack as DoesNotRaise -from typing import List +from typing import List, Tuple import pytest -from supervision.dataset.formats.coco import classes_to_coco_categories, coco_categories_to_classes +from supervision.dataset.formats.coco import classes_to_coco_categories, coco_categories_to_classes, \ + group_coco_annotations_by_image_id + + +def generate_cock_coco_annotation( + annotation_id: int = 0, + image_id: int = 0, + category_id: int = 0, + bbox: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0), + area: float = 0.0 +) -> dict: + return { + "id": annotation_id, + "image_id": image_id, + "category_id": category_id, + "bbox": list(bbox), + "area": area, + "iscrowd": 0 + } @pytest.mark.parametrize( @@ -130,3 +148,78 @@ def test_classes_to_coco_categories_and_back_to_classes(classes: List[str], exce coco_categories = classes_to_coco_categories(classes=classes) result = coco_categories_to_classes(coco_categories=coco_categories) assert result == classes + + +@pytest.mark.parametrize( + "coco_annotations, expected_result, exception", + [ + ( + [], + {}, + DoesNotRaise() + ), # empty coco annotations + ( + [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0) + ], + { + 0: [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0) + ] + }, + DoesNotRaise() + ), # single coco annotation + ( + [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0), + generate_cock_coco_annotation(annotation_id=1, image_id=1, category_id=0) + ], + { + 0: [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0) + ], + 1: [ + generate_cock_coco_annotation(annotation_id=1, image_id=1, category_id=0) + ] + }, + DoesNotRaise() + ), # two coco annotations + ( + [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0), + generate_cock_coco_annotation(annotation_id=1, image_id=1, category_id=1), + generate_cock_coco_annotation(annotation_id=2, image_id=1, category_id=2), + generate_cock_coco_annotation(annotation_id=3, image_id=2, category_id=3), + generate_cock_coco_annotation(annotation_id=4, image_id=3, category_id=1), + generate_cock_coco_annotation(annotation_id=5, image_id=3, category_id=2), + generate_cock_coco_annotation(annotation_id=5, image_id=3, category_id=3), + ], + { + 0: [ + generate_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0), + ], + 1: [ + generate_cock_coco_annotation(annotation_id=1, image_id=1, category_id=1), + generate_cock_coco_annotation(annotation_id=2, image_id=1, category_id=2), + ], + 2: [ + generate_cock_coco_annotation(annotation_id=3, image_id=2, category_id=3), + ], + 3: [ + generate_cock_coco_annotation(annotation_id=4, image_id=3, category_id=1), + generate_cock_coco_annotation(annotation_id=5, image_id=3, category_id=2), + generate_cock_coco_annotation(annotation_id=5, image_id=3, category_id=3), + ] + }, + DoesNotRaise() + ), # two coco annotations + ] +) +def test_group_coco_annotations_by_image_id( + coco_annotations: List[dict], + expected_result: dict, + exception: Exception +) -> None: + with exception: + result = group_coco_annotations_by_image_id(coco_annotations=coco_annotations) + assert result == expected_result From 5bf78e55053c080e454c3923ab2d23dfcc6a8024 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 02:52:20 +0200 Subject: [PATCH 10/13] naming refactor --- supervision/dataset/formats/coco.py | 28 ++++++++++++++-------------- supervision/detection/core.py | 14 -------------- 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index b9ea4fdb..fac0b1af 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -91,12 +91,12 @@ def coco_annotations_to_detections( def detections_to_coco_annotations( detections: Detections, image_id: int, - label_id: int, + annotation_id: int, min_image_area_percentage: float = 0.0, max_image_area_percentage: float = 1.0, approximation_percentage: float = 0.75, ) -> Tuple[List[Dict], int]: - annotations_data = [] + coco_annotations = [] for xyxy, mask, confidence, class_id, tracker_id in detections: polygon = [] if mask is not None: @@ -109,18 +109,18 @@ def detections_to_coco_annotations( )[0].flatten() ) - per_label_dict = {} - per_label_dict["id"] = label_id - per_label_dict["image_id"] = image_id - per_label_dict["category_id"] = int(class_id) + coco_annotation = {} + coco_annotation["id"] = annotation_id + coco_annotation["image_id"] = image_id + coco_annotation["category_id"] = int(class_id) box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] - per_label_dict["bbox"] = [xyxy[0], xyxy[1], box_width, box_height] - per_label_dict["area"] = box_width * box_height - per_label_dict["segmentation"] = polygon - per_label_dict["iscrowd"] = 0 - annotations_data.append(per_label_dict) - label_id += 1 - return annotations_data, label_id + coco_annotation["bbox"] = [xyxy[0], xyxy[1], box_width, box_height] + coco_annotation["area"] = box_width * box_height + coco_annotation["segmentation"] = polygon + coco_annotation["iscrowd"] = 0 + coco_annotations.append(coco_annotation) + annotation_id += 1 + return coco_annotations, annotation_id def load_coco_annotations( @@ -218,7 +218,7 @@ def save_coco_annotations( coco_annotation, label_id = detections_to_coco_annotations( detections=detections, image_id=image_id, - label_id=annotation_id, + annotation_id=annotation_id, min_image_area_percentage=min_image_area_percentage, max_image_area_percentage=max_image_area_percentage, approximation_percentage=approximation_percentage, diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 97150e45..93c8e1fb 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -355,20 +355,6 @@ class Detections: return Detections(xyxy=xywh_to_xyxy(boxes_xywh=xywh), mask=mask) - @classmethod - @deprecated( - "Dataset loading and saving is going to be executed by supervision.dataset.core.Dataset" - ) - def from_coco_annotations(cls, coco_annotation: dict) -> Detections: - xyxy, class_id = [], [] - - for annotation in coco_annotation: - x_min, y_min, width, height = annotation["bbox"] - xyxy.append([x_min, y_min, x_min + width, y_min + height]) - class_id.append(annotation["category_id"]) - - return cls(xyxy=np.array(xyxy), class_id=np.array(class_id)) - @classmethod def empty(cls) -> Detections: """ From de1ceff0651c1b074a2062b8506437a9454787dc Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 03:02:24 +0200 Subject: [PATCH 11/13] small fix --- 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 fac0b1af..953ec540 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -155,7 +155,7 @@ def load_coco_annotations( coco_image["width"], coco_image["height"], ) - image_annotations = coco_annotations_groups.get(coco_image["id"]) + image_annotations = coco_annotations_groups.get(coco_image["id"], []) image_path = os.path.join(images_directory_path, image_name) image = cv2.imread(str(image_path)) From b40265db9e4f441857c19c6fd673407a80e3032e Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 03:02:57 +0200 Subject: [PATCH 12/13] small fix --- 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 953ec540..a01a68b3 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -129,7 +129,7 @@ def load_coco_annotations( force_masks: bool = False, ) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: """ - Loads YOLO annotations and returns class names, images, and their corresponding detections. + Loads COCO annotations and returns class names, images, and their corresponding detections. Args: images_directory_path (str): The path to the directory containing the images. From 782e7e5a3966fa8cee6de3a219c93ed5d9cfc1d6 Mon Sep 17 00:00:00 2001 From: SkalskiP Date: Tue, 27 Jun 2023 13:53:27 +0200 Subject: [PATCH 13/13] ready for final tests --- supervision/dataset/formats/coco.py | 76 ++++++++++++----------------- test/dataset/formats/test_coco.py | 67 ++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 47 deletions(-) diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py index a01a68b3..08da424b 100644 --- a/supervision/dataset/formats/coco.py +++ b/supervision/dataset/formats/coco.py @@ -58,34 +58,29 @@ def _polygons_to_masks( def coco_annotations_to_detections( image_annotations: List[dict], resolution_wh: Tuple[int, int], with_masks: bool ) -> Detections: - detection = Detections.empty() - class_ids = [] - xyxy = [] - polygons = [] - - for image_annotation in image_annotations: - bbox = image_annotation["bbox"] - xyxy.append(bbox) - class_ids.append(image_annotation["category_id"]) - if with_masks: - _polygons = image_annotation["segmentation"] - _polygons = np.asarray(_polygons, dtype=np.int32) - _polygons = np.reshape(_polygons, (-1, 2)) - polygons.append(_polygons) + if not image_annotations: + return Detections.empty() + class_ids = [ + image_annotation["category_id"] for image_annotation in image_annotations + ] + xyxy = [image_annotation["bbox"] for image_annotation in image_annotations] xyxy = np.asarray(xyxy) - if xyxy.shape[0] > 0: - xyxy[:, 2] += xyxy[:, 0] - xyxy[:, 3] += xyxy[:, 1] - class_ids = np.asarray(class_ids, dtype=int) + xyxy[:, 2:4] += xyxy[:, 0:2] - if with_masks: - mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) - detection = Detections(class_id=class_ids, xyxy=xyxy, mask=mask) - else: - detection = Detections(xyxy=xyxy, class_id=class_ids) + if with_masks: + polygons = [ + np.reshape( + np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2) + ) + for image_annotation in image_annotations + ] + mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + return Detections( + class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask + ) - return detection + return Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) def detections_to_coco_annotations( @@ -97,7 +92,8 @@ def detections_to_coco_annotations( approximation_percentage: float = 0.75, ) -> Tuple[List[Dict], int]: coco_annotations = [] - for xyxy, mask, confidence, class_id, tracker_id in detections: + for xyxy, mask, _, class_id, _ in detections: + box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] polygon = [] if mask is not None: polygon = list( @@ -108,16 +104,15 @@ def detections_to_coco_annotations( approximation_percentage=approximation_percentage, )[0].flatten() ) - - coco_annotation = {} - coco_annotation["id"] = annotation_id - coco_annotation["image_id"] = image_id - coco_annotation["category_id"] = int(class_id) - box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] - coco_annotation["bbox"] = [xyxy[0], xyxy[1], box_width, box_height] - coco_annotation["area"] = box_width * box_height - coco_annotation["segmentation"] = polygon - coco_annotation["iscrowd"] = 0 + 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, + "iscrowd": 0, + } coco_annotations.append(coco_annotation) annotation_id += 1 return coco_annotations, annotation_id @@ -128,17 +123,6 @@ def load_coco_annotations( annotations_path: str, force_masks: bool = False, ) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: - """ - Loads COCO annotations and returns class names, images, and their corresponding detections. - - Args: - images_directory_path (str): The path to the directory containing the images. - annotations_path (str): The path to the coco json annotation file. - force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. - - Returns: - 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. - """ coco_data = read_json_file(file_path=annotations_path) classes = coco_categories_to_classes(coco_categories=coco_data["categories"]) coco_images = coco_data["images"] diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py index 0a75d2aa..3b8d8856 100644 --- a/test/dataset/formats/test_coco.py +++ b/test/dataset/formats/test_coco.py @@ -3,8 +3,11 @@ from typing import List, Tuple import pytest +from supervision import Detections from supervision.dataset.formats.coco import classes_to_coco_categories, coco_categories_to_classes, \ - group_coco_annotations_by_image_id + group_coco_annotations_by_image_id, coco_annotations_to_detections + +import numpy as np def generate_cock_coco_annotation( @@ -223,3 +226,65 @@ def test_group_coco_annotations_by_image_id( with exception: result = group_coco_annotations_by_image_id(coco_annotations=coco_annotations) assert result == expected_result + + +@pytest.mark.parametrize( + "image_annotations, resolution_wh, with_masks, expected_result, exception", + [ + ( + [], + (1000, 1000), + False, + Detections.empty(), + DoesNotRaise() + ), # empty image annotations + ( + [ + generate_cock_coco_annotation(category_id=0, bbox=(0, 0, 100, 100), area=100 * 100) + ], + (1000, 1000), + False, + Detections( + xyxy=np.array([ + [ 0, 0, 100, 100] + ], dtype=np.float32), + class_id=np.array([ + 0 + ], dtype=int) + ), + DoesNotRaise() + ), # single image annotations + ( + [ + generate_cock_coco_annotation(category_id=0, bbox=(0, 0, 100, 100), area=100 * 100), + generate_cock_coco_annotation(category_id=0, bbox=(100, 100, 100, 100), area=100 * 100), + ], + (1000, 1000), + False, + Detections( + xyxy=np.array([ + [ 0, 0, 100, 100], + [ 100, 100, 200, 200] + ], dtype=np.float32), + class_id=np.array([ + 0, 0 + ], dtype=int) + ), + DoesNotRaise() + ), # two image annotations + ] +) +def test_coco_annotations_to_detections( + image_annotations: List[dict], + resolution_wh: Tuple[int, int], + with_masks: bool, + expected_result: Detections, + exception: Exception +) -> None: + with exception: + result = coco_annotations_to_detections( + image_annotations=image_annotations, + resolution_wh=resolution_wh, + with_masks=with_masks + ) + assert result == expected_result