|
| 1 | +from glob import glob |
| 2 | +import os |
| 3 | +from typing import Tuple, List, Optional |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +from PIL import Image |
| 7 | + |
| 8 | +from detectionmetrics.datasets.detection import ImageDetectionDataset |
| 9 | +from detectionmetrics.utils import io as uio |
| 10 | + |
| 11 | + |
| 12 | +def build_dataset( |
| 13 | + dataset_fname: str, dataset_dir: Optional[str] = None, im_ext: str = "jpg" |
| 14 | +) -> Tuple[pd.DataFrame, dict]: |
| 15 | + """Build dataset and ontology dictionaries from YOLO dataset structure |
| 16 | +
|
| 17 | + :param dataset_fname: Path to the YAML dataset configuration file |
| 18 | + :type dataset_fname: str |
| 19 | + :param dataset_dir: Path to the directory containing images and annotations. If not provided, it will be inferred from the dataset file |
| 20 | + :type dataset_dir: Optional[str] |
| 21 | + :param im_ext: Image file extension (default is "jpg") |
| 22 | + :type im_ext: str |
| 23 | + :return: Dataset DataFrame and ontology dictionary |
| 24 | + :rtype: Tuple[pd.DataFrame, dict] |
| 25 | + """ |
| 26 | + # Read dataset configuration from YAML file |
| 27 | + assert os.path.isfile(dataset_fname), f"Dataset file not found: {dataset_fname}" |
| 28 | + dataset_info = uio.read_yaml(dataset_fname) |
| 29 | + |
| 30 | + # Check that image directory exists |
| 31 | + if dataset_dir is None: |
| 32 | + dataset_dir = dataset_info["path"] |
| 33 | + assert os.path.isdir(dataset_dir), f"Dataset directory not found: {dataset_dir}" |
| 34 | + |
| 35 | + # Build ontology from dataset configuration |
| 36 | + ontology = {} |
| 37 | + for idx, name in dataset_info["names"].items(): |
| 38 | + ontology[name] = { |
| 39 | + "idx": idx, |
| 40 | + "rgb": [0, 0, 0], # Placeholder; YAML doesn't define RGB colors |
| 41 | + } |
| 42 | + |
| 43 | + # Build dataset DataFrame |
| 44 | + rows = [] |
| 45 | + for split in ["train", "val", "test"]: |
| 46 | + if split in dataset_info: |
| 47 | + images_dir = os.path.join(dataset_dir, dataset_info[split]) |
| 48 | + labels_dir = os.path.join( |
| 49 | + dataset_dir, dataset_info[split].replace("images", "labels") |
| 50 | + ) |
| 51 | + for label_fname in glob(os.path.join(labels_dir, "*.txt")): |
| 52 | + label_basename = os.path.basename(label_fname) |
| 53 | + image_basename = label_basename.replace(".txt", f".{im_ext}") |
| 54 | + image_fname = os.path.join(images_dir, image_basename) |
| 55 | + os.path.basename(image_fname) |
| 56 | + if not os.path.isfile(image_fname): |
| 57 | + continue |
| 58 | + |
| 59 | + rows.append( |
| 60 | + { |
| 61 | + "image": os.path.join("images", split, image_basename), |
| 62 | + "annotation": os.path.join("labels", split, label_basename), |
| 63 | + "split": split, |
| 64 | + } |
| 65 | + ) |
| 66 | + |
| 67 | + dataset = pd.DataFrame(rows) |
| 68 | + dataset.attrs = {"ontology": ontology} |
| 69 | + |
| 70 | + return dataset, ontology, dataset_dir |
| 71 | + |
| 72 | + |
| 73 | +class YOLODataset(ImageDetectionDataset): |
| 74 | + """ |
| 75 | + Specific class for YOLO-styled object detection datasets. |
| 76 | +
|
| 77 | + :param dataset_fname: Path to the YAML dataset configuration file |
| 78 | + :type dataset_fname: str |
| 79 | + :param dataset_dir: Path to the directory containing images and annotations. If not provided, it will be inferred from the dataset file |
| 80 | + :type dataset_dir: Optional[str] |
| 81 | + :param im_ext: Image file extension (default is "jpg") |
| 82 | + :type im_ext: str |
| 83 | + """ |
| 84 | + |
| 85 | + def __init__( |
| 86 | + self, dataset_fname: str, dataset_dir: Optional[str], im_ext: str = "jpg" |
| 87 | + ): |
| 88 | + # Build dataset using the same COCO object |
| 89 | + dataset, ontology, dataset_dir = build_dataset( |
| 90 | + dataset_fname, dataset_dir, im_ext |
| 91 | + ) |
| 92 | + |
| 93 | + self.im_ext = im_ext |
| 94 | + super().__init__(dataset=dataset, dataset_dir=dataset_dir, ontology=ontology) |
| 95 | + |
| 96 | + def read_annotation( |
| 97 | + self, fname: str, image_size: Optional[Tuple[int, int]] = None |
| 98 | + ) -> Tuple[List[List[float]], List[int], List[int]]: |
| 99 | + """Return bounding boxes, and category indices for a given image ID. |
| 100 | +
|
| 101 | + :param fname: Annotation path |
| 102 | + :type fname: str |
| 103 | + :param image_size: Corresponding image size in (w, h) format for converting relative bbox size to absolute. If not provided, we will assume image path |
| 104 | + :type image_size: Optional[Tuple[int, int]] |
| 105 | + :return: Tuple of (boxes, category_indices) |
| 106 | + """ |
| 107 | + label = uio.read_txt(fname) |
| 108 | + image_fname = fname.replace(".txt", f".{self.im_ext}") |
| 109 | + image_fname = image_fname.replace("labels", "images") |
| 110 | + if image_size is None: |
| 111 | + image_size = Image.open(image_fname).size |
| 112 | + |
| 113 | + boxes = [] |
| 114 | + category_indices = [] |
| 115 | + |
| 116 | + im_w, im_h = image_size |
| 117 | + for row in label: |
| 118 | + category_idx, xc, yc, w, h = map(float, row.split()) |
| 119 | + category_indices.append(int(category_idx)) |
| 120 | + |
| 121 | + abs_xc = xc * im_w |
| 122 | + abs_yc = yc * im_h |
| 123 | + abs_w = w * im_w |
| 124 | + abs_h = h * im_h |
| 125 | + |
| 126 | + boxes.append( |
| 127 | + [ |
| 128 | + abs_xc - abs_w / 2, |
| 129 | + abs_yc - abs_h / 2, |
| 130 | + abs_xc + abs_w / 2, |
| 131 | + abs_yc + abs_h / 2, |
| 132 | + ] |
| 133 | + ) |
| 134 | + |
| 135 | + return boxes, category_indices |
0 commit comments