diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index 277d8e10..b6b4f187 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -1,10 +1,12 @@ from dataclasses import dataclass +from pathlib import Path from typing import Dict, List, Optional +import cv2 import numpy as np +from supervision.dataset.formats.pascal_voc import detections_to_pascal_voc from supervision.detection.core import Detections -# from supervision.dataset.formats.pascal_voc import dataset_to_pascal_voc @dataclass @@ -14,20 +16,45 @@ class Dataset: Attributes: classes (List[str]): List containing dataset class names. - images (Dict[str, np.ndarray]): Dictionary mapping image path to image. - annotations (Dict[str, Detections]): Dictionary mapping image path to annotations. + images (Dict[str, np.ndarray]): Dictionary mapping image name to image. + annotations (Dict[str, Detections]): Dictionary mapping image name to annotations. """ + classes: List[str] images: Dict[str, np.ndarray] annotations: Dict[str, Detections] - # def as_pascal_voc( - # self, - # images_directory_path: Optional[str], - # annotations_directory_path: Optional[str] - # ) -> None: - # dataset_to_pascal_voc( - # detections=self, - # images_directory_path=images_directory_path, - # annotations_directory_path=annotations_directory_path - # ) + def as_pascal_voc( + self, + images_directory_path: Optional[str], + annotations_directory_path: Optional[str], + minimum_detection_area_percentage: float = 0.0, + maximum_detection_area_percentage: float = 1.0, + ) -> None: + if images_directory_path: + images_path = Path(images_directory_path) + images_path.mkdir(parents=True, exist_ok=True) + + if annotations_directory_path: + annotations_path = Path(annotations_directory_path) + annotations_path.mkdir(parents=True, exist_ok=True) + + for image_name, image in self.images.items(): + detections = self.annotations[image_name] + + if images_directory_path: + cv2.imwrite(str(images_path / image_name), image) + + if annotations_directory_path: + annotation_name = Path(image_name).stem + pascal_voc_xml = detections_to_pascal_voc( + detections=detections, + classes=self.classes, + filename=image_name, + image_shape=image.shape, + minimum_detection_area_percentage=minimum_detection_area_percentage, + maximum_detection_area_percentage=maximum_detection_area_percentage, + ) + + with open(annotations_path / f"{annotation_name}.xml", "w") as f: + f.write(pascal_voc_xml) diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index 13f58b62..8314ac77 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -1,13 +1,21 @@ -from typing import List, Tuple, Optional +from typing import List, Optional, Tuple from xml.dom.minidom import parseString from xml.etree.ElementTree import Element, SubElement, tostring -from supervision.detection.core import Detections - +import cv2 import numpy as np +from supervision.detection.core import Detections +from supervision.detection.utils import ( + filter_polygons_by_area, + mask_to_polygons, + polygon_to_xyxy, +) -def object_to_pascal_voc(xyxy: np.ndarray, name: str, polygon: Optional[np.ndarray] = None) -> Element: + +def object_to_pascal_voc( + xyxy: np.ndarray, name: str, polygon: Optional[np.ndarray] = None +) -> Element: root = Element("object") object_name = SubElement(root, "name") @@ -23,21 +31,25 @@ def object_to_pascal_voc(xyxy: np.ndarray, name: str, polygon: Optional[np.ndarr ymax = SubElement(bndbox, "ymax") ymax.text = str(int(xyxy[3])) - object_polygon = SubElement(root, "polygon") - for index, point in enumerate(polygon, start=1): - x_coordinate, y_coordinate = point - x = SubElement(object_polygon, f"x{index}") - x.text = str(x_coordinate) - y = SubElement(object_polygon, f"y{index}") - y.text = str(y_coordinate) + if polygon is not None: + object_polygon = SubElement(root, "polygon") + for index, point in enumerate(polygon, start=1): + x_coordinate, y_coordinate = point + x = SubElement(object_polygon, f"x{index}") + x.text = str(x_coordinate) + y = SubElement(object_polygon, f"y{index}") + y.text = str(y_coordinate) return root + def detections_to_pascal_voc( - detections: Detections, - classes: List[str], - filename: str, - image_shape: Tuple[int, int, int] + detections: Detections, + classes: List[str], + filename: str, + image_shape: Tuple[int, int, int], + minimum_detection_area_percentage: float = 0.0, + maximum_detection_area_percentage: float = 1.0, ) -> str: """ Converts Detections object to Pascal VOC XML format. @@ -47,10 +59,15 @@ def detections_to_pascal_voc( classes (List[str]): A list of class names corresponding to the class ids in the Detections object. filename (str): The name of the image file associated with the detections. image_shape (Tuple[int, int, int]): The shape of the image file associated with the detections. + minimum_detection_area_percentage (float): Minimum detection area relative to area of image associated with it. + maximum_detection_area_percentage (float): Maximum detection area relative to area of image associated with it. Returns: str: An XML string in Pascal VOC format representing the detections. """ height, width, depth = image_shape + image_area = height * width + minimum_detection_area = minimum_detection_area_percentage * image_area + maximum_detection_area = maximum_detection_area_percentage * image_area # Create root element annotation = Element("annotation") @@ -82,101 +99,33 @@ def detections_to_pascal_voc( segmented.text = "0" # Add object elements - for i in range(detections.xyxy.shape[0]): - obj = SubElement(annotation, "object") - - class_id = detections.class_id[i] if detections.class_id is not None else None - name = SubElement(obj, "name") - name.text = classes[class_id] if class_id is not None else "unknown" - - bndbox = SubElement(obj, "bndbox") - xmin = SubElement(bndbox, "xmin") - xmin.text = str(int(detections.xyxy[i, 0])) - ymin = SubElement(bndbox, "ymin") - ymin.text = str(int(detections.xyxy[i, 1])) - xmax = SubElement(bndbox, "xmax") - xmax.text = str(int(detections.xyxy[i, 2])) - ymax = SubElement(bndbox, "ymax") - ymax.text = str(int(detections.xyxy[i, 3])) + for xyxy, mask, _, class_id, _ in detections: + name = classes[class_id] + if mask is not None: + polygons = mask_to_polygons(mask=mask) + if len(polygons) == 1: + polygons = filter_polygons_by_area( + polygons=polygons, min_area=None, max_area=maximum_detection_area + ) + else: + polygons = filter_polygons_by_area( + polygons=polygons, + min_area=minimum_detection_area, + max_area=maximum_detection_area, + ) + for polygon in polygons: + approx_polygon = cv2.approxPolyDP(polygon, 1.0, True) + approx_polygon = np.squeeze(approx_polygon, axis=1) + xyxy = polygon_to_xyxy(polygon=approx_polygon) + next_object = object_to_pascal_voc( + xyxy=xyxy, name=name, polygon=polygon + ) + annotation.append(next_object) + else: + next_object = object_to_pascal_voc(xyxy=xyxy, name=name) + annotation.append(next_object) # Generate XML string xml_string = parseString(tostring(annotation)).toprettyxml(indent=" ") return xml_string - - -# def dataset_to_pascal_voc( -# dataset: Dataset, -# images_directory_path: Optional[str], -# annotations_directory_path: Optional[str] -# ) -> None: -# # Ensure the output directories exist -# if images_directory_path and not os.path.exists(images_directory_path): -# os.makedirs(images_directory_path) -# -# if annotations_directory_path and not os.path.exists(annotations_directory_path): -# os.makedirs(annotations_directory_path) -# -# # Iterate over the images and their corresponding detections -# for image_path, image_annotations in dataset.annotations.items(): -# # Retrieve the image from the dataset -# image = dataset.images[image_path] -# -# # Create the root element for the XML -# annotation = ET.Element("annotation") -# -# # Add folder, filename, and path elements -# folder = ET.SubElement(annotation, "folder") -# folder.text = "" -# filename = ET.SubElement(annotation, "filename") -# filename.text = os.path.basename(image_path) -# path = ET.SubElement(annotation, "path") -# path.text = os.path.basename(image_path) -# -# # Add image size information using the image shape -# size = ET.SubElement(annotation, "size") -# width = ET.SubElement(size, "width") -# width.text = str(image.shape[1]) # Use image width -# height = ET.SubElement(size, "height") -# height.text = str(image.shape[0]) # Use image height -# depth = ET.SubElement(size, "depth") -# depth.text = str(image.shape[2]) # Use image depth (number of channels) -# -# # Iterate over the bounding boxes and their attributes -# for i in range(image_annotations.xyxy.shape[0]): -# object_element = ET.SubElement(annotation, "object") -# -# name = ET.SubElement(object_element, "name") -# name.text = dataset.classes[image_annotations.class_id[i]] -# -# pose = ET.SubElement(object_element, "pose") -# pose.text = "Unspecified" -# -# truncated = ET.SubElement(object_element, "truncated") -# truncated.text = "0" -# -# difficult = ET.SubElement(object_element, "difficult") -# difficult.text = "0" -# -# # Add bounding box information -# bndbox = ET.SubElement(object_element, "bndbox") -# xmin = ET.SubElement(bndbox, "xmin") -# xmin.text = str(image_annotations.xyxy[i, 0]) -# ymin = ET.SubElement(bndbox, "ymin") -# ymin.text = str(image_annotations.xyxy[i, 1]) -# xmax = ET.SubElement(bndbox, "xmax") -# xmax.text = str(image_annotations.xyxy[i, 2]) -# ymax = ET.SubElement(bndbox, "ymax") -# ymax.text = str(image_annotations.xyxy[i, 3]) -# -# # Save the XML to the annotations directory -# if annotations_directory_path: -# xml_file_path = os.path.join(annotations_directory_path, -# os.path.splitext(os.path.basename(image_path))[0] + ".xml") -# tree = ET.ElementTree(annotation) -# tree.write(xml_file_path, encoding="utf-8", xml_declaration=True) -# -# # Save the image to the images directory -# if images_directory_path: -# img_file_path = os.path.join(images_directory_path, os.path.basename(image_path)) -# cv2.imwrite(img_file_path, dataset.images[image_path]) \ No newline at end of file diff --git a/supervision/detection/core.py b/supervision/detection/core.py index df85fed0..e51ebc5e 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -50,20 +50,19 @@ def _validate_tracker_id(tracker_id: Any, n: int) -> None: @dataclass class Detections: """ - Dataclass containing information about the detections in a video frame. - + Data class containing information about the detections in a video frame. Attributes: xyxy (np.ndarray): An array of shape `(n, 4)` containing the bounding boxes coordinates in format `[x1, y1, x2, y2]` - mask (Optional[np.ndarray]): An array of shape `(n, W, H)` containing the segmentation masks. - class_id (Optional[np.ndarray]): An array of shape `(n,)` containing the class ids of the detections. + mask: (Optional[np.ndarray]): An array of shape `(n, W, H)` containing the segmentation masks. confidence (Optional[np.ndarray]): An array of shape `(n,)` containing the confidence scores of the detections. + class_id (Optional[np.ndarray]): An array of shape `(n,)` containing the class ids of the detections. tracker_id (Optional[np.ndarray]): An array of shape `(n,)` containing the tracker ids of the detections. """ xyxy: np.ndarray mask: np.Optional[np.ndarray] = None - class_id: Optional[np.ndarray] = None confidence: Optional[np.ndarray] = None + class_id: Optional[np.ndarray] = None tracker_id: Optional[np.ndarray] = None def __post_init__(self): diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index b2d6c5c3..fa5adf10 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -1,9 +1,8 @@ -from typing import Tuple, List, Optional +from typing import List, Optional, Tuple import cv2 import numpy as np - MIN_POLYGON_POINT_COUNT = 3 @@ -152,16 +151,21 @@ def mask_to_xyxy(masks: np.ndarray) -> np.ndarray: def mask_to_polygons(mask: np.ndarray) -> List[np.ndarray]: - contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) + contours, _ = cv2.findContours( + mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE + ) return [ np.squeeze(contour, axis=1) - for contour - in contours + for contour in contours if contour.shape[0] >= MIN_POLYGON_POINT_COUNT ] -def filter_polygons_by_area(polygons: List[np.ndarray], min_area: Optional[float] = None, max_area: Optional[float] = None) -> List[np.ndarray]: +def filter_polygons_by_area( + polygons: List[np.ndarray], + min_area: Optional[float] = None, + max_area: Optional[float] = None, +) -> List[np.ndarray]: """ Filters a list of polygons based on their area. @@ -178,16 +182,12 @@ def filter_polygons_by_area(polygons: List[np.ndarray], min_area: Optional[float """ if min_area is None and max_area is None: return polygons - ares = [ - cv2.contourArea(polygon) - for polygon - in polygons - ] + ares = [cv2.contourArea(polygon) for polygon in polygons] return [ polygon - for polygon, area - in zip(polygons, ares) - if (min_area is None or area>= min_area) and (max_area is None or area<= max_area) + for polygon, area in zip(polygons, ares) + if (min_area is None or area >= min_area) + and (max_area is None or area <= max_area) ] @@ -204,4 +204,4 @@ def polygon_to_xyxy(polygon: np.ndarray) -> np.ndarray: """ x_min, y_min = np.min(polygon, axis=0) x_max, y_max = np.max(polygon, axis=0) - return np.array([x_min, y_min, x_max, y_max]) \ No newline at end of file + return np.array([x_min, y_min, x_max, y_max]) diff --git a/supervision/file.py b/supervision/file.py new file mode 100644 index 00000000..7e2f5350 --- /dev/null +++ b/supervision/file.py @@ -0,0 +1,3 @@ +def write_text_to_file(content: str, output_path: str) -> None: + with open(output_path, "w") as file: + file.write(content)