Create dataset.py
Browse files- dataset.py +72 -0
dataset.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split, Features, Value, Sequence, Image as HFImage
|
4 |
+
|
5 |
+
|
6 |
+
class LineGraphicsDataset(GeneratorBasedBuilder):
|
7 |
+
def _info(self):
|
8 |
+
return DatasetInfo(
|
9 |
+
features=Features({
|
10 |
+
"image_name": Value("string"),
|
11 |
+
"image": HFImage(),
|
12 |
+
"width": Value("int32"),
|
13 |
+
"height": Value("int32"),
|
14 |
+
"instances": Sequence({
|
15 |
+
"category_id": Value("int32"),
|
16 |
+
"mask": Sequence(Sequence(Value("float32"))) # list of polygon(s)
|
17 |
+
})
|
18 |
+
}),
|
19 |
+
description="Line Graphics Dataset with polygon instance masks in COCO format.",
|
20 |
+
)
|
21 |
+
|
22 |
+
def _split_generators(self, dl_manager):
|
23 |
+
# Automatically download and extract the repo contents
|
24 |
+
data_dir = dl_manager.download_and_extract(self.config.data_dir or ".")
|
25 |
+
|
26 |
+
return [
|
27 |
+
SplitGenerator(
|
28 |
+
name=Split.TRAIN,
|
29 |
+
gen_kwargs={"split_dir": os.path.join(data_dir, "train")}
|
30 |
+
),
|
31 |
+
SplitGenerator(
|
32 |
+
name=Split.VALIDATION,
|
33 |
+
gen_kwargs={"split_dir": os.path.join(data_dir, "val")}
|
34 |
+
),
|
35 |
+
SplitGenerator(
|
36 |
+
name=Split.TEST,
|
37 |
+
gen_kwargs={"split_dir": os.path.join(data_dir, "test")}
|
38 |
+
),
|
39 |
+
]
|
40 |
+
|
41 |
+
def _generate_examples(self, split_dir):
|
42 |
+
# Load annotations.json
|
43 |
+
ann_path = os.path.join(split_dir, "annotations.json")
|
44 |
+
with open(ann_path, "r") as f:
|
45 |
+
coco = json.load(f)
|
46 |
+
|
47 |
+
image_id_to_info = {img["id"]: img for img in coco["images"]}
|
48 |
+
|
49 |
+
from collections import defaultdict
|
50 |
+
anns_by_image = defaultdict(list)
|
51 |
+
for ann in coco["annotations"]:
|
52 |
+
anns_by_image[ann["image_id"]].append(ann)
|
53 |
+
|
54 |
+
for img_id, info in image_id_to_info.items():
|
55 |
+
image_path = os.path.join(split_dir, "images", info["file_name"])
|
56 |
+
width = info["width"]
|
57 |
+
height = info["height"]
|
58 |
+
|
59 |
+
instances = []
|
60 |
+
for ann in anns_by_image[img_id]:
|
61 |
+
instances.append({
|
62 |
+
"category_id": ann["category_id"],
|
63 |
+
"mask": ann["segmentation"] # List of polygons
|
64 |
+
})
|
65 |
+
|
66 |
+
yield info["file_name"], {
|
67 |
+
"image_name": info["file_name"],
|
68 |
+
"image": image_path,
|
69 |
+
"width": width,
|
70 |
+
"height": height,
|
71 |
+
"instances": instances
|
72 |
+
}
|