File size: 2,846 Bytes
a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 bf78bd5 a3d3018 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import os
import json
from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split, Features, Value, Sequence, Image as HFImage
class LineGraphicsDataset(GeneratorBasedBuilder):
def _info(self):
return DatasetInfo(
features=Features({
"image_name": Value("string"),
"image": HFImage(),
"width": Value("int32"),
"height": Value("int32"),
"instances": Sequence({
"category_id": Value("int32"),
"mask": Sequence(Sequence(Value("float32"))) # List of polygons (each polygon = list of floats)
})
}),
description="Line Graphics Dataset with polygon instance masks in COCO format.",
)
def _split_generators(self, dl_manager):
data_dir = dl_manager.download_and_extract(self.config.data_dir or ".")
return [
SplitGenerator(
name=Split.TRAIN,
gen_kwargs={"split_dir": os.path.join(data_dir, "train")},
),
SplitGenerator(
name=Split.VALIDATION,
gen_kwargs={"split_dir": os.path.join(data_dir, "val")},
),
SplitGenerator(
name=Split.TEST,
gen_kwargs={"split_dir": os.path.join(data_dir, "test")},
),
]
def _generate_examples(self, split_dir):
# Load annotations
annotation_file = os.path.join(split_dir, "annotations.json")
with open(annotation_file, "r") as f:
coco = json.load(f)
# Map image_id to metadata
image_id_to_info = {img["id"]: img for img in coco["images"]}
# Group annotations by image
from collections import defaultdict
anns_by_image = defaultdict(list)
for ann in coco["annotations"]:
anns_by_image[ann["image_id"]].append(ann)
# Generate examples
for image_id, image_info in image_id_to_info.items():
file_name = image_info["file_name"]
image_path = os.path.join(split_dir, "images", file_name)
instances = []
for ann in anns_by_image[image_id]:
# Each mask is a list of polygons
segmentation = ann["segmentation"]
if not isinstance(segmentation, list):
continue # skip if malformed
instances.append({
"category_id": ann["category_id"],
"mask": segmentation
})
yield file_name, {
"image_name": file_name,
"image": image_path,
"width": image_info["width"],
"height": image_info["height"],
"instances": instances
}
|