visible-watermark-pita / watermarkdataset.py
bastienp's picture
feat: update script dataset and include data from coco
032c4ac
raw
history blame
2.53 kB
import os
from glob import glob
from PIL import Image
import datasets
_DESCRIPTION = """\
Watermark Dataset
"""
_VERSION = datasets.Version("1.0.0")
_REPO = "data"
_URLS = {"train": f"{_REPO}/train.zip", "valid": f"{_REPO}/valid.zip"}
_CATEGORIES = ["watermark"]
class WatermarkPita(datasets.GeneratorBasedBuilder):
"""Watermark Dataset"""
VERSION = datasets.Version("1.0.0")
def _info(self):
return datasets.DatasetInfo(
features=datasets.Features(
{
"image": datasets.Image(),
"objects": datasets.Sequence({
"label": datasets.ClassLabel(names=_CATEGORIES),
"bbox": datasets.Sequence(datasets.Value("int32"), length=4)
}),
}
),
description=_DESCRIPTION,
)
def _split_generators(self, dl_manager):
data_dir = dl_manager.download_and_extract(_URLS)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"split": "train", "data_dir": data_dir["train"]},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"split": "valid", "data_dir": data_dir["valid"]},
),
]
def _generate_examples(self, split, data_dir):
image_dir = os.path.join(data_dir, "images")
label_dir = os.path.join(data_dir, "labels")
image_paths = sorted(glob(image_dir + "/*/*.png"))
label_paths = sorted(glob(label_dir + "/*/*.txt"))
for idx, (image_path, label_path) in enumerate(zip(image_paths, label_paths)):
im = Image.open(image_path)
width, height = im.size
with open(label_path, "r") as f:
lines = f.readlines()
objects = []
for line in lines:
line = line.strip().split()
bbox_class = int(line[0])
bbox_top_left = int(float(line[1]) * width)
bbox_top_right = int(float(line[2]) * height)
bbox_bottom_left = int(float(line[3]) * width)
bbox_bottom_right = int(float(line[4]) * height)
objects.append({
"label": bbox_class,
"bbox": [bbox_top_left, bbox_top_right, bbox_bottom_left, bbox_bottom_right]
})
yield idx, {"image": image_path, "objects": objects}