Egg-Detection / dataset.py
afshin-dini's picture
Update the script
b8ca326
import os
import numpy as np
from PIL import Image
from datasets import Dataset, DatasetDict, GeneratorBasedBuilder, SplitGenerator, DatasetInfo, Image, Features, Image, Value, Sequence, Split
class YoloDataset(GeneratorBasedBuilder):
def _info(self):
return DatasetInfo(
description="YOLO-style dataset",
features=Features({
'image': Image(),
'label': Sequence({
'class_id': Value('int32'),
'x_center': Value('float32'),
'y_center': Value('float32'),
'width': Value('float32'),
'height': Value('float32'),
}),
}),
supervised_keys=None,
homepage="https://huggingface.co/datasets/your_username/your_dataset_name",
license="MIT",
)
def _split_generators(self, dl_manager):
data_dir = os.path.join(self.config.data_dir, "data")
return [
SplitGenerator(
name=Split.TRAIN,
gen_kwargs={"images_path": os.path.join(data_dir, "images/train"),
"labels_path": os.path.join(data_dir, "labels/train")}
),
SplitGenerator(
name=Split.VALIDATION,
gen_kwargs={"images_path": os.path.join(data_dir, "images/val"),
"labels_path": os.path.join(data_dir, "labels/val")}
),
]
def _generate_examples(self, images_path, labels_path):
"""Yields examples."""
for image_file in os.listdir(images_path):
if not image_file.endswith((".jpg", ".png", ".jpeg")):
continue # Skip non-image files
image_path = os.path.join(images_path, image_file)
label_file = os.path.splitext(image_file)[0] + ".txt"
label_path = os.path.join(labels_path, label_file)
objects = []
if os.path.exists(label_path):
with open(label_path, "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split()
if len(parts) == 5:
class_id, x_center, y_center, width, height = map(float, parts)
objects.append({
"class_id": int(class_id),
"x_center": x_center,
"y_center": y_center,
"width": width,
"height": height
})
yield image_file, {"image": image_path, "label": objects}