Datasets:
Create utm_dataset.py
Browse files- utm_dataset.py +51 -0
utm_dataset.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from datasets import DatasetInfo, Features, ClassLabel, Image, GeneratorBasedBuilder, Split
|
| 3 |
+
|
| 4 |
+
class UTM_Dataset(GeneratorBasedBuilder):
|
| 5 |
+
"""UTM Dataset organized in train/validation/test splits with subfolders as classes."""
|
| 6 |
+
|
| 7 |
+
VERSION = "1.0.0"
|
| 8 |
+
|
| 9 |
+
def _info(self):
|
| 10 |
+
"""Returns the dataset metadata, features, and supervised keys."""
|
| 11 |
+
return DatasetInfo(
|
| 12 |
+
description="UTM Dataset organized in train/validation/test with subfolders as classes",
|
| 13 |
+
features=Features(
|
| 14 |
+
{
|
| 15 |
+
"image": Image(), # images
|
| 16 |
+
"label": ClassLabel(names=self._get_class_names()) # labels from subfolder names
|
| 17 |
+
}
|
| 18 |
+
),
|
| 19 |
+
supervised_keys=("image", "label"),
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def _get_class_names(self):
|
| 23 |
+
"""Get class names from the train folder subdirectories."""
|
| 24 |
+
train_dir = os.path.join(self.config.data_dir, "train")
|
| 25 |
+
return sorted(
|
| 26 |
+
[d for d in os.listdir(train_dir) if os.path.isdir(os.path.join(train_dir, d))]
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def _split_generators(self, dl_manager):
|
| 30 |
+
"""Defines the splits and their corresponding folders."""
|
| 31 |
+
data_dir = self.config.data_dir
|
| 32 |
+
|
| 33 |
+
return [
|
| 34 |
+
Split.TRAIN: self._generate_examples(os.path.join(data_dir, "train")),
|
| 35 |
+
Split.VALIDATION: self._generate_examples(os.path.join(data_dir, "validation")),
|
| 36 |
+
Split.TEST: self._generate_examples(os.path.join(data_dir, "test")),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
def _generate_examples(self, path):
|
| 40 |
+
"""Yields (id, example) tuples for each image in the folder."""
|
| 41 |
+
for class_name in sorted(os.listdir(path)):
|
| 42 |
+
class_dir = os.path.join(path, class_name)
|
| 43 |
+
if not os.path.isdir(class_dir):
|
| 44 |
+
continue
|
| 45 |
+
for fname in sorted(os.listdir(class_dir)):
|
| 46 |
+
if fname.lower().endswith((".png", ".jpg", ".jpeg")):
|
| 47 |
+
# Unique id for each example
|
| 48 |
+
yield f"{class_name}_{fname}", {
|
| 49 |
+
"image": os.path.join(class_dir, fname),
|
| 50 |
+
"label": class_name,
|
| 51 |
+
}
|