PawanratRung commited on
Commit
87d0afa
·
verified ·
1 Parent(s): 5320be2

Create coco.py

Browse files
3rdparty/densepose/data/datasets/coco.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ import contextlib
3
+ import io
4
+ import logging
5
+ import os
6
+ from collections import defaultdict
7
+ from dataclasses import dataclass
8
+ from typing import Any, Dict, Iterable, List, Optional
9
+ from fvcore.common.timer import Timer
10
+
11
+ from detectron2.data import DatasetCatalog, MetadataCatalog
12
+ from detectron2.structures import BoxMode
13
+ from detectron2.utils.file_io import PathManager
14
+
15
+ from ..utils import maybe_prepend_base_path
16
+
17
+ DENSEPOSE_MASK_KEY = "dp_masks"
18
+ DENSEPOSE_IUV_KEYS_WITHOUT_MASK = ["dp_x", "dp_y", "dp_I", "dp_U", "dp_V"]
19
+ DENSEPOSE_CSE_KEYS_WITHOUT_MASK = ["dp_x", "dp_y", "dp_vertex", "ref_model"]
20
+ DENSEPOSE_ALL_POSSIBLE_KEYS = set(
21
+ DENSEPOSE_IUV_KEYS_WITHOUT_MASK + DENSEPOSE_CSE_KEYS_WITHOUT_MASK + [DENSEPOSE_MASK_KEY]
22
+ )
23
+ DENSEPOSE_METADATA_URL_PREFIX = "https://dl.fbaipublicfiles.com/densepose/data/"
24
+
25
+
26
+ @dataclass
27
+ class CocoDatasetInfo:
28
+ name: str
29
+ images_root: str
30
+ annotations_fpath: str
31
+
32
+
33
+ DATASETS = [
34
+ CocoDatasetInfo(
35
+ name="densepose_coco_2014_train",
36
+ images_root="coco/train2014",
37
+ annotations_fpath="coco/annotations/densepose_train2014.json",
38
+ ),
39
+ CocoDatasetInfo(
40
+ name="densepose_coco_2014_minival",
41
+ images_root="coco/val2014",
42
+ annotations_fpath="coco/annotations/densepose_minival2014.json",
43
+ ),
44
+ CocoDatasetInfo(
45
+ name="densepose_coco_2014_minival_100",
46
+ images_root="coco/val2014",
47
+ annotations_fpath="coco/annotations/densepose_minival2014_100.json",
48
+ ),
49
+ CocoDatasetInfo(
50
+ name="densepose_coco_2014_valminusminival",
51
+ images_root="coco/val2014",
52
+ annotations_fpath="coco/annotations/densepose_valminusminival2014.json",
53
+ ),
54
+ CocoDatasetInfo(
55
+ name="densepose_coco_2014_train_cse",
56
+ images_root="coco/train2014",
57
+ annotations_fpath="coco_cse/densepose_train2014_cse.json",
58
+ ),
59
+ CocoDatasetInfo(
60
+ name="densepose_coco_2014_minival_cse",
61
+ images_root="coco/val2014",
62
+ annotations_fpath="coco_cse/densepose_minival2014_cse.json",
63
+ ),
64
+ CocoDatasetInfo(
65
+ name="densepose_coco_2014_minival_100_cse",
66
+ images_root="coco/val2014",
67
+ annotations_fpath="coco_cse/densepose_minival2014_100_cse.json",
68
+ ),
69
+ CocoDatasetInfo(
70
+ name="densepose_coco_2014_valminusminival_cse",
71
+ images_root="coco/val2014",
72
+ annotations_fpath="coco_cse/densepose_valminusminival2014_cse.json",
73
+ ),
74
+ CocoDatasetInfo(
75
+ name="densepose_chimps",
76
+ images_root="densepose_chimps/images",
77
+ annotations_fpath="densepose_chimps/densepose_chimps_densepose.json",
78
+ ),
79
+ CocoDatasetInfo(
80
+ name="densepose_chimps_cse_train",
81
+ images_root="densepose_chimps/images",
82
+ annotations_fpath="densepose_chimps/densepose_chimps_cse_train.json",
83
+ ),
84
+ CocoDatasetInfo(
85
+ name="densepose_chimps_cse_val",
86
+ images_root="densepose_chimps/images",
87
+ annotations_fpath="densepose_chimps/densepose_chimps_cse_val.json",
88
+ ),
89
+ CocoDatasetInfo(
90
+ name="posetrack2017_train",
91
+ images_root="posetrack2017/posetrack_data_2017",
92
+ annotations_fpath="posetrack2017/densepose_posetrack_train2017.json",
93
+ ),
94
+ CocoDatasetInfo(
95
+ name="posetrack2017_val",
96
+ images_root="posetrack2017/posetrack_data_2017",
97
+ annotations_fpath="posetrack2017/densepose_posetrack_val2017.json",
98
+ ),
99
+ CocoDatasetInfo(
100
+ name="lvis_v05_train",
101
+ images_root="coco/train2017",
102
+ annotations_fpath="lvis/lvis_v0.5_plus_dp_train.json",
103
+ ),
104
+ CocoDatasetInfo(
105
+ name="lvis_v05_val",
106
+ images_root="coco/val2017",
107
+ annotations_fpath="lvis/lvis_v0.5_plus_dp_val.json",
108
+ ),
109
+ ]
110
+
111
+
112
+ BASE_DATASETS = [
113
+ CocoDatasetInfo(
114
+ name="base_coco_2017_train",
115
+ images_root="coco/train2017",
116
+ annotations_fpath="coco/annotations/instances_train2017.json",
117
+ ),
118
+ CocoDatasetInfo(
119
+ name="base_coco_2017_val",
120
+ images_root="coco/val2017",
121
+ annotations_fpath="coco/annotations/instances_val2017.json",
122
+ ),
123
+ CocoDatasetInfo(
124
+ name="base_coco_2017_val_100",
125
+ images_root="coco/val2017",
126
+ annotations_fpath="coco/annotations/instances_val2017_100.json",
127
+ ),
128
+ ]
129
+
130
+
131
+ def get_metadata(base_path: Optional[str]) -> Dict[str, Any]:
132
+ """
133
+ Returns metadata associated with COCO DensePose datasets
134
+ Args:
135
+ base_path: Optional[str]
136
+ Base path used to load metadata from
137
+ Returns:
138
+ Dict[str, Any]
139
+ Metadata in the form of a dictionary
140
+ """
141
+ meta = {
142
+ "densepose_transform_src": maybe_prepend_base_path(base_path, "UV_symmetry_transforms.mat"),
143
+ "densepose_smpl_subdiv": maybe_prepend_base_path(base_path, "SMPL_subdiv.mat"),
144
+ "densepose_smpl_subdiv_transform": maybe_prepend_base_path(
145
+ base_path,
146
+ "SMPL_SUBDIV_TRANSFORM.mat",
147
+ ),
148
+ }
149
+ return meta
150
+
151
+
152
+ def _load_coco_annotations(json_file: str):
153
+ """
154
+ Load COCO annotations from a JSON file
155
+ Args:
156
+ json_file: str
157
+ Path to the file to load annotations from
158
+ Returns:
159
+ Instance of `pycocotools.coco.COCO` that provides access to annotations
160
+ data
161
+ """
162
+ from pycocotools.coco import COCO
163
+
164
+ logger = logging.getLogger(__name__)
165
+ timer = Timer()
166
+ with contextlib.redirect_stdout(io.StringIO()):
167
+ coco_api = COCO(json_file)
168
+ if timer.seconds() > 1:
169
+ logger.info("Loading {} takes {:.2f} seconds.".format(json_file, timer.seconds()))
170
+ return coco_api
171
+
172
+
173
+ def _add_categories_metadata(dataset_name: str, categories: List[Dict[str, Any]]):
174
+ meta = MetadataCatalog.get(dataset_name)
175
+ meta.categories = {c["id"]: c["name"] for c in categories}
176
+ logger = logging.getLogger(__name__)
177
+ logger.info("Dataset {} categories: {}".format(dataset_name, meta.categories))
178
+
179
+
180
+ def _verify_annotations_have_unique_ids(json_file: str, anns: List[List[Dict[str, Any]]]):
181
+ if "minival" in json_file:
182
+ # Skip validation on COCO2014 valminusminival and minival annotations
183
+ # The ratio of buggy annotations there is tiny and does not affect accuracy
184
+ # Therefore we explicitly white-list them
185
+ return
186
+ ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image]
187
+ assert len(set(ann_ids)) == len(ann_ids), "Annotation ids in '{}' are not unique!".format(
188
+ json_file
189
+ )
190
+
191
+
192
+ def _maybe_add_bbox(obj: Dict[str, Any], ann_dict: Dict[str, Any]):
193
+ if "bbox" not in ann_dict:
194
+ return
195
+ obj["bbox"] = ann_dict["bbox"]
196
+ obj["bbox_mode"] = BoxMode.XYWH_ABS
197
+
198
+
199
+ def _maybe_add_segm(obj: Dict[str, Any], ann_dict: Dict[str, Any]):
200
+ if "segmentation" not in ann_dict:
201
+ return
202
+ segm = ann_dict["segmentation"]
203
+ if not isinstance(segm, dict):
204
+ # filter out invalid polygons (< 3 points)
205
+ segm = [poly for poly in segm if len(poly) % 2 == 0 and len(poly) >= 6]
206
+ if len(segm) == 0:
207
+ return
208
+ obj["segmentation"] = segm
209
+
210
+
211
+ def _maybe_add_keypoints(obj: Dict[str, Any], ann_dict: Dict[str, Any]):
212
+ if "keypoints" not in ann_dict:
213
+ return
214
+ keypts = ann_dict["keypoints"] # list[int]
215
+ for idx, v in enumerate(keypts):
216
+ if idx % 3 != 2:
217
+ # COCO's segmentation coordinates are floating points in [0, H or W],
218
+ # but keypoint coordinates are integers in [0, H-1 or W-1]
219
+ # Therefore we assume the coordinates are "pixel indices" and
220
+ # add 0.5 to convert to floating point coordinates.
221
+ keypts[idx] = v + 0.5
222
+ obj["keypoints"] = keypts
223
+
224
+
225
+ def _maybe_add_densepose(obj: Dict[str, Any], ann_dict: Dict[str, Any]):
226
+ for key in DENSEPOSE_ALL_POSSIBLE_KEYS:
227
+ if key in ann_dict:
228
+ obj[key] = ann_dict[key]
229
+
230
+
231
+ def _combine_images_with_annotations(
232
+ dataset_name: str,
233
+ image_root: str,
234
+ img_datas: Iterable[Dict[str, Any]],
235
+ ann_datas: Iterable[Iterable[Dict[str, Any]]],
236
+ ):
237
+
238
+ ann_keys = ["iscrowd", "category_id"]
239
+ dataset_dicts = []
240
+ contains_video_frame_info = False
241
+
242
+ for img_dict, ann_dicts in zip(img_datas, ann_datas):
243
+ record = {}
244
+ record["file_name"] = os.path.join(image_root, img_dict["file_name"])
245
+ record["height"] = img_dict["height"]
246
+ record["width"] = img_dict["width"]
247
+ record["image_id"] = img_dict["id"]
248
+ record["dataset"] = dataset_name
249
+ if "frame_id" in img_dict:
250
+ record["frame_id"] = img_dict["frame_id"]
251
+ record["video_id"] = img_dict.get("vid_id", None)
252
+ contains_video_frame_info = True
253
+ objs = []
254
+ for ann_dict in ann_dicts:
255
+ assert ann_dict["image_id"] == record["image_id"]
256
+ assert ann_dict.get("ignore", 0) == 0
257
+ obj = {key: ann_dict[key] for key in ann_keys if key in ann_dict}
258
+ _maybe_add_bbox(obj, ann_dict)
259
+ _maybe_add_segm(obj, ann_dict)
260
+ _maybe_add_keypoints(obj, ann_dict)
261
+ _maybe_add_densepose(obj, ann_dict)
262
+ objs.append(obj)
263
+ record["annotations"] = objs
264
+ dataset_dicts.append(record)
265
+ if contains_video_frame_info:
266
+ create_video_frame_mapping(dataset_name, dataset_dicts)
267
+ return dataset_dicts
268
+
269
+
270
+ def get_contiguous_id_to_category_id_map(metadata):
271
+ cat_id_2_cont_id = metadata.thing_dataset_id_to_contiguous_id
272
+ cont_id_2_cat_id = {}
273
+ for cat_id, cont_id in cat_id_2_cont_id.items():
274
+ if cont_id in cont_id_2_cat_id:
275
+ continue
276
+ cont_id_2_cat_id[cont_id] = cat_id
277
+ return cont_id_2_cat_id
278
+
279
+
280
+ def maybe_filter_categories_cocoapi(dataset_name, coco_api):
281
+ meta = MetadataCatalog.get(dataset_name)
282
+ cont_id_2_cat_id = get_contiguous_id_to_category_id_map(meta)
283
+ cat_id_2_cont_id = meta.thing_dataset_id_to_contiguous_id
284
+ # filter categories
285
+ cats = []
286
+ for cat in coco_api.dataset["categories"]:
287
+ cat_id = cat["id"]
288
+ if cat_id not in cat_id_2_cont_id:
289
+ continue
290
+ cont_id = cat_id_2_cont_id[cat_id]
291
+ if (cont_id in cont_id_2_cat_id) and (cont_id_2_cat_id[cont_id] == cat_id):
292
+ cats.append(cat)
293
+ coco_api.dataset["categories"] = cats
294
+ # filter annotations, if multiple categories are mapped to a single
295
+ # contiguous ID, use only one category ID and map all annotations to that category ID
296
+ anns = []
297
+ for ann in coco_api.dataset["annotations"]:
298
+ cat_id = ann["category_id"]
299
+ if cat_id not in cat_id_2_cont_id:
300
+ continue
301
+ cont_id = cat_id_2_cont_id[cat_id]
302
+ ann["category_id"] = cont_id_2_cat_id[cont_id]
303
+ anns.append(ann)
304
+ coco_api.dataset["annotations"] = anns
305
+ # recreate index
306
+ coco_api.createIndex()
307
+
308
+
309
+ def maybe_filter_and_map_categories_cocoapi(dataset_name, coco_api):
310
+ meta = MetadataCatalog.get(dataset_name)
311
+ category_id_map = meta.thing_dataset_id_to_contiguous_id
312
+ # map categories
313
+ cats = []
314
+ for cat in coco_api.dataset["categories"]:
315
+ cat_id = cat["id"]
316
+ if cat_id not in category_id_map:
317
+ continue
318
+ cat["id"] = category_id_map[cat_id]
319
+ cats.append(cat)
320
+ coco_api.dataset["categories"] = cats
321
+ # map annotation categories
322
+ anns = []
323
+ for ann in coco_api.dataset["annotations"]:
324
+ cat_id = ann["category_id"]
325
+ if cat_id not in category_id_map:
326
+ continue
327
+ ann["category_id"] = category_id_map[cat_id]
328
+ anns.append(ann)
329
+ coco_api.dataset["annotations"] = anns
330
+ # recreate index
331
+ coco_api.createIndex()
332
+
333
+
334
+ def create_video_frame_mapping(dataset_name, dataset_dicts):
335
+ mapping = defaultdict(dict)
336
+ for d in dataset_dicts:
337
+ video_id = d.get("video_id")
338
+ if video_id is None:
339
+ continue
340
+ mapping[video_id].update({d["frame_id"]: d["file_name"]})
341
+ MetadataCatalog.get(dataset_name).set(video_frame_mapping=mapping)
342
+
343
+
344
+ def load_coco_json(annotations_json_file: str, image_root: str, dataset_name: str):
345
+ """
346
+ Loads a JSON file with annotations in COCO instances format.
347
+ Replaces `detectron2.data.datasets.coco.load_coco_json` to handle metadata
348
+ in a more flexible way. Postpones category mapping to a later stage to be
349
+ able to combine several datasets with different (but coherent) sets of
350
+ categories.
351
+ Args:
352
+ annotations_json_file: str
353
+ Path to the JSON file with annotations in COCO instances format.
354
+ image_root: str
355
+ directory that contains all the images
356
+ dataset_name: str
357
+ the name that identifies a dataset, e.g. "densepose_coco_2014_train"
358
+ extra_annotation_keys: Optional[List[str]]
359
+ If provided, these keys are used to extract additional data from
360
+ the annotations.
361
+ """
362
+ coco_api = _load_coco_annotations(PathManager.get_local_path(annotations_json_file))
363
+ _add_categories_metadata(dataset_name, coco_api.loadCats(coco_api.getCatIds()))
364
+ # sort indices for reproducible results
365
+ img_ids = sorted(coco_api.imgs.keys())
366
+ # imgs is a list of dicts, each looks something like:
367
+ # {'license': 4,
368
+ # 'url': 'http://farm6.staticflickr.com/5454/9413846304_881d5e5c3b_z.jpg',
369
+ # 'file_name': 'COCO_val2014_000000001268.jpg',
370
+ # 'height': 427,
371
+ # 'width': 640,
372
+ # 'date_captured': '2013-11-17 05:57:24',
373
+ # 'id': 1268}
374
+ imgs = coco_api.loadImgs(img_ids)
375
+ logger = logging.getLogger(__name__)
376
+ logger.info("Loaded {} images in COCO format from {}".format(len(imgs), annotations_json_file))
377
+ # anns is a list[list[dict]], where each dict is an annotation
378
+ # record for an object. The inner list enumerates the objects in an image
379
+ # and the outer list enumerates over images.
380
+ anns = [coco_api.imgToAnns[img_id] for img_id in img_ids]
381
+ _verify_annotations_have_unique_ids(annotations_json_file, anns)
382
+ dataset_records = _combine_images_with_annotations(dataset_name, image_root, imgs, anns)
383
+ return dataset_records
384
+
385
+
386
+ def register_dataset(dataset_data: CocoDatasetInfo, datasets_root: Optional[str] = None):
387
+ """
388
+ Registers provided COCO DensePose dataset
389
+
390
+ Args:
391
+ dataset_data: CocoDatasetInfo
392
+ Dataset data
393
+ datasets_root: Optional[str]
394
+ Datasets root folder (default: None)
395
+ """
396
+ annotations_fpath = maybe_prepend_base_path(datasets_root, dataset_data.annotations_fpath)
397
+ images_root = maybe_prepend_base_path(datasets_root, dataset_data.images_root)
398
+
399
+ def load_annotations():
400
+ return load_coco_json(
401
+ annotations_json_file=annotations_fpath,
402
+ image_root=images_root,
403
+ dataset_name=dataset_data.name,
404
+ )
405
+
406
+ DatasetCatalog.register(dataset_data.name, load_annotations)
407
+ MetadataCatalog.get(dataset_data.name).set(
408
+ json_file=annotations_fpath,
409
+ image_root=images_root,
410
+ **get_metadata(DENSEPOSE_METADATA_URL_PREFIX)
411
+ )
412
+
413
+
414
+ def register_datasets(
415
+ datasets_data: Iterable[CocoDatasetInfo], datasets_root: Optional[str] = None
416
+ ):
417
+ """
418
+ Registers provided COCO DensePose datasets
419
+ Args:
420
+ datasets_data: Iterable[CocoDatasetInfo]
421
+ An iterable of dataset datas
422
+ datasets_root: Optional[str]
423
+ Datasets root folder (default: None)
424
+ """
425
+ for dataset_data in datasets_data:
426
+ register_dataset(dataset_data, datasets_root)