Resolved issue, code quality checked, ready for review

This commit is contained in:
hd
2023-06-26 20:05:15 +02:00
parent 484e3d4afd
commit beea21a97d
3 changed files with 132 additions and 97 deletions
+18 -20
View File
@@ -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,
)
+109 -70
View File
@@ -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)
+5 -7
View File
@@ -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)