PawanratRung commited on
Commit
abd0b8d
·
verified ·
1 Parent(s): 19ebd30

Create dataset_mapper.py

Browse files
3rdparty/densepose/data/dataset_mapper.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+
4
+ import copy
5
+ import logging
6
+ from typing import Any, Dict, List, Tuple
7
+ import torch
8
+
9
+ from detectron2.data import MetadataCatalog
10
+ from detectron2.data import detection_utils as utils
11
+ from detectron2.data import transforms as T
12
+ from detectron2.layers import ROIAlign
13
+ from detectron2.structures import BoxMode
14
+ from detectron2.utils.file_io import PathManager
15
+
16
+ from densepose.structures import DensePoseDataRelative, DensePoseList, DensePoseTransformData
17
+
18
+
19
+ def build_augmentation(cfg, is_train):
20
+ logger = logging.getLogger(__name__)
21
+ result = utils.build_augmentation(cfg, is_train)
22
+ if is_train:
23
+ random_rotation = T.RandomRotation(
24
+ cfg.INPUT.ROTATION_ANGLES, expand=False, sample_style="choice"
25
+ )
26
+ result.append(random_rotation)
27
+ logger.info("DensePose-specific augmentation used in training: " + str(random_rotation))
28
+ return result
29
+
30
+
31
+ class DatasetMapper:
32
+ """
33
+ A customized version of `detectron2.data.DatasetMapper`
34
+ """
35
+
36
+ def __init__(self, cfg, is_train=True):
37
+ self.augmentation = build_augmentation(cfg, is_train)
38
+
39
+ # fmt: off
40
+ self.img_format = cfg.INPUT.FORMAT
41
+ self.mask_on = (
42
+ cfg.MODEL.MASK_ON or (
43
+ cfg.MODEL.DENSEPOSE_ON
44
+ and cfg.MODEL.ROI_DENSEPOSE_HEAD.COARSE_SEGM_TRAINED_BY_MASKS)
45
+ )
46
+ self.keypoint_on = cfg.MODEL.KEYPOINT_ON
47
+ self.densepose_on = cfg.MODEL.DENSEPOSE_ON
48
+ assert not cfg.MODEL.LOAD_PROPOSALS, "not supported yet"
49
+ # fmt: on
50
+ if self.keypoint_on and is_train:
51
+ # Flip only makes sense in training
52
+ self.keypoint_hflip_indices = utils.create_keypoint_hflip_indices(cfg.DATASETS.TRAIN)
53
+ else:
54
+ self.keypoint_hflip_indices = None
55
+
56
+ if self.densepose_on:
57
+ densepose_transform_srcs = [
58
+ MetadataCatalog.get(ds).densepose_transform_src
59
+ for ds in cfg.DATASETS.TRAIN + cfg.DATASETS.TEST
60
+ ]
61
+ assert len(densepose_transform_srcs) > 0
62
+ # TODO: check that DensePose transformation data is the same for
63
+ # all the datasets. Otherwise one would have to pass DB ID with
64
+ # each entry to select proper transformation data. For now, since
65
+ # all DensePose annotated data uses the same data semantics, we
66
+ # omit this check.
67
+ densepose_transform_data_fpath = PathManager.get_local_path(densepose_transform_srcs[0])
68
+ self.densepose_transform_data = DensePoseTransformData.load(
69
+ densepose_transform_data_fpath
70
+ )
71
+
72
+ self.is_train = is_train
73
+
74
+ def __call__(self, dataset_dict):
75
+ """
76
+ Args:
77
+ dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.
78
+
79
+ Returns:
80
+ dict: a format that builtin models in detectron2 accept
81
+ """
82
+ dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below
83
+ image = utils.read_image(dataset_dict["file_name"], format=self.img_format)
84
+ utils.check_image_size(dataset_dict, image)
85
+
86
+ image, transforms = T.apply_transform_gens(self.augmentation, image)
87
+ image_shape = image.shape[:2] # h, w
88
+ dataset_dict["image"] = torch.as_tensor(image.transpose(2, 0, 1).astype("float32"))
89
+
90
+ if not self.is_train:
91
+ dataset_dict.pop("annotations", None)
92
+ return dataset_dict
93
+
94
+ for anno in dataset_dict["annotations"]:
95
+ if not self.mask_on:
96
+ anno.pop("segmentation", None)
97
+ if not self.keypoint_on:
98
+ anno.pop("keypoints", None)
99
+
100
+ # USER: Implement additional transformations if you have other types of data
101
+ # USER: Don't call transpose_densepose if you don't need
102
+ annos = [
103
+ self._transform_densepose(
104
+ utils.transform_instance_annotations(
105
+ obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indices
106
+ ),
107
+ transforms,
108
+ )
109
+ for obj in dataset_dict.pop("annotations")
110
+ if obj.get("iscrowd", 0) == 0
111
+ ]
112
+
113
+ if self.mask_on:
114
+ self._add_densepose_masks_as_segmentation(annos, image_shape)
115
+
116
+ instances = utils.annotations_to_instances(annos, image_shape, mask_format="bitmask")
117
+ densepose_annotations = [obj.get("densepose") for obj in annos]
118
+ if densepose_annotations and not all(v is None for v in densepose_annotations):
119
+ instances.gt_densepose = DensePoseList(
120
+ densepose_annotations, instances.gt_boxes, image_shape
121
+ )
122
+
123
+ dataset_dict["instances"] = instances[instances.gt_boxes.nonempty()]
124
+ return dataset_dict
125
+
126
+ def _transform_densepose(self, annotation, transforms):
127
+ if not self.densepose_on:
128
+ return annotation
129
+
130
+ # Handle densepose annotations
131
+ is_valid, reason_not_valid = DensePoseDataRelative.validate_annotation(annotation)
132
+ if is_valid:
133
+ densepose_data = DensePoseDataRelative(annotation, cleanup=True)
134
+ densepose_data.apply_transform(transforms, self.densepose_transform_data)
135
+ annotation["densepose"] = densepose_data
136
+ else:
137
+ # logger = logging.getLogger(__name__)
138
+ # logger.debug("Could not load DensePose annotation: {}".format(reason_not_valid))
139
+ DensePoseDataRelative.cleanup_annotation(annotation)
140
+ # NOTE: annotations for certain instances may be unavailable.
141
+ # 'None' is accepted by the DensePostList data structure.
142
+ annotation["densepose"] = None
143
+ return annotation
144
+
145
+ def _add_densepose_masks_as_segmentation(
146
+ self, annotations: List[Dict[str, Any]], image_shape_hw: Tuple[int, int]
147
+ ):
148
+ for obj in annotations:
149
+ if ("densepose" not in obj) or ("segmentation" in obj):
150
+ continue
151
+ # DP segmentation: torch.Tensor [S, S] of float32, S=256
152
+ segm_dp = torch.zeros_like(obj["densepose"].segm)
153
+ segm_dp[obj["densepose"].segm > 0] = 1
154
+ segm_h, segm_w = segm_dp.shape
155
+ bbox_segm_dp = torch.tensor((0, 0, segm_h - 1, segm_w - 1), dtype=torch.float32)
156
+ # image bbox
157
+ x0, y0, x1, y1 = (
158
+ v.item() for v in BoxMode.convert(obj["bbox"], obj["bbox_mode"], BoxMode.XYXY_ABS)
159
+ )
160
+ segm_aligned = (
161
+ ROIAlign((y1 - y0, x1 - x0), 1.0, 0, aligned=True)
162
+ .forward(segm_dp.view(1, 1, *segm_dp.shape), bbox_segm_dp)
163
+ .squeeze()
164
+ )
165
+ image_mask = torch.zeros(*image_shape_hw, dtype=torch.float32)
166
+ image_mask[y0:y1, x0:x1] = segm_aligned
167
+ # segmentation for BitMask: np.array [H, W] of bool
168
+ obj["segmentation"] = image_mask >= 0.5