|
|
import os |
|
|
from datasets import DatasetInfo, GeneratorBasedBuilder, SplitGenerator, Split, Value, Features |
|
|
|
|
|
class MyDataset(GeneratorBasedBuilder): |
|
|
def _info(self): |
|
|
return DatasetInfo( |
|
|
description="Custom dataset with images and labels in separate folders", |
|
|
features=Features({ |
|
|
"image": Value("string"), |
|
|
"label": Value("string") |
|
|
}), |
|
|
) |
|
|
|
|
|
def _split_generators(self, dl_manager): |
|
|
data_dir = self.config.data_dir or "" |
|
|
return [ |
|
|
SplitGenerator(name=Split.TRAIN, gen_kwargs={"split_dir": os.path.join(data_dir, "train")}), |
|
|
SplitGenerator(name=Split.TEST, gen_kwargs={"split_dir": os.path.join(data_dir, "test")}), |
|
|
] |
|
|
|
|
|
def _generate_examples(self, split_dir): |
|
|
image_dir = os.path.join(split_dir, "images") |
|
|
label_dir = os.path.join(split_dir, "labels") |
|
|
|
|
|
idx = 0 |
|
|
for image_name in sorted(os.listdir(image_dir)): |
|
|
if not image_name.lower().endswith((".jpg", ".png", ".jpeg")): |
|
|
continue |
|
|
|
|
|
image_path = os.path.join(image_dir, image_name) |
|
|
label_path = os.path.join(label_dir, os.path.splitext(image_name)[0] + ".txt") |
|
|
|
|
|
if not os.path.exists(label_path): |
|
|
continue |
|
|
|
|
|
with open(label_path, "r") as f: |
|
|
label = f.read().strip() |
|
|
|
|
|
yield idx, { |
|
|
"image": image_path, |
|
|
"label": label, |
|
|
} |
|
|
idx += 1 |