generated from roboflow/template-python
-
Notifications
You must be signed in to change notification settings - Fork 3k
COCO Detection Dataset Import/Export support #150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3b2902c
COCO dataset import export interface,
hardikdava 253113f
refactored code
hardikdava 769b6b9
Tested and working version
hardikdava ab9728c
Updated doc-strings
hardikdava 484e3d4
COCO segmentation support added
hardikdava beea21a
Resolved issue, code quality checked, ready for review
hardikdava 540efc8
classes_to_coco_categories, coco_categories_to_classes refactor + tests
SkalskiP 4d82460
naming refactor
SkalskiP f63336a
save_coco_annotations logic simplification
SkalskiP 5bf78e5
naming refactor
SkalskiP de1ceff
small fix
SkalskiP b40265d
small fix
SkalskiP 782e7e5
ready for final tests
SkalskiP File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| 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 read_json_file, save_json_file | ||
|
|
||
|
|
||
| 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 group_coco_annotations_by_image_id( | ||
| coco_annotations: List[dict], | ||
| ) -> Dict[int, List[dict]]: | ||
| 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( | ||
| 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], resolution_wh: Tuple[int, int], with_masks: bool | ||
| ) -> Detections: | ||
| 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) | ||
| xyxy[:, 2:4] += xyxy[:, 0:2] | ||
|
|
||
| if with_masks: | ||
| polygons = [ | ||
| np.reshape( | ||
| np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2) | ||
| ) | ||
| for image_annotation in image_annotations | ||
| ] | ||
| 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 Detections(xyxy=xyxy, class_id=np.asarray(class_ids, dtype=int)) | ||
|
|
||
|
|
||
| def detections_to_coco_annotations( | ||
| detections: Detections, | ||
| image_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]: | ||
| coco_annotations = [] | ||
| 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( | ||
| 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() | ||
| ) | ||
| 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 | ||
|
|
||
|
|
||
| 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]]: | ||
| 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, 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)) | ||
| annotation = coco_annotations_to_detections( | ||
| image_annotations=image_annotations, | ||
| resolution_wh=(image_width, image_height), | ||
| with_masks=force_masks, | ||
| ) | ||
|
|
||
| images[image_name] = image | ||
| annotations[image_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, | ||
| licenses: List[dict] = None, | ||
| info: dict = None, | ||
| ) -> None: | ||
| Path(annotation_path).parent.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", | ||
| } | ||
| ] | ||
|
|
||
| coco_annotations = [] | ||
| coco_images = [] | ||
| coco_categories = classes_to_coco_categories(classes=classes) | ||
|
|
||
| image_id = 0 | ||
SkalskiP marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| annotation_id = 0 | ||
| for image_name, image in images.items(): | ||
| image_height, image_width, _ = image.shape | ||
|
|
||
| coco_image = { | ||
| "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"), | ||
| } | ||
|
|
||
| coco_images.append(coco_image) | ||
| detections = annotations[image_name] | ||
|
|
||
| coco_annotation, label_id = detections_to_coco_annotations( | ||
| detections=detections, | ||
| image_id=image_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, | ||
| ) | ||
|
|
||
| coco_annotations.extend(coco_annotation) | ||
| image_id += 1 | ||
|
|
||
| annotation_dict = { | ||
| "info": info, | ||
| "licenses": licenses, | ||
| "categories": coco_categories, | ||
| "images": coco_images, | ||
| "annotations": coco_annotations, | ||
| } | ||
| save_json_file(annotation_dict, file_path=annotation_path) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.