Commit
•
5664e18
1
Parent(s):
1b00d9c
add script
Browse files- README.md +246 -0
- coco_detection_dataset_script.py +325 -0
README.md
CHANGED
@@ -1,3 +1,249 @@
|
|
1 |
---
|
2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
license: apache-2.0
|
3 |
+
task_categories:
|
4 |
+
- object-detection
|
5 |
+
tags:
|
6 |
+
- COCO
|
7 |
+
- Detection
|
8 |
+
- '2017'
|
9 |
+
pretty_name: COCO detection dataset script
|
10 |
+
size_categories:
|
11 |
+
- 100K<n<1M
|
12 |
+
dataset_info:
|
13 |
+
config_name: '2017'
|
14 |
+
features:
|
15 |
+
- name: id
|
16 |
+
dtype: int64
|
17 |
+
- name: objects
|
18 |
+
struct:
|
19 |
+
- name: bbox_id
|
20 |
+
sequence: int64
|
21 |
+
- name: category_id
|
22 |
+
sequence:
|
23 |
+
class_label:
|
24 |
+
names:
|
25 |
+
'0': N/A
|
26 |
+
'1': person
|
27 |
+
'2': bicycle
|
28 |
+
'3': car
|
29 |
+
'4': motorcycle
|
30 |
+
'5': airplane
|
31 |
+
'6': bus
|
32 |
+
'7': train
|
33 |
+
'8': truck
|
34 |
+
'9': boat
|
35 |
+
'10': traffic light
|
36 |
+
'11': fire hydrant
|
37 |
+
'12': street sign
|
38 |
+
'13': stop sign
|
39 |
+
'14': parking meter
|
40 |
+
'15': bench
|
41 |
+
'16': bird
|
42 |
+
'17': cat
|
43 |
+
'18': dog
|
44 |
+
'19': horse
|
45 |
+
'20': sheep
|
46 |
+
'21': cow
|
47 |
+
'22': elephant
|
48 |
+
'23': bear
|
49 |
+
'24': zebra
|
50 |
+
'25': giraffe
|
51 |
+
'26': hat
|
52 |
+
'27': backpack
|
53 |
+
'28': umbrella
|
54 |
+
'29': shoe
|
55 |
+
'30': eye glasses
|
56 |
+
'31': handbag
|
57 |
+
'32': tie
|
58 |
+
'33': suitcase
|
59 |
+
'34': frisbee
|
60 |
+
'35': skis
|
61 |
+
'36': snowboard
|
62 |
+
'37': sports ball
|
63 |
+
'38': kite
|
64 |
+
'39': baseball bat
|
65 |
+
'40': baseball glove
|
66 |
+
'41': skateboard
|
67 |
+
'42': surfboard
|
68 |
+
'43': tennis racket
|
69 |
+
'44': bottle
|
70 |
+
'45': plate
|
71 |
+
'46': wine glass
|
72 |
+
'47': cup
|
73 |
+
'48': fork
|
74 |
+
'49': knife
|
75 |
+
'50': spoon
|
76 |
+
'51': bowl
|
77 |
+
'52': banana
|
78 |
+
'53': apple
|
79 |
+
'54': sandwich
|
80 |
+
'55': orange
|
81 |
+
'56': broccoli
|
82 |
+
'57': carrot
|
83 |
+
'58': hot dog
|
84 |
+
'59': pizza
|
85 |
+
'60': donut
|
86 |
+
'61': cake
|
87 |
+
'62': chair
|
88 |
+
'63': couch
|
89 |
+
'64': potted plant
|
90 |
+
'65': bed
|
91 |
+
'66': mirror
|
92 |
+
'67': dining table
|
93 |
+
'68': window
|
94 |
+
'69': desk
|
95 |
+
'70': toilet
|
96 |
+
'71': door
|
97 |
+
'72': tv
|
98 |
+
'73': laptop
|
99 |
+
'74': mouse
|
100 |
+
'75': remote
|
101 |
+
'76': keyboard
|
102 |
+
'77': cell phone
|
103 |
+
'78': microwave
|
104 |
+
'79': oven
|
105 |
+
'80': toaster
|
106 |
+
'81': sink
|
107 |
+
'82': refrigerator
|
108 |
+
'83': blender
|
109 |
+
'84': book
|
110 |
+
'85': clock
|
111 |
+
'86': vase
|
112 |
+
'87': scissors
|
113 |
+
'88': teddy bear
|
114 |
+
'89': hair drier
|
115 |
+
'90': toothbrush
|
116 |
+
- name: bbox
|
117 |
+
sequence:
|
118 |
+
sequence: float64
|
119 |
+
length: 4
|
120 |
+
- name: iscrowd
|
121 |
+
sequence: int64
|
122 |
+
- name: area
|
123 |
+
sequence: float64
|
124 |
+
- name: height
|
125 |
+
dtype: int64
|
126 |
+
- name: width
|
127 |
+
dtype: int64
|
128 |
+
- name: file_name
|
129 |
+
dtype: string
|
130 |
+
- name: coco_url
|
131 |
+
dtype: string
|
132 |
+
- name: image_path
|
133 |
+
dtype: string
|
134 |
+
splits:
|
135 |
+
- name: train
|
136 |
+
num_bytes: 87231216
|
137 |
+
num_examples: 117266
|
138 |
+
- name: validation
|
139 |
+
num_bytes: 3692192
|
140 |
+
num_examples: 4952
|
141 |
+
download_size: 20405354669
|
142 |
+
dataset_size: 90923408
|
143 |
---
|
144 |
+
## Usage
|
145 |
+
For using the COCO dataset (2017), you need to download it manually first:
|
146 |
+
```bash
|
147 |
+
wget http://images.cocodataset.org/zips/train2017.zip
|
148 |
+
wget http://images.cocodataset.org/zips/val2017.zip
|
149 |
+
wget http://images.cocodataset.org/annotations/annotations_trainval2017.zip
|
150 |
+
```
|
151 |
+
|
152 |
+
Then to load the dataset:
|
153 |
+
```python
|
154 |
+
COCO_DIR = ...(path to the downloaded dataset directory)...
|
155 |
+
ds = datasets.load_dataset(
|
156 |
+
"yonigozlan/coco_2017_detection_script",
|
157 |
+
"2017",
|
158 |
+
data_dir=COCO_DIR,
|
159 |
+
trust_remote_code=True,
|
160 |
+
)
|
161 |
+
```
|
162 |
+
|
163 |
+
## Benchmarking
|
164 |
+
Here is an example of how to benchmark a 🤗 Transformers object detection model on the validation data of the COCO dataset:
|
165 |
+
|
166 |
+
```python
|
167 |
+
import datasets
|
168 |
+
import torch
|
169 |
+
from PIL import Image
|
170 |
+
from torch.utils.data import DataLoader
|
171 |
+
from torchmetrics.detection.mean_ap import MeanAveragePrecision
|
172 |
+
from tqdm import tqdm
|
173 |
+
|
174 |
+
from transformers import AutoImageProcessor, AutoModelForObjectDetection
|
175 |
+
|
176 |
+
# prepare data
|
177 |
+
COCO_DIR = ...(path to the downloaded dataset directory)...
|
178 |
+
ds = datasets.load_dataset(
|
179 |
+
"yonigozlan/coco_2017_detection_script",
|
180 |
+
"2017",
|
181 |
+
data_dir=COCO_DIR,
|
182 |
+
trust_remote_code=True,
|
183 |
+
)
|
184 |
+
val_data = ds["validation"]
|
185 |
+
categories = val_data.features["objects"]["category_id"].feature.names
|
186 |
+
id2label = {index: x for index, x in enumerate(categories, start=0)}
|
187 |
+
label2id = {v: k for k, v in id2label.items()}
|
188 |
+
checkpoint = "facebook/detr-resnet-50"
|
189 |
+
|
190 |
+
# load model and processor
|
191 |
+
model = AutoModelForObjectDetection.from_pretrained(
|
192 |
+
checkpoint, torch_dtype=torch.float16
|
193 |
+
).to("cuda")
|
194 |
+
id2label_model = model.config.id2label
|
195 |
+
processor = AutoImageProcessor.from_pretrained(checkpoint)
|
196 |
+
|
197 |
+
|
198 |
+
def collate_fn(batch):
|
199 |
+
data = {}
|
200 |
+
images = [Image.open(x["image_path"]).convert("RGB") for x in batch]
|
201 |
+
data["images"] = images
|
202 |
+
annotations = []
|
203 |
+
for x in batch:
|
204 |
+
boxes = x["objects"]["bbox"]
|
205 |
+
# convert to xyxy format
|
206 |
+
boxes = [[box[0], box[1], box[0] + box[2], box[1] + box[3]] for box in boxes]
|
207 |
+
labels = x["objects"]["category_id"]
|
208 |
+
boxes = torch.tensor(boxes)
|
209 |
+
labels = torch.tensor(labels)
|
210 |
+
annotations.append({"boxes": boxes, "labels": labels})
|
211 |
+
data["original_size"] = [(x["height"], x["width"]) for x in batch]
|
212 |
+
data["annotations"] = annotations
|
213 |
+
return data
|
214 |
+
|
215 |
+
|
216 |
+
# prepare dataloader
|
217 |
+
dataloader = DataLoader(val_data, batch_size=8, collate_fn=collate_fn)
|
218 |
+
|
219 |
+
# prepare metric
|
220 |
+
metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True)
|
221 |
+
|
222 |
+
# evaluation loop
|
223 |
+
for i, batch in tqdm(enumerate(dataloader), total=len(dataloader)):
|
224 |
+
inputs = (
|
225 |
+
processor(batch["images"], return_tensors="pt").to("cuda").to(torch.float16)
|
226 |
+
)
|
227 |
+
with torch.no_grad():
|
228 |
+
outputs = model(**inputs)
|
229 |
+
target_sizes = torch.tensor([x for x in batch["original_size"]]).to("cuda")
|
230 |
+
results = processor.post_process_object_detection(
|
231 |
+
outputs, threshold=0.0, target_sizes=target_sizes
|
232 |
+
)
|
233 |
+
|
234 |
+
# convert predicted label id to dataset label id
|
235 |
+
if len(id2label_model) != len(id2label):
|
236 |
+
for result in results:
|
237 |
+
result["labels"] = torch.tensor(
|
238 |
+
[label2id.get(id2label_model[x.item()], 0) for x in result["labels"]]
|
239 |
+
)
|
240 |
+
# put results back to cpu
|
241 |
+
for result in results:
|
242 |
+
for k, v in result.items():
|
243 |
+
if isinstance(v, torch.Tensor):
|
244 |
+
result[k] = v.to("cpu")
|
245 |
+
metric.update(results, batch["annotations"])
|
246 |
+
|
247 |
+
metrics = metric.compute()
|
248 |
+
print(metrics)
|
249 |
+
```
|
coco_detection_dataset_script.py
ADDED
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
|
4 |
+
import datasets
|
5 |
+
|
6 |
+
|
7 |
+
class COCOBuilderConfig(datasets.BuilderConfig):
|
8 |
+
def __init__(self, name, splits, **kwargs):
|
9 |
+
super().__init__(name, **kwargs)
|
10 |
+
self.splits = splits
|
11 |
+
|
12 |
+
|
13 |
+
# Add BibTeX citation
|
14 |
+
# Find for instance the citation on arxiv or on the dataset repo/website
|
15 |
+
_CITATION = """\
|
16 |
+
@article{DBLP:journals/corr/LinMBHPRDZ14,
|
17 |
+
author = {Tsung{-}Yi Lin and
|
18 |
+
Michael Maire and
|
19 |
+
Serge J. Belongie and
|
20 |
+
Lubomir D. Bourdev and
|
21 |
+
Ross B. Girshick and
|
22 |
+
James Hays and
|
23 |
+
Pietro Perona and
|
24 |
+
Deva Ramanan and
|
25 |
+
Piotr Doll{'{a} }r and
|
26 |
+
C. Lawrence Zitnick},
|
27 |
+
title = {Microsoft {COCO:} Common Objects in Context},
|
28 |
+
journal = {CoRR},
|
29 |
+
volume = {abs/1405.0312},
|
30 |
+
year = {2014},
|
31 |
+
url = {http://arxiv.org/abs/1405.0312},
|
32 |
+
archivePrefix = {arXiv},
|
33 |
+
eprint = {1405.0312},
|
34 |
+
timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},
|
35 |
+
biburl = {https://dblp.org/rec/bib/journals/corr/LinMBHPRDZ14},
|
36 |
+
bibsource = {dblp computer science bibliography, https://dblp.org}
|
37 |
+
}
|
38 |
+
"""
|
39 |
+
|
40 |
+
# Add description of the dataset here
|
41 |
+
# You can copy an official description
|
42 |
+
_DESCRIPTION = """\
|
43 |
+
COCO is a large-scale object detection, segmentation, and captioning dataset.
|
44 |
+
"""
|
45 |
+
|
46 |
+
# Add a link to an official homepage for the dataset here
|
47 |
+
_HOMEPAGE = "http://cocodataset.org/#home"
|
48 |
+
|
49 |
+
# Add the licence for the dataset here if you can find it
|
50 |
+
_LICENSE = ""
|
51 |
+
|
52 |
+
# Add link to the official dataset URLs here
|
53 |
+
# The HuggingFace dataset library don't host the datasets but only point to the original files
|
54 |
+
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
|
55 |
+
|
56 |
+
# This script is supposed to work with local (downloaded) COCO dataset.
|
57 |
+
_URLs = {}
|
58 |
+
|
59 |
+
|
60 |
+
# Name of the dataset usually match the script name with CamelCase instead of snake_case
|
61 |
+
class COCODataset(datasets.GeneratorBasedBuilder):
|
62 |
+
"""An example dataset script to work with the local (downloaded) COCO dataset"""
|
63 |
+
|
64 |
+
VERSION = datasets.Version("0.0.0")
|
65 |
+
|
66 |
+
BUILDER_CONFIG_CLASS = COCOBuilderConfig
|
67 |
+
BUILDER_CONFIGS = [
|
68 |
+
COCOBuilderConfig(name="2017", splits=["train", "val"]),
|
69 |
+
]
|
70 |
+
DEFAULT_CONFIG_NAME = "2017"
|
71 |
+
|
72 |
+
def _info(self):
|
73 |
+
# This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
|
74 |
+
|
75 |
+
feature_dict = {
|
76 |
+
"id": datasets.Value("int64"),
|
77 |
+
"objects": {
|
78 |
+
"bbox_id": datasets.Sequence(datasets.Value("int64")),
|
79 |
+
"category_id": datasets.Sequence(
|
80 |
+
datasets.ClassLabel(
|
81 |
+
names=[
|
82 |
+
"N/A",
|
83 |
+
"person",
|
84 |
+
"bicycle",
|
85 |
+
"car",
|
86 |
+
"motorcycle",
|
87 |
+
"airplane",
|
88 |
+
"bus",
|
89 |
+
"train",
|
90 |
+
"truck",
|
91 |
+
"boat",
|
92 |
+
"traffic light",
|
93 |
+
"fire hydrant",
|
94 |
+
"street sign",
|
95 |
+
"stop sign",
|
96 |
+
"parking meter",
|
97 |
+
"bench",
|
98 |
+
"bird",
|
99 |
+
"cat",
|
100 |
+
"dog",
|
101 |
+
"horse",
|
102 |
+
"sheep",
|
103 |
+
"cow",
|
104 |
+
"elephant",
|
105 |
+
"bear",
|
106 |
+
"zebra",
|
107 |
+
"giraffe",
|
108 |
+
"hat",
|
109 |
+
"backpack",
|
110 |
+
"umbrella",
|
111 |
+
"shoe",
|
112 |
+
"eye glasses",
|
113 |
+
"handbag",
|
114 |
+
"tie",
|
115 |
+
"suitcase",
|
116 |
+
"frisbee",
|
117 |
+
"skis",
|
118 |
+
"snowboard",
|
119 |
+
"sports ball",
|
120 |
+
"kite",
|
121 |
+
"baseball bat",
|
122 |
+
"baseball glove",
|
123 |
+
"skateboard",
|
124 |
+
"surfboard",
|
125 |
+
"tennis racket",
|
126 |
+
"bottle",
|
127 |
+
"plate",
|
128 |
+
"wine glass",
|
129 |
+
"cup",
|
130 |
+
"fork",
|
131 |
+
"knife",
|
132 |
+
"spoon",
|
133 |
+
"bowl",
|
134 |
+
"banana",
|
135 |
+
"apple",
|
136 |
+
"sandwich",
|
137 |
+
"orange",
|
138 |
+
"broccoli",
|
139 |
+
"carrot",
|
140 |
+
"hot dog",
|
141 |
+
"pizza",
|
142 |
+
"donut",
|
143 |
+
"cake",
|
144 |
+
"chair",
|
145 |
+
"couch",
|
146 |
+
"potted plant",
|
147 |
+
"bed",
|
148 |
+
"mirror",
|
149 |
+
"dining table",
|
150 |
+
"window",
|
151 |
+
"desk",
|
152 |
+
"toilet",
|
153 |
+
"door",
|
154 |
+
"tv",
|
155 |
+
"laptop",
|
156 |
+
"mouse",
|
157 |
+
"remote",
|
158 |
+
"keyboard",
|
159 |
+
"cell phone",
|
160 |
+
"microwave",
|
161 |
+
"oven",
|
162 |
+
"toaster",
|
163 |
+
"sink",
|
164 |
+
"refrigerator",
|
165 |
+
"blender",
|
166 |
+
"book",
|
167 |
+
"clock",
|
168 |
+
"vase",
|
169 |
+
"scissors",
|
170 |
+
"teddy bear",
|
171 |
+
"hair drier",
|
172 |
+
"toothbrush",
|
173 |
+
]
|
174 |
+
)
|
175 |
+
),
|
176 |
+
"bbox": datasets.Sequence(
|
177 |
+
datasets.Sequence(datasets.Value("float64"), length=4)
|
178 |
+
),
|
179 |
+
"iscrowd": datasets.Sequence(datasets.Value("int64")),
|
180 |
+
"area": datasets.Sequence(datasets.Value("float64")),
|
181 |
+
},
|
182 |
+
"height": datasets.Value("int64"),
|
183 |
+
"width": datasets.Value("int64"),
|
184 |
+
"file_name": datasets.Value("string"),
|
185 |
+
"coco_url": datasets.Value("string"),
|
186 |
+
"image_path": datasets.Value("string"),
|
187 |
+
}
|
188 |
+
|
189 |
+
features = datasets.Features(feature_dict)
|
190 |
+
|
191 |
+
return datasets.DatasetInfo(
|
192 |
+
# This is the description that will appear on the datasets page.
|
193 |
+
description=_DESCRIPTION,
|
194 |
+
# This defines the different columns of the dataset and their types
|
195 |
+
features=features, # Here we define them above because they are different between the two configurations
|
196 |
+
# If there's a common (input, target) tuple from the features,
|
197 |
+
# specify them here. They'll be used if as_supervised=True in
|
198 |
+
# builder.as_dataset.
|
199 |
+
supervised_keys=None,
|
200 |
+
# Homepage of the dataset for documentation
|
201 |
+
homepage=_HOMEPAGE,
|
202 |
+
# License for the dataset if available
|
203 |
+
license=_LICENSE,
|
204 |
+
# Citation for the dataset
|
205 |
+
citation=_CITATION,
|
206 |
+
)
|
207 |
+
|
208 |
+
def _split_generators(self, dl_manager):
|
209 |
+
"""Returns SplitGenerators."""
|
210 |
+
# This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
|
211 |
+
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
|
212 |
+
|
213 |
+
data_dir = self.config.data_dir
|
214 |
+
if not data_dir:
|
215 |
+
raise ValueError(
|
216 |
+
"This script is supposed to work with local (downloaded) COCO dataset. The argument `data_dir` in `load_dataset()` is required."
|
217 |
+
)
|
218 |
+
|
219 |
+
_DL_URLS = {
|
220 |
+
"train": os.path.join(data_dir, "train2017.zip"),
|
221 |
+
"val": os.path.join(data_dir, "val2017.zip"),
|
222 |
+
"annotations_trainval": os.path.join(
|
223 |
+
data_dir, "annotations_trainval2017.zip"
|
224 |
+
),
|
225 |
+
}
|
226 |
+
archive_path = dl_manager.download_and_extract(_DL_URLS)
|
227 |
+
|
228 |
+
splits = []
|
229 |
+
for split in self.config.splits:
|
230 |
+
if split == "train":
|
231 |
+
dataset = datasets.SplitGenerator(
|
232 |
+
name=datasets.Split.TRAIN,
|
233 |
+
# These kwargs will be passed to _generate_examples
|
234 |
+
gen_kwargs={
|
235 |
+
"json_path": os.path.join(
|
236 |
+
archive_path["annotations_trainval"],
|
237 |
+
"annotations",
|
238 |
+
"instances_train2017.json",
|
239 |
+
),
|
240 |
+
"image_dir": os.path.join(archive_path["train"], "train2017"),
|
241 |
+
"split": "train",
|
242 |
+
},
|
243 |
+
)
|
244 |
+
elif split in ["val", "valid", "validation", "dev"]:
|
245 |
+
dataset = datasets.SplitGenerator(
|
246 |
+
name=datasets.Split.VALIDATION,
|
247 |
+
# These kwargs will be passed to _generate_examples
|
248 |
+
gen_kwargs={
|
249 |
+
"json_path": os.path.join(
|
250 |
+
archive_path["annotations_trainval"],
|
251 |
+
"annotations",
|
252 |
+
"instances_val2017.json",
|
253 |
+
),
|
254 |
+
"image_dir": os.path.join(archive_path["val"], "val2017"),
|
255 |
+
"split": "valid",
|
256 |
+
},
|
257 |
+
)
|
258 |
+
else:
|
259 |
+
continue
|
260 |
+
|
261 |
+
splits.append(dataset)
|
262 |
+
|
263 |
+
return splits
|
264 |
+
|
265 |
+
def _generate_examples(
|
266 |
+
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
|
267 |
+
self,
|
268 |
+
json_path,
|
269 |
+
image_dir,
|
270 |
+
split,
|
271 |
+
):
|
272 |
+
"""Yields examples as (key, example) tuples."""
|
273 |
+
# This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
|
274 |
+
# The `key` is here for legacy reason (tfds) and is not important in itself.
|
275 |
+
|
276 |
+
features = [
|
277 |
+
"id",
|
278 |
+
"objects",
|
279 |
+
"height",
|
280 |
+
"width",
|
281 |
+
"file_name",
|
282 |
+
"coco_url",
|
283 |
+
"image_path",
|
284 |
+
]
|
285 |
+
object_features = [
|
286 |
+
"bbox_id",
|
287 |
+
"category_id",
|
288 |
+
"bbox",
|
289 |
+
"iscrowd",
|
290 |
+
"area",
|
291 |
+
]
|
292 |
+
|
293 |
+
with open(json_path, "r", encoding="UTF-8") as fp:
|
294 |
+
data = json.load(fp)
|
295 |
+
|
296 |
+
images = data["images"]
|
297 |
+
images_entry = {image["id"]: image for image in images}
|
298 |
+
for image_id, image_entry in images_entry.items():
|
299 |
+
image_entry["image_path"] = os.path.join(
|
300 |
+
image_dir, image_entry["file_name"]
|
301 |
+
)
|
302 |
+
image_entry["objects"] = []
|
303 |
+
|
304 |
+
objects = data["annotations"]
|
305 |
+
for id_, object_entry in enumerate(objects):
|
306 |
+
image_id = object_entry["image_id"]
|
307 |
+
|
308 |
+
entry = {k: v for k, v in object_entry.items() if k in object_features}
|
309 |
+
entry["bbox_id"] = object_entry["id"]
|
310 |
+
if entry["iscrowd"]:
|
311 |
+
continue
|
312 |
+
images_entry[image_id]["objects"].append(entry)
|
313 |
+
|
314 |
+
for id_, entry in images_entry.items():
|
315 |
+
entry = {k: v for k, v in entry.items() if k in features}
|
316 |
+
# collate objects
|
317 |
+
objects = entry.pop("objects")
|
318 |
+
if not objects:
|
319 |
+
continue
|
320 |
+
entry["objects"] = {
|
321 |
+
object_feature: [obj[object_feature] for obj in objects]
|
322 |
+
for object_feature in object_features
|
323 |
+
}
|
324 |
+
|
325 |
+
yield str(entry["id"]), entry
|