basso4 commited on
Commit
7bd9425
1 Parent(s): 49458e6

Upload 785 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. densepose/__init__.py +20 -0
  2. densepose/__pycache__/__init__.cpython-310.pyc +0 -0
  3. densepose/__pycache__/__init__.cpython-38.pyc +0 -0
  4. densepose/__pycache__/config.cpython-310.pyc +0 -0
  5. densepose/__pycache__/config.cpython-38.pyc +0 -0
  6. densepose/config.py +277 -0
  7. densepose/converters/__init__.py +15 -0
  8. densepose/converters/__pycache__/__init__.cpython-310.pyc +0 -0
  9. densepose/converters/__pycache__/__init__.cpython-38.pyc +0 -0
  10. densepose/converters/__pycache__/base.cpython-310.pyc +0 -0
  11. densepose/converters/__pycache__/base.cpython-38.pyc +0 -0
  12. densepose/converters/__pycache__/builtin.cpython-310.pyc +0 -0
  13. densepose/converters/__pycache__/builtin.cpython-38.pyc +0 -0
  14. densepose/converters/__pycache__/chart_output_hflip.cpython-310.pyc +0 -0
  15. densepose/converters/__pycache__/chart_output_hflip.cpython-38.pyc +0 -0
  16. densepose/converters/__pycache__/chart_output_to_chart_result.cpython-310.pyc +0 -0
  17. densepose/converters/__pycache__/chart_output_to_chart_result.cpython-38.pyc +0 -0
  18. densepose/converters/__pycache__/hflip.cpython-310.pyc +0 -0
  19. densepose/converters/__pycache__/hflip.cpython-38.pyc +0 -0
  20. densepose/converters/__pycache__/segm_to_mask.cpython-310.pyc +0 -0
  21. densepose/converters/__pycache__/segm_to_mask.cpython-38.pyc +0 -0
  22. densepose/converters/__pycache__/to_chart_result.cpython-310.pyc +0 -0
  23. densepose/converters/__pycache__/to_chart_result.cpython-38.pyc +0 -0
  24. densepose/converters/__pycache__/to_mask.cpython-310.pyc +0 -0
  25. densepose/converters/__pycache__/to_mask.cpython-38.pyc +0 -0
  26. densepose/converters/base.py +93 -0
  27. densepose/converters/builtin.py +31 -0
  28. densepose/converters/chart_output_hflip.py +71 -0
  29. densepose/converters/chart_output_to_chart_result.py +188 -0
  30. densepose/converters/hflip.py +34 -0
  31. densepose/converters/segm_to_mask.py +150 -0
  32. densepose/converters/to_chart_result.py +70 -0
  33. densepose/converters/to_mask.py +49 -0
  34. densepose/data/__init__.py +25 -0
  35. densepose/data/__pycache__/__init__.cpython-310.pyc +0 -0
  36. densepose/data/__pycache__/__init__.cpython-38.pyc +0 -0
  37. densepose/data/__pycache__/build.cpython-310.pyc +0 -0
  38. densepose/data/__pycache__/build.cpython-38.pyc +0 -0
  39. densepose/data/__pycache__/combined_loader.cpython-310.pyc +0 -0
  40. densepose/data/__pycache__/combined_loader.cpython-38.pyc +0 -0
  41. densepose/data/__pycache__/dataset_mapper.cpython-310.pyc +0 -0
  42. densepose/data/__pycache__/dataset_mapper.cpython-38.pyc +0 -0
  43. densepose/data/__pycache__/image_list_dataset.cpython-310.pyc +0 -0
  44. densepose/data/__pycache__/image_list_dataset.cpython-38.pyc +0 -0
  45. densepose/data/__pycache__/inference_based_loader.cpython-310.pyc +0 -0
  46. densepose/data/__pycache__/inference_based_loader.cpython-38.pyc +0 -0
  47. densepose/data/__pycache__/utils.cpython-310.pyc +0 -0
  48. densepose/data/__pycache__/utils.cpython-38.pyc +0 -0
  49. densepose/data/build.py +736 -0
  50. densepose/data/combined_loader.py +44 -0
densepose/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ from .data.datasets import builtin # just to register data
3
+ from .converters import builtin as builtin_converters # register converters
4
+ from .config import (
5
+ add_densepose_config,
6
+ add_densepose_head_config,
7
+ add_hrnet_config,
8
+ add_dataset_category_config,
9
+ add_bootstrap_config,
10
+ load_bootstrap_config,
11
+ )
12
+ from .structures import DensePoseDataRelative, DensePoseList, DensePoseTransformData
13
+ from .evaluation import DensePoseCOCOEvaluator
14
+ from .modeling.roi_heads import DensePoseROIHeads
15
+ from .modeling.test_time_augmentation import (
16
+ DensePoseGeneralizedRCNNWithTTA,
17
+ DensePoseDatasetMapperTTA,
18
+ )
19
+ from .utils.transform import load_from_cfg
20
+ from .modeling.hrfpn import build_hrfpn_backbone
densepose/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (926 Bytes). View file
 
densepose/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (924 Bytes). View file
 
densepose/__pycache__/config.cpython-310.pyc ADDED
Binary file (5.83 kB). View file
 
densepose/__pycache__/config.cpython-38.pyc ADDED
Binary file (5.76 kB). View file
 
densepose/config.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding = utf-8 -*-
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ # pyre-ignore-all-errors
4
+
5
+ from detectron2.config import CfgNode as CN
6
+
7
+
8
+ def add_dataset_category_config(cfg: CN) -> None:
9
+ """
10
+ Add config for additional category-related dataset options
11
+ - category whitelisting
12
+ - category mapping
13
+ """
14
+ _C = cfg
15
+ _C.DATASETS.CATEGORY_MAPS = CN(new_allowed=True)
16
+ _C.DATASETS.WHITELISTED_CATEGORIES = CN(new_allowed=True)
17
+ # class to mesh mapping
18
+ _C.DATASETS.CLASS_TO_MESH_NAME_MAPPING = CN(new_allowed=True)
19
+
20
+
21
+ def add_evaluation_config(cfg: CN) -> None:
22
+ _C = cfg
23
+ _C.DENSEPOSE_EVALUATION = CN()
24
+ # evaluator type, possible values:
25
+ # - "iou": evaluator for models that produce iou data
26
+ # - "cse": evaluator for models that produce cse data
27
+ _C.DENSEPOSE_EVALUATION.TYPE = "iou"
28
+ # storage for DensePose results, possible values:
29
+ # - "none": no explicit storage, all the results are stored in the
30
+ # dictionary with predictions, memory intensive;
31
+ # historically the default storage type
32
+ # - "ram": RAM storage, uses per-process RAM storage, which is
33
+ # reduced to a single process storage on later stages,
34
+ # less memory intensive
35
+ # - "file": file storage, uses per-process file-based storage,
36
+ # the least memory intensive, but may create bottlenecks
37
+ # on file system accesses
38
+ _C.DENSEPOSE_EVALUATION.STORAGE = "none"
39
+ # minimum threshold for IOU values: the lower its values is,
40
+ # the more matches are produced (and the higher the AP score)
41
+ _C.DENSEPOSE_EVALUATION.MIN_IOU_THRESHOLD = 0.5
42
+ # Non-distributed inference is slower (at inference time) but can avoid RAM OOM
43
+ _C.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE = True
44
+ # evaluate mesh alignment based on vertex embeddings, only makes sense in CSE context
45
+ _C.DENSEPOSE_EVALUATION.EVALUATE_MESH_ALIGNMENT = False
46
+ # meshes to compute mesh alignment for
47
+ _C.DENSEPOSE_EVALUATION.MESH_ALIGNMENT_MESH_NAMES = []
48
+
49
+
50
+ def add_bootstrap_config(cfg: CN) -> None:
51
+ """ """
52
+ _C = cfg
53
+ _C.BOOTSTRAP_DATASETS = []
54
+ _C.BOOTSTRAP_MODEL = CN()
55
+ _C.BOOTSTRAP_MODEL.WEIGHTS = ""
56
+ _C.BOOTSTRAP_MODEL.DEVICE = "cuda"
57
+
58
+
59
+ def get_bootstrap_dataset_config() -> CN:
60
+ _C = CN()
61
+ _C.DATASET = ""
62
+ # ratio used to mix data loaders
63
+ _C.RATIO = 0.1
64
+ # image loader
65
+ _C.IMAGE_LOADER = CN(new_allowed=True)
66
+ _C.IMAGE_LOADER.TYPE = ""
67
+ _C.IMAGE_LOADER.BATCH_SIZE = 4
68
+ _C.IMAGE_LOADER.NUM_WORKERS = 4
69
+ _C.IMAGE_LOADER.CATEGORIES = []
70
+ _C.IMAGE_LOADER.MAX_COUNT_PER_CATEGORY = 1_000_000
71
+ _C.IMAGE_LOADER.CATEGORY_TO_CLASS_MAPPING = CN(new_allowed=True)
72
+ # inference
73
+ _C.INFERENCE = CN()
74
+ # batch size for model inputs
75
+ _C.INFERENCE.INPUT_BATCH_SIZE = 4
76
+ # batch size to group model outputs
77
+ _C.INFERENCE.OUTPUT_BATCH_SIZE = 2
78
+ # sampled data
79
+ _C.DATA_SAMPLER = CN(new_allowed=True)
80
+ _C.DATA_SAMPLER.TYPE = ""
81
+ _C.DATA_SAMPLER.USE_GROUND_TRUTH_CATEGORIES = False
82
+ # filter
83
+ _C.FILTER = CN(new_allowed=True)
84
+ _C.FILTER.TYPE = ""
85
+ return _C
86
+
87
+
88
+ def load_bootstrap_config(cfg: CN) -> None:
89
+ """
90
+ Bootstrap datasets are given as a list of `dict` that are not automatically
91
+ converted into CfgNode. This method processes all bootstrap dataset entries
92
+ and ensures that they are in CfgNode format and comply with the specification
93
+ """
94
+ if not cfg.BOOTSTRAP_DATASETS:
95
+ return
96
+
97
+ bootstrap_datasets_cfgnodes = []
98
+ for dataset_cfg in cfg.BOOTSTRAP_DATASETS:
99
+ _C = get_bootstrap_dataset_config().clone()
100
+ _C.merge_from_other_cfg(CN(dataset_cfg))
101
+ bootstrap_datasets_cfgnodes.append(_C)
102
+ cfg.BOOTSTRAP_DATASETS = bootstrap_datasets_cfgnodes
103
+
104
+
105
+ def add_densepose_head_cse_config(cfg: CN) -> None:
106
+ """
107
+ Add configuration options for Continuous Surface Embeddings (CSE)
108
+ """
109
+ _C = cfg
110
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE = CN()
111
+ # Dimensionality D of the embedding space
112
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_SIZE = 16
113
+ # Embedder specifications for various mesh IDs
114
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBEDDERS = CN(new_allowed=True)
115
+ # normalization coefficient for embedding distances
116
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBEDDING_DIST_GAUSS_SIGMA = 0.01
117
+ # normalization coefficient for geodesic distances
118
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.GEODESIC_DIST_GAUSS_SIGMA = 0.01
119
+ # embedding loss weight
120
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_LOSS_WEIGHT = 0.6
121
+ # embedding loss name, currently the following options are supported:
122
+ # - EmbeddingLoss: cross-entropy on vertex labels
123
+ # - SoftEmbeddingLoss: cross-entropy on vertex label combined with
124
+ # Gaussian penalty on distance between vertices
125
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_LOSS_NAME = "EmbeddingLoss"
126
+ # optimizer hyperparameters
127
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.FEATURES_LR_FACTOR = 1.0
128
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBEDDING_LR_FACTOR = 1.0
129
+ # Shape to shape cycle consistency loss parameters:
130
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.SHAPE_TO_SHAPE_CYCLE_LOSS = CN({"ENABLED": False})
131
+ # shape to shape cycle consistency loss weight
132
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.SHAPE_TO_SHAPE_CYCLE_LOSS.WEIGHT = 0.025
133
+ # norm type used for loss computation
134
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.SHAPE_TO_SHAPE_CYCLE_LOSS.NORM_P = 2
135
+ # normalization term for embedding similarity matrices
136
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.SHAPE_TO_SHAPE_CYCLE_LOSS.TEMPERATURE = 0.05
137
+ # maximum number of vertices to include into shape to shape cycle loss
138
+ # if negative or zero, all vertices are considered
139
+ # if positive, random subset of vertices of given size is considered
140
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.SHAPE_TO_SHAPE_CYCLE_LOSS.MAX_NUM_VERTICES = 4936
141
+ # Pixel to shape cycle consistency loss parameters:
142
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS = CN({"ENABLED": False})
143
+ # pixel to shape cycle consistency loss weight
144
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.WEIGHT = 0.0001
145
+ # norm type used for loss computation
146
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.NORM_P = 2
147
+ # map images to all meshes and back (if false, use only gt meshes from the batch)
148
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.USE_ALL_MESHES_NOT_GT_ONLY = False
149
+ # Randomly select at most this number of pixels from every instance
150
+ # if negative or zero, all vertices are considered
151
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.NUM_PIXELS_TO_SAMPLE = 100
152
+ # normalization factor for pixel to pixel distances (higher value = smoother distribution)
153
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.PIXEL_SIGMA = 5.0
154
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.TEMPERATURE_PIXEL_TO_VERTEX = 0.05
155
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CSE.PIX_TO_SHAPE_CYCLE_LOSS.TEMPERATURE_VERTEX_TO_PIXEL = 0.05
156
+
157
+
158
+ def add_densepose_head_config(cfg: CN) -> None:
159
+ """
160
+ Add config for densepose head.
161
+ """
162
+ _C = cfg
163
+
164
+ _C.MODEL.DENSEPOSE_ON = True
165
+
166
+ _C.MODEL.ROI_DENSEPOSE_HEAD = CN()
167
+ _C.MODEL.ROI_DENSEPOSE_HEAD.NAME = ""
168
+ _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_STACKED_CONVS = 8
169
+ # Number of parts used for point labels
170
+ _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_PATCHES = 24
171
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECONV_KERNEL = 4
172
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_DIM = 512
173
+ _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_KERNEL = 3
174
+ _C.MODEL.ROI_DENSEPOSE_HEAD.UP_SCALE = 2
175
+ _C.MODEL.ROI_DENSEPOSE_HEAD.HEATMAP_SIZE = 112
176
+ _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_TYPE = "ROIAlignV2"
177
+ _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_RESOLUTION = 28
178
+ _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_SAMPLING_RATIO = 2
179
+ _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_COARSE_SEGM_CHANNELS = 2 # 15 or 2
180
+ # Overlap threshold for an RoI to be considered foreground (if >= FG_IOU_THRESHOLD)
181
+ _C.MODEL.ROI_DENSEPOSE_HEAD.FG_IOU_THRESHOLD = 0.7
182
+ # Loss weights for annotation masks.(14 Parts)
183
+ _C.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS = 5.0
184
+ # Loss weights for surface parts. (24 Parts)
185
+ _C.MODEL.ROI_DENSEPOSE_HEAD.PART_WEIGHTS = 1.0
186
+ # Loss weights for UV regression.
187
+ _C.MODEL.ROI_DENSEPOSE_HEAD.POINT_REGRESSION_WEIGHTS = 0.01
188
+ # Coarse segmentation is trained using instance segmentation task data
189
+ _C.MODEL.ROI_DENSEPOSE_HEAD.COARSE_SEGM_TRAINED_BY_MASKS = False
190
+ # For Decoder
191
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_ON = True
192
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NUM_CLASSES = 256
193
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_CONV_DIMS = 256
194
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NORM = ""
195
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_COMMON_STRIDE = 4
196
+ # For DeepLab head
197
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB = CN()
198
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NORM = "GN"
199
+ _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NONLOCAL_ON = 0
200
+ # Predictor class name, must be registered in DENSEPOSE_PREDICTOR_REGISTRY
201
+ # Some registered predictors:
202
+ # "DensePoseChartPredictor": predicts segmentation and UV coordinates for predefined charts
203
+ # "DensePoseChartWithConfidencePredictor": predicts segmentation, UV coordinates
204
+ # and associated confidences for predefined charts (default)
205
+ # "DensePoseEmbeddingWithConfidencePredictor": predicts segmentation, embeddings
206
+ # and associated confidences for CSE
207
+ _C.MODEL.ROI_DENSEPOSE_HEAD.PREDICTOR_NAME = "DensePoseChartWithConfidencePredictor"
208
+ # Loss class name, must be registered in DENSEPOSE_LOSS_REGISTRY
209
+ # Some registered losses:
210
+ # "DensePoseChartLoss": loss for chart-based models that estimate
211
+ # segmentation and UV coordinates
212
+ # "DensePoseChartWithConfidenceLoss": loss for chart-based models that estimate
213
+ # segmentation, UV coordinates and the corresponding confidences (default)
214
+ _C.MODEL.ROI_DENSEPOSE_HEAD.LOSS_NAME = "DensePoseChartWithConfidenceLoss"
215
+ # Confidences
216
+ # Enable learning UV confidences (variances) along with the actual values
217
+ _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE = CN({"ENABLED": False})
218
+ # UV confidence lower bound
219
+ _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.EPSILON = 0.01
220
+ # Enable learning segmentation confidences (variances) along with the actual values
221
+ _C.MODEL.ROI_DENSEPOSE_HEAD.SEGM_CONFIDENCE = CN({"ENABLED": False})
222
+ # Segmentation confidence lower bound
223
+ _C.MODEL.ROI_DENSEPOSE_HEAD.SEGM_CONFIDENCE.EPSILON = 0.01
224
+ # Statistical model type for confidence learning, possible values:
225
+ # - "iid_iso": statistically independent identically distributed residuals
226
+ # with isotropic covariance
227
+ # - "indep_aniso": statistically independent residuals with anisotropic
228
+ # covariances
229
+ _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.TYPE = "iid_iso"
230
+ # List of angles for rotation in data augmentation during training
231
+ _C.INPUT.ROTATION_ANGLES = [0]
232
+ _C.TEST.AUG.ROTATION_ANGLES = () # Rotation TTA
233
+
234
+ add_densepose_head_cse_config(cfg)
235
+
236
+
237
+ def add_hrnet_config(cfg: CN) -> None:
238
+ """
239
+ Add config for HRNet backbone.
240
+ """
241
+ _C = cfg
242
+
243
+ # For HigherHRNet w32
244
+ _C.MODEL.HRNET = CN()
245
+ _C.MODEL.HRNET.STEM_INPLANES = 64
246
+ _C.MODEL.HRNET.STAGE2 = CN()
247
+ _C.MODEL.HRNET.STAGE2.NUM_MODULES = 1
248
+ _C.MODEL.HRNET.STAGE2.NUM_BRANCHES = 2
249
+ _C.MODEL.HRNET.STAGE2.BLOCK = "BASIC"
250
+ _C.MODEL.HRNET.STAGE2.NUM_BLOCKS = [4, 4]
251
+ _C.MODEL.HRNET.STAGE2.NUM_CHANNELS = [32, 64]
252
+ _C.MODEL.HRNET.STAGE2.FUSE_METHOD = "SUM"
253
+ _C.MODEL.HRNET.STAGE3 = CN()
254
+ _C.MODEL.HRNET.STAGE3.NUM_MODULES = 4
255
+ _C.MODEL.HRNET.STAGE3.NUM_BRANCHES = 3
256
+ _C.MODEL.HRNET.STAGE3.BLOCK = "BASIC"
257
+ _C.MODEL.HRNET.STAGE3.NUM_BLOCKS = [4, 4, 4]
258
+ _C.MODEL.HRNET.STAGE3.NUM_CHANNELS = [32, 64, 128]
259
+ _C.MODEL.HRNET.STAGE3.FUSE_METHOD = "SUM"
260
+ _C.MODEL.HRNET.STAGE4 = CN()
261
+ _C.MODEL.HRNET.STAGE4.NUM_MODULES = 3
262
+ _C.MODEL.HRNET.STAGE4.NUM_BRANCHES = 4
263
+ _C.MODEL.HRNET.STAGE4.BLOCK = "BASIC"
264
+ _C.MODEL.HRNET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4]
265
+ _C.MODEL.HRNET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256]
266
+ _C.MODEL.HRNET.STAGE4.FUSE_METHOD = "SUM"
267
+
268
+ _C.MODEL.HRNET.HRFPN = CN()
269
+ _C.MODEL.HRNET.HRFPN.OUT_CHANNELS = 256
270
+
271
+
272
+ def add_densepose_config(cfg: CN) -> None:
273
+ add_densepose_head_config(cfg)
274
+ add_hrnet_config(cfg)
275
+ add_bootstrap_config(cfg)
276
+ add_dataset_category_config(cfg)
277
+ add_evaluation_config(cfg)
densepose/converters/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from .hflip import HFlipConverter
4
+ from .to_mask import ToMaskConverter
5
+ from .to_chart_result import ToChartResultConverter, ToChartResultConverterWithConfidences
6
+ from .segm_to_mask import (
7
+ predictor_output_with_fine_and_coarse_segm_to_mask,
8
+ predictor_output_with_coarse_segm_to_mask,
9
+ resample_fine_and_coarse_segm_to_bbox,
10
+ )
11
+ from .chart_output_to_chart_result import (
12
+ densepose_chart_predictor_output_to_result,
13
+ densepose_chart_predictor_output_to_result_with_confidences,
14
+ )
15
+ from .chart_output_hflip import densepose_chart_predictor_output_hflip
densepose/converters/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (800 Bytes). View file
 
densepose/converters/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (798 Bytes). View file
 
densepose/converters/__pycache__/base.cpython-310.pyc ADDED
Binary file (3.68 kB). View file
 
densepose/converters/__pycache__/base.cpython-38.pyc ADDED
Binary file (3.65 kB). View file
 
densepose/converters/__pycache__/builtin.cpython-310.pyc ADDED
Binary file (805 Bytes). View file
 
densepose/converters/__pycache__/builtin.cpython-38.pyc ADDED
Binary file (811 Bytes). View file
 
densepose/converters/__pycache__/chart_output_hflip.cpython-310.pyc ADDED
Binary file (1.95 kB). View file
 
densepose/converters/__pycache__/chart_output_hflip.cpython-38.pyc ADDED
Binary file (1.96 kB). View file
 
densepose/converters/__pycache__/chart_output_to_chart_result.cpython-310.pyc ADDED
Binary file (6.08 kB). View file
 
densepose/converters/__pycache__/chart_output_to_chart_result.cpython-38.pyc ADDED
Binary file (6.06 kB). View file
 
densepose/converters/__pycache__/hflip.cpython-310.pyc ADDED
Binary file (1.36 kB). View file
 
densepose/converters/__pycache__/hflip.cpython-38.pyc ADDED
Binary file (1.35 kB). View file
 
densepose/converters/__pycache__/segm_to_mask.cpython-310.pyc ADDED
Binary file (5.79 kB). View file
 
densepose/converters/__pycache__/segm_to_mask.cpython-38.pyc ADDED
Binary file (5.77 kB). View file
 
densepose/converters/__pycache__/to_chart_result.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
densepose/converters/__pycache__/to_chart_result.cpython-38.pyc ADDED
Binary file (2.73 kB). View file
 
densepose/converters/__pycache__/to_mask.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
densepose/converters/__pycache__/to_mask.cpython-38.pyc ADDED
Binary file (1.75 kB). View file
 
densepose/converters/base.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Any, Tuple, Type
4
+ import torch
5
+
6
+
7
+ class BaseConverter:
8
+ """
9
+ Converter base class to be reused by various converters.
10
+ Converter allows one to convert data from various source types to a particular
11
+ destination type. Each source type needs to register its converter. The
12
+ registration for each source type is valid for all descendants of that type.
13
+ """
14
+
15
+ @classmethod
16
+ def register(cls, from_type: Type, converter: Any = None):
17
+ """
18
+ Registers a converter for the specified type.
19
+ Can be used as a decorator (if converter is None), or called as a method.
20
+
21
+ Args:
22
+ from_type (type): type to register the converter for;
23
+ all instances of this type will use the same converter
24
+ converter (callable): converter to be registered for the given
25
+ type; if None, this method is assumed to be a decorator for the converter
26
+ """
27
+
28
+ if converter is not None:
29
+ cls._do_register(from_type, converter)
30
+
31
+ def wrapper(converter: Any) -> Any:
32
+ cls._do_register(from_type, converter)
33
+ return converter
34
+
35
+ return wrapper
36
+
37
+ @classmethod
38
+ def _do_register(cls, from_type: Type, converter: Any):
39
+ cls.registry[from_type] = converter # pyre-ignore[16]
40
+
41
+ @classmethod
42
+ def _lookup_converter(cls, from_type: Type) -> Any:
43
+ """
44
+ Perform recursive lookup for the given type
45
+ to find registered converter. If a converter was found for some base
46
+ class, it gets registered for this class to save on further lookups.
47
+
48
+ Args:
49
+ from_type: type for which to find a converter
50
+ Return:
51
+ callable or None - registered converter or None
52
+ if no suitable entry was found in the registry
53
+ """
54
+ if from_type in cls.registry: # pyre-ignore[16]
55
+ return cls.registry[from_type]
56
+ for base in from_type.__bases__:
57
+ converter = cls._lookup_converter(base)
58
+ if converter is not None:
59
+ cls._do_register(from_type, converter)
60
+ return converter
61
+ return None
62
+
63
+ @classmethod
64
+ def convert(cls, instance: Any, *args, **kwargs):
65
+ """
66
+ Convert an instance to the destination type using some registered
67
+ converter. Does recursive lookup for base classes, so there's no need
68
+ for explicit registration for derived classes.
69
+
70
+ Args:
71
+ instance: source instance to convert to the destination type
72
+ Return:
73
+ An instance of the destination type obtained from the source instance
74
+ Raises KeyError, if no suitable converter found
75
+ """
76
+ instance_type = type(instance)
77
+ converter = cls._lookup_converter(instance_type)
78
+ if converter is None:
79
+ if cls.dst_type is None: # pyre-ignore[16]
80
+ output_type_str = "itself"
81
+ else:
82
+ output_type_str = cls.dst_type
83
+ raise KeyError(f"Could not find converter from {instance_type} to {output_type_str}")
84
+ return converter(instance, *args, **kwargs)
85
+
86
+
87
+ IntTupleBox = Tuple[int, int, int, int]
88
+
89
+
90
+ def make_int_box(box: torch.Tensor) -> IntTupleBox:
91
+ int_box = [0, 0, 0, 0]
92
+ int_box[0], int_box[1], int_box[2], int_box[3] = tuple(box.long().tolist())
93
+ return int_box[0], int_box[1], int_box[2], int_box[3]
densepose/converters/builtin.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from ..structures import DensePoseChartPredictorOutput, DensePoseEmbeddingPredictorOutput
4
+ from . import (
5
+ HFlipConverter,
6
+ ToChartResultConverter,
7
+ ToChartResultConverterWithConfidences,
8
+ ToMaskConverter,
9
+ densepose_chart_predictor_output_hflip,
10
+ densepose_chart_predictor_output_to_result,
11
+ densepose_chart_predictor_output_to_result_with_confidences,
12
+ predictor_output_with_coarse_segm_to_mask,
13
+ predictor_output_with_fine_and_coarse_segm_to_mask,
14
+ )
15
+
16
+ ToMaskConverter.register(
17
+ DensePoseChartPredictorOutput, predictor_output_with_fine_and_coarse_segm_to_mask
18
+ )
19
+ ToMaskConverter.register(
20
+ DensePoseEmbeddingPredictorOutput, predictor_output_with_coarse_segm_to_mask
21
+ )
22
+
23
+ ToChartResultConverter.register(
24
+ DensePoseChartPredictorOutput, densepose_chart_predictor_output_to_result
25
+ )
26
+
27
+ ToChartResultConverterWithConfidences.register(
28
+ DensePoseChartPredictorOutput, densepose_chart_predictor_output_to_result_with_confidences
29
+ )
30
+
31
+ HFlipConverter.register(DensePoseChartPredictorOutput, densepose_chart_predictor_output_hflip)
densepose/converters/chart_output_hflip.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ from dataclasses import fields
3
+ import torch
4
+
5
+ from densepose.structures import DensePoseChartPredictorOutput, DensePoseTransformData
6
+
7
+
8
+ def densepose_chart_predictor_output_hflip(
9
+ densepose_predictor_output: DensePoseChartPredictorOutput,
10
+ transform_data: DensePoseTransformData,
11
+ ) -> DensePoseChartPredictorOutput:
12
+ """
13
+ Change to take into account a Horizontal flip.
14
+ """
15
+ if len(densepose_predictor_output) > 0:
16
+
17
+ PredictorOutput = type(densepose_predictor_output)
18
+ output_dict = {}
19
+
20
+ for field in fields(densepose_predictor_output):
21
+ field_value = getattr(densepose_predictor_output, field.name)
22
+ # flip tensors
23
+ if isinstance(field_value, torch.Tensor):
24
+ setattr(densepose_predictor_output, field.name, torch.flip(field_value, [3]))
25
+
26
+ densepose_predictor_output = _flip_iuv_semantics_tensor(
27
+ densepose_predictor_output, transform_data
28
+ )
29
+ densepose_predictor_output = _flip_segm_semantics_tensor(
30
+ densepose_predictor_output, transform_data
31
+ )
32
+
33
+ for field in fields(densepose_predictor_output):
34
+ output_dict[field.name] = getattr(densepose_predictor_output, field.name)
35
+
36
+ return PredictorOutput(**output_dict)
37
+ else:
38
+ return densepose_predictor_output
39
+
40
+
41
+ def _flip_iuv_semantics_tensor(
42
+ densepose_predictor_output: DensePoseChartPredictorOutput,
43
+ dp_transform_data: DensePoseTransformData,
44
+ ) -> DensePoseChartPredictorOutput:
45
+ point_label_symmetries = dp_transform_data.point_label_symmetries
46
+ uv_symmetries = dp_transform_data.uv_symmetries
47
+
48
+ N, C, H, W = densepose_predictor_output.u.shape
49
+ u_loc = (densepose_predictor_output.u[:, 1:, :, :].clamp(0, 1) * 255).long()
50
+ v_loc = (densepose_predictor_output.v[:, 1:, :, :].clamp(0, 1) * 255).long()
51
+ Iindex = torch.arange(C - 1, device=densepose_predictor_output.u.device)[
52
+ None, :, None, None
53
+ ].expand(N, C - 1, H, W)
54
+ densepose_predictor_output.u[:, 1:, :, :] = uv_symmetries["U_transforms"][Iindex, v_loc, u_loc]
55
+ densepose_predictor_output.v[:, 1:, :, :] = uv_symmetries["V_transforms"][Iindex, v_loc, u_loc]
56
+
57
+ for el in ["fine_segm", "u", "v"]:
58
+ densepose_predictor_output.__dict__[el] = densepose_predictor_output.__dict__[el][
59
+ :, point_label_symmetries, :, :
60
+ ]
61
+ return densepose_predictor_output
62
+
63
+
64
+ def _flip_segm_semantics_tensor(
65
+ densepose_predictor_output: DensePoseChartPredictorOutput, dp_transform_data
66
+ ):
67
+ if densepose_predictor_output.coarse_segm.shape[1] > 2:
68
+ densepose_predictor_output.coarse_segm = densepose_predictor_output.coarse_segm[
69
+ :, dp_transform_data.mask_label_symmetries, :, :
70
+ ]
71
+ return densepose_predictor_output
densepose/converters/chart_output_to_chart_result.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Dict
4
+ import torch
5
+ from torch.nn import functional as F
6
+
7
+ from detectron2.structures.boxes import Boxes, BoxMode
8
+
9
+ from ..structures import (
10
+ DensePoseChartPredictorOutput,
11
+ DensePoseChartResult,
12
+ DensePoseChartResultWithConfidences,
13
+ )
14
+ from . import resample_fine_and_coarse_segm_to_bbox
15
+ from .base import IntTupleBox, make_int_box
16
+
17
+
18
+ def resample_uv_tensors_to_bbox(
19
+ u: torch.Tensor,
20
+ v: torch.Tensor,
21
+ labels: torch.Tensor,
22
+ box_xywh_abs: IntTupleBox,
23
+ ) -> torch.Tensor:
24
+ """
25
+ Resamples U and V coordinate estimates for the given bounding box
26
+
27
+ Args:
28
+ u (tensor [1, C, H, W] of float): U coordinates
29
+ v (tensor [1, C, H, W] of float): V coordinates
30
+ labels (tensor [H, W] of long): labels obtained by resampling segmentation
31
+ outputs for the given bounding box
32
+ box_xywh_abs (tuple of 4 int): bounding box that corresponds to predictor outputs
33
+ Return:
34
+ Resampled U and V coordinates - a tensor [2, H, W] of float
35
+ """
36
+ x, y, w, h = box_xywh_abs
37
+ w = max(int(w), 1)
38
+ h = max(int(h), 1)
39
+ u_bbox = F.interpolate(u, (h, w), mode="bilinear", align_corners=False)
40
+ v_bbox = F.interpolate(v, (h, w), mode="bilinear", align_corners=False)
41
+ uv = torch.zeros([2, h, w], dtype=torch.float32, device=u.device)
42
+ for part_id in range(1, u_bbox.size(1)):
43
+ uv[0][labels == part_id] = u_bbox[0, part_id][labels == part_id]
44
+ uv[1][labels == part_id] = v_bbox[0, part_id][labels == part_id]
45
+ return uv
46
+
47
+
48
+ def resample_uv_to_bbox(
49
+ predictor_output: DensePoseChartPredictorOutput,
50
+ labels: torch.Tensor,
51
+ box_xywh_abs: IntTupleBox,
52
+ ) -> torch.Tensor:
53
+ """
54
+ Resamples U and V coordinate estimates for the given bounding box
55
+
56
+ Args:
57
+ predictor_output (DensePoseChartPredictorOutput): DensePose predictor
58
+ output to be resampled
59
+ labels (tensor [H, W] of long): labels obtained by resampling segmentation
60
+ outputs for the given bounding box
61
+ box_xywh_abs (tuple of 4 int): bounding box that corresponds to predictor outputs
62
+ Return:
63
+ Resampled U and V coordinates - a tensor [2, H, W] of float
64
+ """
65
+ return resample_uv_tensors_to_bbox(
66
+ predictor_output.u,
67
+ predictor_output.v,
68
+ labels,
69
+ box_xywh_abs,
70
+ )
71
+
72
+
73
+ def densepose_chart_predictor_output_to_result(
74
+ predictor_output: DensePoseChartPredictorOutput, boxes: Boxes
75
+ ) -> DensePoseChartResult:
76
+ """
77
+ Convert densepose chart predictor outputs to results
78
+
79
+ Args:
80
+ predictor_output (DensePoseChartPredictorOutput): DensePose predictor
81
+ output to be converted to results, must contain only 1 output
82
+ boxes (Boxes): bounding box that corresponds to the predictor output,
83
+ must contain only 1 bounding box
84
+ Return:
85
+ DensePose chart-based result (DensePoseChartResult)
86
+ """
87
+ assert len(predictor_output) == 1 and len(boxes) == 1, (
88
+ f"Predictor output to result conversion can operate only single outputs"
89
+ f", got {len(predictor_output)} predictor outputs and {len(boxes)} boxes"
90
+ )
91
+
92
+ boxes_xyxy_abs = boxes.tensor.clone()
93
+ boxes_xywh_abs = BoxMode.convert(boxes_xyxy_abs, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
94
+ box_xywh = make_int_box(boxes_xywh_abs[0])
95
+
96
+ labels = resample_fine_and_coarse_segm_to_bbox(predictor_output, box_xywh).squeeze(0)
97
+ uv = resample_uv_to_bbox(predictor_output, labels, box_xywh)
98
+ return DensePoseChartResult(labels=labels, uv=uv)
99
+
100
+
101
+ def resample_confidences_to_bbox(
102
+ predictor_output: DensePoseChartPredictorOutput,
103
+ labels: torch.Tensor,
104
+ box_xywh_abs: IntTupleBox,
105
+ ) -> Dict[str, torch.Tensor]:
106
+ """
107
+ Resamples confidences for the given bounding box
108
+
109
+ Args:
110
+ predictor_output (DensePoseChartPredictorOutput): DensePose predictor
111
+ output to be resampled
112
+ labels (tensor [H, W] of long): labels obtained by resampling segmentation
113
+ outputs for the given bounding box
114
+ box_xywh_abs (tuple of 4 int): bounding box that corresponds to predictor outputs
115
+ Return:
116
+ Resampled confidences - a dict of [H, W] tensors of float
117
+ """
118
+
119
+ x, y, w, h = box_xywh_abs
120
+ w = max(int(w), 1)
121
+ h = max(int(h), 1)
122
+
123
+ confidence_names = [
124
+ "sigma_1",
125
+ "sigma_2",
126
+ "kappa_u",
127
+ "kappa_v",
128
+ "fine_segm_confidence",
129
+ "coarse_segm_confidence",
130
+ ]
131
+ confidence_results = {key: None for key in confidence_names}
132
+ confidence_names = [
133
+ key for key in confidence_names if getattr(predictor_output, key) is not None
134
+ ]
135
+ confidence_base = torch.zeros([h, w], dtype=torch.float32, device=predictor_output.u.device)
136
+
137
+ # assign data from channels that correspond to the labels
138
+ for key in confidence_names:
139
+ resampled_confidence = F.interpolate(
140
+ getattr(predictor_output, key),
141
+ (h, w),
142
+ mode="bilinear",
143
+ align_corners=False,
144
+ )
145
+ result = confidence_base.clone()
146
+ for part_id in range(1, predictor_output.u.size(1)):
147
+ if resampled_confidence.size(1) != predictor_output.u.size(1):
148
+ # confidence is not part-based, don't try to fill it part by part
149
+ continue
150
+ result[labels == part_id] = resampled_confidence[0, part_id][labels == part_id]
151
+
152
+ if resampled_confidence.size(1) != predictor_output.u.size(1):
153
+ # confidence is not part-based, fill the data with the first channel
154
+ # (targeted for segmentation confidences that have only 1 channel)
155
+ result = resampled_confidence[0, 0]
156
+
157
+ confidence_results[key] = result
158
+
159
+ return confidence_results # pyre-ignore[7]
160
+
161
+
162
+ def densepose_chart_predictor_output_to_result_with_confidences(
163
+ predictor_output: DensePoseChartPredictorOutput, boxes: Boxes
164
+ ) -> DensePoseChartResultWithConfidences:
165
+ """
166
+ Convert densepose chart predictor outputs to results
167
+
168
+ Args:
169
+ predictor_output (DensePoseChartPredictorOutput): DensePose predictor
170
+ output with confidences to be converted to results, must contain only 1 output
171
+ boxes (Boxes): bounding box that corresponds to the predictor output,
172
+ must contain only 1 bounding box
173
+ Return:
174
+ DensePose chart-based result with confidences (DensePoseChartResultWithConfidences)
175
+ """
176
+ assert len(predictor_output) == 1 and len(boxes) == 1, (
177
+ f"Predictor output to result conversion can operate only single outputs"
178
+ f", got {len(predictor_output)} predictor outputs and {len(boxes)} boxes"
179
+ )
180
+
181
+ boxes_xyxy_abs = boxes.tensor.clone()
182
+ boxes_xywh_abs = BoxMode.convert(boxes_xyxy_abs, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
183
+ box_xywh = make_int_box(boxes_xywh_abs[0])
184
+
185
+ labels = resample_fine_and_coarse_segm_to_bbox(predictor_output, box_xywh).squeeze(0)
186
+ uv = resample_uv_to_bbox(predictor_output, labels, box_xywh)
187
+ confidences = resample_confidences_to_bbox(predictor_output, labels, box_xywh)
188
+ return DensePoseChartResultWithConfidences(labels=labels, uv=uv, **confidences)
densepose/converters/hflip.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Any
4
+
5
+ from .base import BaseConverter
6
+
7
+
8
+ class HFlipConverter(BaseConverter):
9
+ """
10
+ Converts various DensePose predictor outputs to DensePose results.
11
+ Each DensePose predictor output type has to register its convertion strategy.
12
+ """
13
+
14
+ registry = {}
15
+ dst_type = None
16
+
17
+ @classmethod
18
+ # pyre-fixme[14]: `convert` overrides method defined in `BaseConverter`
19
+ # inconsistently.
20
+ def convert(cls, predictor_outputs: Any, transform_data: Any, *args, **kwargs):
21
+ """
22
+ Performs an horizontal flip on DensePose predictor outputs.
23
+ Does recursive lookup for base classes, so there's no need
24
+ for explicit registration for derived classes.
25
+
26
+ Args:
27
+ predictor_outputs: DensePose predictor output to be converted to BitMasks
28
+ transform_data: Anything useful for the flip
29
+ Return:
30
+ An instance of the same type as predictor_outputs
31
+ """
32
+ return super(HFlipConverter, cls).convert(
33
+ predictor_outputs, transform_data, *args, **kwargs
34
+ )
densepose/converters/segm_to_mask.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Any
4
+ import torch
5
+ from torch.nn import functional as F
6
+
7
+ from detectron2.structures import BitMasks, Boxes, BoxMode
8
+
9
+ from .base import IntTupleBox, make_int_box
10
+ from .to_mask import ImageSizeType
11
+
12
+
13
+ def resample_coarse_segm_tensor_to_bbox(coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox):
14
+ """
15
+ Resample coarse segmentation tensor to the given
16
+ bounding box and derive labels for each pixel of the bounding box
17
+
18
+ Args:
19
+ coarse_segm: float tensor of shape [1, K, Hout, Wout]
20
+ box_xywh_abs (tuple of 4 int): bounding box given by its upper-left
21
+ corner coordinates, width (W) and height (H)
22
+ Return:
23
+ Labels for each pixel of the bounding box, a long tensor of size [1, H, W]
24
+ """
25
+ x, y, w, h = box_xywh_abs
26
+ w = max(int(w), 1)
27
+ h = max(int(h), 1)
28
+ labels = F.interpolate(coarse_segm, (h, w), mode="bilinear", align_corners=False).argmax(dim=1)
29
+ return labels
30
+
31
+
32
+ def resample_fine_and_coarse_segm_tensors_to_bbox(
33
+ fine_segm: torch.Tensor, coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox
34
+ ):
35
+ """
36
+ Resample fine and coarse segmentation tensors to the given
37
+ bounding box and derive labels for each pixel of the bounding box
38
+
39
+ Args:
40
+ fine_segm: float tensor of shape [1, C, Hout, Wout]
41
+ coarse_segm: float tensor of shape [1, K, Hout, Wout]
42
+ box_xywh_abs (tuple of 4 int): bounding box given by its upper-left
43
+ corner coordinates, width (W) and height (H)
44
+ Return:
45
+ Labels for each pixel of the bounding box, a long tensor of size [1, H, W]
46
+ """
47
+ x, y, w, h = box_xywh_abs
48
+ w = max(int(w), 1)
49
+ h = max(int(h), 1)
50
+ # coarse segmentation
51
+ coarse_segm_bbox = F.interpolate(
52
+ coarse_segm,
53
+ (h, w),
54
+ mode="bilinear",
55
+ align_corners=False,
56
+ ).argmax(dim=1)
57
+ # combined coarse and fine segmentation
58
+ labels = (
59
+ F.interpolate(fine_segm, (h, w), mode="bilinear", align_corners=False).argmax(dim=1)
60
+ * (coarse_segm_bbox > 0).long()
61
+ )
62
+ return labels
63
+
64
+
65
+ def resample_fine_and_coarse_segm_to_bbox(predictor_output: Any, box_xywh_abs: IntTupleBox):
66
+ """
67
+ Resample fine and coarse segmentation outputs from a predictor to the given
68
+ bounding box and derive labels for each pixel of the bounding box
69
+
70
+ Args:
71
+ predictor_output: DensePose predictor output that contains segmentation
72
+ results to be resampled
73
+ box_xywh_abs (tuple of 4 int): bounding box given by its upper-left
74
+ corner coordinates, width (W) and height (H)
75
+ Return:
76
+ Labels for each pixel of the bounding box, a long tensor of size [1, H, W]
77
+ """
78
+ return resample_fine_and_coarse_segm_tensors_to_bbox(
79
+ predictor_output.fine_segm,
80
+ predictor_output.coarse_segm,
81
+ box_xywh_abs,
82
+ )
83
+
84
+
85
+ def predictor_output_with_coarse_segm_to_mask(
86
+ predictor_output: Any, boxes: Boxes, image_size_hw: ImageSizeType
87
+ ) -> BitMasks:
88
+ """
89
+ Convert predictor output with coarse and fine segmentation to a mask.
90
+ Assumes that predictor output has the following attributes:
91
+ - coarse_segm (tensor of size [N, D, H, W]): coarse segmentation
92
+ unnormalized scores for N instances; D is the number of coarse
93
+ segmentation labels, H and W is the resolution of the estimate
94
+
95
+ Args:
96
+ predictor_output: DensePose predictor output to be converted to mask
97
+ boxes (Boxes): bounding boxes that correspond to the DensePose
98
+ predictor outputs
99
+ image_size_hw (tuple [int, int]): image height Himg and width Wimg
100
+ Return:
101
+ BitMasks that contain a bool tensor of size [N, Himg, Wimg] with
102
+ a mask of the size of the image for each instance
103
+ """
104
+ H, W = image_size_hw
105
+ boxes_xyxy_abs = boxes.tensor.clone()
106
+ boxes_xywh_abs = BoxMode.convert(boxes_xyxy_abs, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
107
+ N = len(boxes_xywh_abs)
108
+ masks = torch.zeros((N, H, W), dtype=torch.bool, device=boxes.tensor.device)
109
+ for i in range(len(boxes_xywh_abs)):
110
+ box_xywh = make_int_box(boxes_xywh_abs[i])
111
+ box_mask = resample_coarse_segm_tensor_to_bbox(predictor_output[i].coarse_segm, box_xywh)
112
+ x, y, w, h = box_xywh
113
+ masks[i, y : y + h, x : x + w] = box_mask
114
+
115
+ return BitMasks(masks)
116
+
117
+
118
+ def predictor_output_with_fine_and_coarse_segm_to_mask(
119
+ predictor_output: Any, boxes: Boxes, image_size_hw: ImageSizeType
120
+ ) -> BitMasks:
121
+ """
122
+ Convert predictor output with coarse and fine segmentation to a mask.
123
+ Assumes that predictor output has the following attributes:
124
+ - coarse_segm (tensor of size [N, D, H, W]): coarse segmentation
125
+ unnormalized scores for N instances; D is the number of coarse
126
+ segmentation labels, H and W is the resolution of the estimate
127
+ - fine_segm (tensor of size [N, C, H, W]): fine segmentation
128
+ unnormalized scores for N instances; C is the number of fine
129
+ segmentation labels, H and W is the resolution of the estimate
130
+
131
+ Args:
132
+ predictor_output: DensePose predictor output to be converted to mask
133
+ boxes (Boxes): bounding boxes that correspond to the DensePose
134
+ predictor outputs
135
+ image_size_hw (tuple [int, int]): image height Himg and width Wimg
136
+ Return:
137
+ BitMasks that contain a bool tensor of size [N, Himg, Wimg] with
138
+ a mask of the size of the image for each instance
139
+ """
140
+ H, W = image_size_hw
141
+ boxes_xyxy_abs = boxes.tensor.clone()
142
+ boxes_xywh_abs = BoxMode.convert(boxes_xyxy_abs, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
143
+ N = len(boxes_xywh_abs)
144
+ masks = torch.zeros((N, H, W), dtype=torch.bool, device=boxes.tensor.device)
145
+ for i in range(len(boxes_xywh_abs)):
146
+ box_xywh = make_int_box(boxes_xywh_abs[i])
147
+ labels_i = resample_fine_and_coarse_segm_to_bbox(predictor_output[i], box_xywh)
148
+ x, y, w, h = box_xywh
149
+ masks[i, y : y + h, x : x + w] = labels_i > 0
150
+ return BitMasks(masks)
densepose/converters/to_chart_result.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Any
4
+
5
+ from detectron2.structures import Boxes
6
+
7
+ from ..structures import DensePoseChartResult, DensePoseChartResultWithConfidences
8
+ from .base import BaseConverter
9
+
10
+
11
+ class ToChartResultConverter(BaseConverter):
12
+ """
13
+ Converts various DensePose predictor outputs to DensePose results.
14
+ Each DensePose predictor output type has to register its convertion strategy.
15
+ """
16
+
17
+ registry = {}
18
+ dst_type = DensePoseChartResult
19
+
20
+ @classmethod
21
+ # pyre-fixme[14]: `convert` overrides method defined in `BaseConverter`
22
+ # inconsistently.
23
+ def convert(cls, predictor_outputs: Any, boxes: Boxes, *args, **kwargs) -> DensePoseChartResult:
24
+ """
25
+ Convert DensePose predictor outputs to DensePoseResult using some registered
26
+ converter. Does recursive lookup for base classes, so there's no need
27
+ for explicit registration for derived classes.
28
+
29
+ Args:
30
+ densepose_predictor_outputs: DensePose predictor output to be
31
+ converted to BitMasks
32
+ boxes (Boxes): bounding boxes that correspond to the DensePose
33
+ predictor outputs
34
+ Return:
35
+ An instance of DensePoseResult. If no suitable converter was found, raises KeyError
36
+ """
37
+ return super(ToChartResultConverter, cls).convert(predictor_outputs, boxes, *args, **kwargs)
38
+
39
+
40
+ class ToChartResultConverterWithConfidences(BaseConverter):
41
+ """
42
+ Converts various DensePose predictor outputs to DensePose results.
43
+ Each DensePose predictor output type has to register its convertion strategy.
44
+ """
45
+
46
+ registry = {}
47
+ dst_type = DensePoseChartResultWithConfidences
48
+
49
+ @classmethod
50
+ # pyre-fixme[14]: `convert` overrides method defined in `BaseConverter`
51
+ # inconsistently.
52
+ def convert(
53
+ cls, predictor_outputs: Any, boxes: Boxes, *args, **kwargs
54
+ ) -> DensePoseChartResultWithConfidences:
55
+ """
56
+ Convert DensePose predictor outputs to DensePoseResult with confidences
57
+ using some registered converter. Does recursive lookup for base classes,
58
+ so there's no need for explicit registration for derived classes.
59
+
60
+ Args:
61
+ densepose_predictor_outputs: DensePose predictor output with confidences
62
+ to be converted to BitMasks
63
+ boxes (Boxes): bounding boxes that correspond to the DensePose
64
+ predictor outputs
65
+ Return:
66
+ An instance of DensePoseResult. If no suitable converter was found, raises KeyError
67
+ """
68
+ return super(ToChartResultConverterWithConfidences, cls).convert(
69
+ predictor_outputs, boxes, *args, **kwargs
70
+ )
densepose/converters/to_mask.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from typing import Any, Tuple
4
+
5
+ from detectron2.structures import BitMasks, Boxes
6
+
7
+ from .base import BaseConverter
8
+
9
+ ImageSizeType = Tuple[int, int]
10
+
11
+
12
+ class ToMaskConverter(BaseConverter):
13
+ """
14
+ Converts various DensePose predictor outputs to masks
15
+ in bit mask format (see `BitMasks`). Each DensePose predictor output type
16
+ has to register its convertion strategy.
17
+ """
18
+
19
+ registry = {}
20
+ dst_type = BitMasks
21
+
22
+ @classmethod
23
+ # pyre-fixme[14]: `convert` overrides method defined in `BaseConverter`
24
+ # inconsistently.
25
+ def convert(
26
+ cls,
27
+ densepose_predictor_outputs: Any,
28
+ boxes: Boxes,
29
+ image_size_hw: ImageSizeType,
30
+ *args,
31
+ **kwargs
32
+ ) -> BitMasks:
33
+ """
34
+ Convert DensePose predictor outputs to BitMasks using some registered
35
+ converter. Does recursive lookup for base classes, so there's no need
36
+ for explicit registration for derived classes.
37
+
38
+ Args:
39
+ densepose_predictor_outputs: DensePose predictor output to be
40
+ converted to BitMasks
41
+ boxes (Boxes): bounding boxes that correspond to the DensePose
42
+ predictor outputs
43
+ image_size_hw (tuple [int, int]): image height and width
44
+ Return:
45
+ An instance of `BitMasks`. If no suitable converter was found, raises KeyError
46
+ """
47
+ return super(ToMaskConverter, cls).convert(
48
+ densepose_predictor_outputs, boxes, image_size_hw, *args, **kwargs
49
+ )
densepose/data/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ from .meshes import builtin
4
+ from .build import (
5
+ build_detection_test_loader,
6
+ build_detection_train_loader,
7
+ build_combined_loader,
8
+ build_frame_selector,
9
+ build_inference_based_loaders,
10
+ has_inference_based_loaders,
11
+ BootstrapDatasetFactoryCatalog,
12
+ )
13
+ from .combined_loader import CombinedDataLoader
14
+ from .dataset_mapper import DatasetMapper
15
+ from .inference_based_loader import InferenceBasedLoader, ScoreBasedFilter
16
+ from .image_list_dataset import ImageListDataset
17
+ from .utils import is_relative_local_path, maybe_prepend_base_path
18
+
19
+ # ensure the builtin datasets are registered
20
+ from . import datasets
21
+
22
+ # ensure the bootstrap datasets builders are registered
23
+ from . import build
24
+
25
+ __all__ = [k for k in globals().keys() if not k.startswith("_")]
densepose/data/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
densepose/data/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (1.05 kB). View file
 
densepose/data/__pycache__/build.cpython-310.pyc ADDED
Binary file (23.8 kB). View file
 
densepose/data/__pycache__/build.cpython-38.pyc ADDED
Binary file (23.8 kB). View file
 
densepose/data/__pycache__/combined_loader.cpython-310.pyc ADDED
Binary file (1.84 kB). View file
 
densepose/data/__pycache__/combined_loader.cpython-38.pyc ADDED
Binary file (1.82 kB). View file
 
densepose/data/__pycache__/dataset_mapper.cpython-310.pyc ADDED
Binary file (5.44 kB). View file
 
densepose/data/__pycache__/dataset_mapper.cpython-38.pyc ADDED
Binary file (5.45 kB). View file
 
densepose/data/__pycache__/image_list_dataset.cpython-310.pyc ADDED
Binary file (2.67 kB). View file
 
densepose/data/__pycache__/image_list_dataset.cpython-38.pyc ADDED
Binary file (2.67 kB). View file
 
densepose/data/__pycache__/inference_based_loader.cpython-310.pyc ADDED
Binary file (5.87 kB). View file
 
densepose/data/__pycache__/inference_based_loader.cpython-38.pyc ADDED
Binary file (5.77 kB). View file
 
densepose/data/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
densepose/data/__pycache__/utils.cpython-38.pyc ADDED
Binary file (1.63 kB). View file
 
densepose/data/build.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ import itertools
4
+ import logging
5
+ import numpy as np
6
+ from collections import UserDict, defaultdict
7
+ from dataclasses import dataclass
8
+ from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, Sequence, Tuple
9
+ import torch
10
+ from torch.utils.data.dataset import Dataset
11
+
12
+ from detectron2.config import CfgNode
13
+ from detectron2.data.build import build_detection_test_loader as d2_build_detection_test_loader
14
+ from detectron2.data.build import build_detection_train_loader as d2_build_detection_train_loader
15
+ from detectron2.data.build import (
16
+ load_proposals_into_dataset,
17
+ print_instances_class_histogram,
18
+ trivial_batch_collator,
19
+ worker_init_reset_seed,
20
+ )
21
+ from detectron2.data.catalog import DatasetCatalog, Metadata, MetadataCatalog
22
+ from detectron2.data.samplers import TrainingSampler
23
+ from detectron2.utils.comm import get_world_size
24
+
25
+ from densepose.config import get_bootstrap_dataset_config
26
+ from densepose.modeling import build_densepose_embedder
27
+
28
+ from .combined_loader import CombinedDataLoader, Loader
29
+ from .dataset_mapper import DatasetMapper
30
+ from .datasets.coco import DENSEPOSE_CSE_KEYS_WITHOUT_MASK, DENSEPOSE_IUV_KEYS_WITHOUT_MASK
31
+ from .datasets.dataset_type import DatasetType
32
+ from .inference_based_loader import InferenceBasedLoader, ScoreBasedFilter
33
+ from .samplers import (
34
+ DensePoseConfidenceBasedSampler,
35
+ DensePoseCSEConfidenceBasedSampler,
36
+ DensePoseCSEUniformSampler,
37
+ DensePoseUniformSampler,
38
+ MaskFromDensePoseSampler,
39
+ PredictionToGroundTruthSampler,
40
+ )
41
+ from .transform import ImageResizeTransform
42
+ from .utils import get_category_to_class_mapping, get_class_to_mesh_name_mapping
43
+ from .video import (
44
+ FirstKFramesSelector,
45
+ FrameSelectionStrategy,
46
+ LastKFramesSelector,
47
+ RandomKFramesSelector,
48
+ VideoKeyframeDataset,
49
+ video_list_from_file,
50
+ )
51
+
52
+ __all__ = ["build_detection_train_loader", "build_detection_test_loader"]
53
+
54
+
55
+ Instance = Dict[str, Any]
56
+ InstancePredicate = Callable[[Instance], bool]
57
+
58
+
59
+ def _compute_num_images_per_worker(cfg: CfgNode) -> int:
60
+ num_workers = get_world_size()
61
+ images_per_batch = cfg.SOLVER.IMS_PER_BATCH
62
+ assert (
63
+ images_per_batch % num_workers == 0
64
+ ), "SOLVER.IMS_PER_BATCH ({}) must be divisible by the number of workers ({}).".format(
65
+ images_per_batch, num_workers
66
+ )
67
+ assert (
68
+ images_per_batch >= num_workers
69
+ ), "SOLVER.IMS_PER_BATCH ({}) must be larger than the number of workers ({}).".format(
70
+ images_per_batch, num_workers
71
+ )
72
+ images_per_worker = images_per_batch // num_workers
73
+ return images_per_worker
74
+
75
+
76
+ def _map_category_id_to_contiguous_id(dataset_name: str, dataset_dicts: Iterable[Instance]) -> None:
77
+ meta = MetadataCatalog.get(dataset_name)
78
+ for dataset_dict in dataset_dicts:
79
+ for ann in dataset_dict["annotations"]:
80
+ ann["category_id"] = meta.thing_dataset_id_to_contiguous_id[ann["category_id"]]
81
+
82
+
83
+ @dataclass
84
+ class _DatasetCategory:
85
+ """
86
+ Class representing category data in a dataset:
87
+ - id: category ID, as specified in the dataset annotations file
88
+ - name: category name, as specified in the dataset annotations file
89
+ - mapped_id: category ID after applying category maps (DATASETS.CATEGORY_MAPS config option)
90
+ - mapped_name: category name after applying category maps
91
+ - dataset_name: dataset in which the category is defined
92
+
93
+ For example, when training models in a class-agnostic manner, one could take LVIS 1.0
94
+ dataset and map the animal categories to the same category as human data from COCO:
95
+ id = 225
96
+ name = "cat"
97
+ mapped_id = 1
98
+ mapped_name = "person"
99
+ dataset_name = "lvis_v1_animals_dp_train"
100
+ """
101
+
102
+ id: int
103
+ name: str
104
+ mapped_id: int
105
+ mapped_name: str
106
+ dataset_name: str
107
+
108
+
109
+ _MergedCategoriesT = Dict[int, List[_DatasetCategory]]
110
+
111
+
112
+ def _add_category_id_to_contiguous_id_maps_to_metadata(
113
+ merged_categories: _MergedCategoriesT,
114
+ ) -> None:
115
+ merged_categories_per_dataset = {}
116
+ for contiguous_cat_id, cat_id in enumerate(sorted(merged_categories.keys())):
117
+ for cat in merged_categories[cat_id]:
118
+ if cat.dataset_name not in merged_categories_per_dataset:
119
+ merged_categories_per_dataset[cat.dataset_name] = defaultdict(list)
120
+ merged_categories_per_dataset[cat.dataset_name][cat_id].append(
121
+ (
122
+ contiguous_cat_id,
123
+ cat,
124
+ )
125
+ )
126
+
127
+ logger = logging.getLogger(__name__)
128
+ for dataset_name, merged_categories in merged_categories_per_dataset.items():
129
+ meta = MetadataCatalog.get(dataset_name)
130
+ if not hasattr(meta, "thing_classes"):
131
+ meta.thing_classes = []
132
+ meta.thing_dataset_id_to_contiguous_id = {}
133
+ meta.thing_dataset_id_to_merged_id = {}
134
+ else:
135
+ meta.thing_classes.clear()
136
+ meta.thing_dataset_id_to_contiguous_id.clear()
137
+ meta.thing_dataset_id_to_merged_id.clear()
138
+ logger.info(f"Dataset {dataset_name}: category ID to contiguous ID mapping:")
139
+ for _cat_id, categories in sorted(merged_categories.items()):
140
+ added_to_thing_classes = False
141
+ for contiguous_cat_id, cat in categories:
142
+ if not added_to_thing_classes:
143
+ meta.thing_classes.append(cat.mapped_name)
144
+ added_to_thing_classes = True
145
+ meta.thing_dataset_id_to_contiguous_id[cat.id] = contiguous_cat_id
146
+ meta.thing_dataset_id_to_merged_id[cat.id] = cat.mapped_id
147
+ logger.info(f"{cat.id} ({cat.name}) -> {contiguous_cat_id}")
148
+
149
+
150
+ def _maybe_create_general_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
151
+ def has_annotations(instance: Instance) -> bool:
152
+ return "annotations" in instance
153
+
154
+ def has_only_crowd_anotations(instance: Instance) -> bool:
155
+ for ann in instance["annotations"]:
156
+ if ann.get("is_crowd", 0) == 0:
157
+ return False
158
+ return True
159
+
160
+ def general_keep_instance_predicate(instance: Instance) -> bool:
161
+ return has_annotations(instance) and not has_only_crowd_anotations(instance)
162
+
163
+ if not cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS:
164
+ return None
165
+ return general_keep_instance_predicate
166
+
167
+
168
+ def _maybe_create_keypoints_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
169
+
170
+ min_num_keypoints = cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE
171
+
172
+ def has_sufficient_num_keypoints(instance: Instance) -> bool:
173
+ num_kpts = sum(
174
+ (np.array(ann["keypoints"][2::3]) > 0).sum()
175
+ for ann in instance["annotations"]
176
+ if "keypoints" in ann
177
+ )
178
+ return num_kpts >= min_num_keypoints
179
+
180
+ if cfg.MODEL.KEYPOINT_ON and (min_num_keypoints > 0):
181
+ return has_sufficient_num_keypoints
182
+ return None
183
+
184
+
185
+ def _maybe_create_mask_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
186
+ if not cfg.MODEL.MASK_ON:
187
+ return None
188
+
189
+ def has_mask_annotations(instance: Instance) -> bool:
190
+ return any("segmentation" in ann for ann in instance["annotations"])
191
+
192
+ return has_mask_annotations
193
+
194
+
195
+ def _maybe_create_densepose_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
196
+ if not cfg.MODEL.DENSEPOSE_ON:
197
+ return None
198
+
199
+ use_masks = cfg.MODEL.ROI_DENSEPOSE_HEAD.COARSE_SEGM_TRAINED_BY_MASKS
200
+
201
+ def has_densepose_annotations(instance: Instance) -> bool:
202
+ for ann in instance["annotations"]:
203
+ if all(key in ann for key in DENSEPOSE_IUV_KEYS_WITHOUT_MASK) or all(
204
+ key in ann for key in DENSEPOSE_CSE_KEYS_WITHOUT_MASK
205
+ ):
206
+ return True
207
+ if use_masks and "segmentation" in ann:
208
+ return True
209
+ return False
210
+
211
+ return has_densepose_annotations
212
+
213
+
214
+ def _maybe_create_specific_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
215
+ specific_predicate_creators = [
216
+ _maybe_create_keypoints_keep_instance_predicate,
217
+ _maybe_create_mask_keep_instance_predicate,
218
+ _maybe_create_densepose_keep_instance_predicate,
219
+ ]
220
+ predicates = [creator(cfg) for creator in specific_predicate_creators]
221
+ predicates = [p for p in predicates if p is not None]
222
+ if not predicates:
223
+ return None
224
+
225
+ def combined_predicate(instance: Instance) -> bool:
226
+ return any(p(instance) for p in predicates)
227
+
228
+ return combined_predicate
229
+
230
+
231
+ def _get_train_keep_instance_predicate(cfg: CfgNode):
232
+ general_keep_predicate = _maybe_create_general_keep_instance_predicate(cfg)
233
+ combined_specific_keep_predicate = _maybe_create_specific_keep_instance_predicate(cfg)
234
+
235
+ def combined_general_specific_keep_predicate(instance: Instance) -> bool:
236
+ return general_keep_predicate(instance) and combined_specific_keep_predicate(instance)
237
+
238
+ if (general_keep_predicate is None) and (combined_specific_keep_predicate is None):
239
+ return None
240
+ if general_keep_predicate is None:
241
+ return combined_specific_keep_predicate
242
+ if combined_specific_keep_predicate is None:
243
+ return general_keep_predicate
244
+ return combined_general_specific_keep_predicate
245
+
246
+
247
+ def _get_test_keep_instance_predicate(cfg: CfgNode):
248
+ general_keep_predicate = _maybe_create_general_keep_instance_predicate(cfg)
249
+ return general_keep_predicate
250
+
251
+
252
+ def _maybe_filter_and_map_categories(
253
+ dataset_name: str, dataset_dicts: List[Instance]
254
+ ) -> List[Instance]:
255
+ meta = MetadataCatalog.get(dataset_name)
256
+ category_id_map = meta.thing_dataset_id_to_contiguous_id
257
+ filtered_dataset_dicts = []
258
+ for dataset_dict in dataset_dicts:
259
+ anns = []
260
+ for ann in dataset_dict["annotations"]:
261
+ cat_id = ann["category_id"]
262
+ if cat_id not in category_id_map:
263
+ continue
264
+ ann["category_id"] = category_id_map[cat_id]
265
+ anns.append(ann)
266
+ dataset_dict["annotations"] = anns
267
+ filtered_dataset_dicts.append(dataset_dict)
268
+ return filtered_dataset_dicts
269
+
270
+
271
+ def _add_category_whitelists_to_metadata(cfg: CfgNode) -> None:
272
+ for dataset_name, whitelisted_cat_ids in cfg.DATASETS.WHITELISTED_CATEGORIES.items():
273
+ meta = MetadataCatalog.get(dataset_name)
274
+ meta.whitelisted_categories = whitelisted_cat_ids
275
+ logger = logging.getLogger(__name__)
276
+ logger.info(
277
+ "Whitelisted categories for dataset {}: {}".format(
278
+ dataset_name, meta.whitelisted_categories
279
+ )
280
+ )
281
+
282
+
283
+ def _add_category_maps_to_metadata(cfg: CfgNode) -> None:
284
+ for dataset_name, category_map in cfg.DATASETS.CATEGORY_MAPS.items():
285
+ category_map = {
286
+ int(cat_id_src): int(cat_id_dst) for cat_id_src, cat_id_dst in category_map.items()
287
+ }
288
+ meta = MetadataCatalog.get(dataset_name)
289
+ meta.category_map = category_map
290
+ logger = logging.getLogger(__name__)
291
+ logger.info("Category maps for dataset {}: {}".format(dataset_name, meta.category_map))
292
+
293
+
294
+ def _add_category_info_to_bootstrapping_metadata(dataset_name: str, dataset_cfg: CfgNode) -> None:
295
+ meta = MetadataCatalog.get(dataset_name)
296
+ meta.category_to_class_mapping = get_category_to_class_mapping(dataset_cfg)
297
+ meta.categories = dataset_cfg.CATEGORIES
298
+ meta.max_count_per_category = dataset_cfg.MAX_COUNT_PER_CATEGORY
299
+ logger = logging.getLogger(__name__)
300
+ logger.info(
301
+ "Category to class mapping for dataset {}: {}".format(
302
+ dataset_name, meta.category_to_class_mapping
303
+ )
304
+ )
305
+
306
+
307
+ def _maybe_add_class_to_mesh_name_map_to_metadata(dataset_names: List[str], cfg: CfgNode) -> None:
308
+ for dataset_name in dataset_names:
309
+ meta = MetadataCatalog.get(dataset_name)
310
+ if not hasattr(meta, "class_to_mesh_name"):
311
+ meta.class_to_mesh_name = get_class_to_mesh_name_mapping(cfg)
312
+
313
+
314
+ def _merge_categories(dataset_names: Collection[str]) -> _MergedCategoriesT:
315
+ merged_categories = defaultdict(list)
316
+ category_names = {}
317
+ for dataset_name in dataset_names:
318
+ meta = MetadataCatalog.get(dataset_name)
319
+ whitelisted_categories = meta.get("whitelisted_categories")
320
+ category_map = meta.get("category_map", {})
321
+ cat_ids = (
322
+ whitelisted_categories if whitelisted_categories is not None else meta.categories.keys()
323
+ )
324
+ for cat_id in cat_ids:
325
+ cat_name = meta.categories[cat_id]
326
+ cat_id_mapped = category_map.get(cat_id, cat_id)
327
+ if cat_id_mapped == cat_id or cat_id_mapped in cat_ids:
328
+ category_names[cat_id] = cat_name
329
+ else:
330
+ category_names[cat_id] = str(cat_id_mapped)
331
+ # assign temporary mapped category name, this name can be changed
332
+ # during the second pass, since mapped ID can correspond to a category
333
+ # from a different dataset
334
+ cat_name_mapped = meta.categories[cat_id_mapped]
335
+ merged_categories[cat_id_mapped].append(
336
+ _DatasetCategory(
337
+ id=cat_id,
338
+ name=cat_name,
339
+ mapped_id=cat_id_mapped,
340
+ mapped_name=cat_name_mapped,
341
+ dataset_name=dataset_name,
342
+ )
343
+ )
344
+ # second pass to assign proper mapped category names
345
+ for cat_id, categories in merged_categories.items():
346
+ for cat in categories:
347
+ if cat_id in category_names and cat.mapped_name != category_names[cat_id]:
348
+ cat.mapped_name = category_names[cat_id]
349
+
350
+ return merged_categories
351
+
352
+
353
+ def _warn_if_merged_different_categories(merged_categories: _MergedCategoriesT) -> None:
354
+ logger = logging.getLogger(__name__)
355
+ for cat_id in merged_categories:
356
+ merged_categories_i = merged_categories[cat_id]
357
+ first_cat_name = merged_categories_i[0].name
358
+ if len(merged_categories_i) > 1 and not all(
359
+ cat.name == first_cat_name for cat in merged_categories_i[1:]
360
+ ):
361
+ cat_summary_str = ", ".join(
362
+ [f"{cat.id} ({cat.name}) from {cat.dataset_name}" for cat in merged_categories_i]
363
+ )
364
+ logger.warning(
365
+ f"Merged category {cat_id} corresponds to the following categories: "
366
+ f"{cat_summary_str}"
367
+ )
368
+
369
+
370
+ def combine_detection_dataset_dicts(
371
+ dataset_names: Collection[str],
372
+ keep_instance_predicate: Optional[InstancePredicate] = None,
373
+ proposal_files: Optional[Collection[str]] = None,
374
+ ) -> List[Instance]:
375
+ """
376
+ Load and prepare dataset dicts for training / testing
377
+
378
+ Args:
379
+ dataset_names (Collection[str]): a list of dataset names
380
+ keep_instance_predicate (Callable: Dict[str, Any] -> bool): predicate
381
+ applied to instance dicts which defines whether to keep the instance
382
+ proposal_files (Collection[str]): if given, a list of object proposal files
383
+ that match each dataset in `dataset_names`.
384
+ """
385
+ assert len(dataset_names)
386
+ if proposal_files is None:
387
+ proposal_files = [None] * len(dataset_names)
388
+ assert len(dataset_names) == len(proposal_files)
389
+ # load datasets and metadata
390
+ dataset_name_to_dicts = {}
391
+ for dataset_name in dataset_names:
392
+ dataset_name_to_dicts[dataset_name] = DatasetCatalog.get(dataset_name)
393
+ assert len(dataset_name_to_dicts), f"Dataset '{dataset_name}' is empty!"
394
+ # merge categories, requires category metadata to be loaded
395
+ # cat_id -> [(orig_cat_id, cat_name, dataset_name)]
396
+ merged_categories = _merge_categories(dataset_names)
397
+ _warn_if_merged_different_categories(merged_categories)
398
+ merged_category_names = [
399
+ merged_categories[cat_id][0].mapped_name for cat_id in sorted(merged_categories)
400
+ ]
401
+ # map to contiguous category IDs
402
+ _add_category_id_to_contiguous_id_maps_to_metadata(merged_categories)
403
+ # load annotations and dataset metadata
404
+ for dataset_name, proposal_file in zip(dataset_names, proposal_files):
405
+ dataset_dicts = dataset_name_to_dicts[dataset_name]
406
+ assert len(dataset_dicts), f"Dataset '{dataset_name}' is empty!"
407
+ if proposal_file is not None:
408
+ dataset_dicts = load_proposals_into_dataset(dataset_dicts, proposal_file)
409
+ dataset_dicts = _maybe_filter_and_map_categories(dataset_name, dataset_dicts)
410
+ print_instances_class_histogram(dataset_dicts, merged_category_names)
411
+ dataset_name_to_dicts[dataset_name] = dataset_dicts
412
+
413
+ if keep_instance_predicate is not None:
414
+ all_datasets_dicts_plain = [
415
+ d
416
+ for d in itertools.chain.from_iterable(dataset_name_to_dicts.values())
417
+ if keep_instance_predicate(d)
418
+ ]
419
+ else:
420
+ all_datasets_dicts_plain = list(
421
+ itertools.chain.from_iterable(dataset_name_to_dicts.values())
422
+ )
423
+ return all_datasets_dicts_plain
424
+
425
+
426
+ def build_detection_train_loader(cfg: CfgNode, mapper=None):
427
+ """
428
+ A data loader is created in a way similar to that of Detectron2.
429
+ The main differences are:
430
+ - it allows to combine datasets with different but compatible object category sets
431
+
432
+ The data loader is created by the following steps:
433
+ 1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts.
434
+ 2. Start workers to work on the dicts. Each worker will:
435
+ * Map each metadata dict into another format to be consumed by the model.
436
+ * Batch them by simply putting dicts into a list.
437
+ The batched ``list[mapped_dict]`` is what this dataloader will return.
438
+
439
+ Args:
440
+ cfg (CfgNode): the config
441
+ mapper (callable): a callable which takes a sample (dict) from dataset and
442
+ returns the format to be consumed by the model.
443
+ By default it will be `DatasetMapper(cfg, True)`.
444
+
445
+ Returns:
446
+ an infinite iterator of training data
447
+ """
448
+
449
+ _add_category_whitelists_to_metadata(cfg)
450
+ _add_category_maps_to_metadata(cfg)
451
+ _maybe_add_class_to_mesh_name_map_to_metadata(cfg.DATASETS.TRAIN, cfg)
452
+ dataset_dicts = combine_detection_dataset_dicts(
453
+ cfg.DATASETS.TRAIN,
454
+ keep_instance_predicate=_get_train_keep_instance_predicate(cfg),
455
+ proposal_files=cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else None,
456
+ )
457
+ if mapper is None:
458
+ mapper = DatasetMapper(cfg, True)
459
+ return d2_build_detection_train_loader(cfg, dataset=dataset_dicts, mapper=mapper)
460
+
461
+
462
+ def build_detection_test_loader(cfg, dataset_name, mapper=None):
463
+ """
464
+ Similar to `build_detection_train_loader`.
465
+ But this function uses the given `dataset_name` argument (instead of the names in cfg),
466
+ and uses batch size 1.
467
+
468
+ Args:
469
+ cfg: a detectron2 CfgNode
470
+ dataset_name (str): a name of the dataset that's available in the DatasetCatalog
471
+ mapper (callable): a callable which takes a sample (dict) from dataset
472
+ and returns the format to be consumed by the model.
473
+ By default it will be `DatasetMapper(cfg, False)`.
474
+
475
+ Returns:
476
+ DataLoader: a torch DataLoader, that loads the given detection
477
+ dataset, with test-time transformation and batching.
478
+ """
479
+ _add_category_whitelists_to_metadata(cfg)
480
+ _add_category_maps_to_metadata(cfg)
481
+ _maybe_add_class_to_mesh_name_map_to_metadata([dataset_name], cfg)
482
+ dataset_dicts = combine_detection_dataset_dicts(
483
+ [dataset_name],
484
+ keep_instance_predicate=_get_test_keep_instance_predicate(cfg),
485
+ proposal_files=[
486
+ cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(dataset_name)]
487
+ ]
488
+ if cfg.MODEL.LOAD_PROPOSALS
489
+ else None,
490
+ )
491
+ sampler = None
492
+ if not cfg.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE:
493
+ sampler = torch.utils.data.SequentialSampler(dataset_dicts)
494
+ if mapper is None:
495
+ mapper = DatasetMapper(cfg, False)
496
+ return d2_build_detection_test_loader(
497
+ dataset_dicts, mapper=mapper, num_workers=cfg.DATALOADER.NUM_WORKERS, sampler=sampler
498
+ )
499
+
500
+
501
+ def build_frame_selector(cfg: CfgNode):
502
+ strategy = FrameSelectionStrategy(cfg.STRATEGY)
503
+ if strategy == FrameSelectionStrategy.RANDOM_K:
504
+ frame_selector = RandomKFramesSelector(cfg.NUM_IMAGES)
505
+ elif strategy == FrameSelectionStrategy.FIRST_K:
506
+ frame_selector = FirstKFramesSelector(cfg.NUM_IMAGES)
507
+ elif strategy == FrameSelectionStrategy.LAST_K:
508
+ frame_selector = LastKFramesSelector(cfg.NUM_IMAGES)
509
+ elif strategy == FrameSelectionStrategy.ALL:
510
+ frame_selector = None
511
+ # pyre-fixme[61]: `frame_selector` may not be initialized here.
512
+ return frame_selector
513
+
514
+
515
+ def build_transform(cfg: CfgNode, data_type: str):
516
+ if cfg.TYPE == "resize":
517
+ if data_type == "image":
518
+ return ImageResizeTransform(cfg.MIN_SIZE, cfg.MAX_SIZE)
519
+ raise ValueError(f"Unknown transform {cfg.TYPE} for data type {data_type}")
520
+
521
+
522
+ def build_combined_loader(cfg: CfgNode, loaders: Collection[Loader], ratios: Sequence[float]):
523
+ images_per_worker = _compute_num_images_per_worker(cfg)
524
+ return CombinedDataLoader(loaders, images_per_worker, ratios)
525
+
526
+
527
+ def build_bootstrap_dataset(dataset_name: str, cfg: CfgNode) -> Sequence[torch.Tensor]:
528
+ """
529
+ Build dataset that provides data to bootstrap on
530
+
531
+ Args:
532
+ dataset_name (str): Name of the dataset, needs to have associated metadata
533
+ to load the data
534
+ cfg (CfgNode): bootstrapping config
535
+ Returns:
536
+ Sequence[Tensor] - dataset that provides image batches, Tensors of size
537
+ [N, C, H, W] of type float32
538
+ """
539
+ logger = logging.getLogger(__name__)
540
+ _add_category_info_to_bootstrapping_metadata(dataset_name, cfg)
541
+ meta = MetadataCatalog.get(dataset_name)
542
+ factory = BootstrapDatasetFactoryCatalog.get(meta.dataset_type)
543
+ dataset = None
544
+ if factory is not None:
545
+ dataset = factory(meta, cfg)
546
+ if dataset is None:
547
+ logger.warning(f"Failed to create dataset {dataset_name} of type {meta.dataset_type}")
548
+ return dataset
549
+
550
+
551
+ def build_data_sampler(cfg: CfgNode, sampler_cfg: CfgNode, embedder: Optional[torch.nn.Module]):
552
+ if sampler_cfg.TYPE == "densepose_uniform":
553
+ data_sampler = PredictionToGroundTruthSampler()
554
+ # transform densepose pred -> gt
555
+ data_sampler.register_sampler(
556
+ "pred_densepose",
557
+ "gt_densepose",
558
+ DensePoseUniformSampler(count_per_class=sampler_cfg.COUNT_PER_CLASS),
559
+ )
560
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
561
+ return data_sampler
562
+ elif sampler_cfg.TYPE == "densepose_UV_confidence":
563
+ data_sampler = PredictionToGroundTruthSampler()
564
+ # transform densepose pred -> gt
565
+ data_sampler.register_sampler(
566
+ "pred_densepose",
567
+ "gt_densepose",
568
+ DensePoseConfidenceBasedSampler(
569
+ confidence_channel="sigma_2",
570
+ count_per_class=sampler_cfg.COUNT_PER_CLASS,
571
+ search_proportion=0.5,
572
+ ),
573
+ )
574
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
575
+ return data_sampler
576
+ elif sampler_cfg.TYPE == "densepose_fine_segm_confidence":
577
+ data_sampler = PredictionToGroundTruthSampler()
578
+ # transform densepose pred -> gt
579
+ data_sampler.register_sampler(
580
+ "pred_densepose",
581
+ "gt_densepose",
582
+ DensePoseConfidenceBasedSampler(
583
+ confidence_channel="fine_segm_confidence",
584
+ count_per_class=sampler_cfg.COUNT_PER_CLASS,
585
+ search_proportion=0.5,
586
+ ),
587
+ )
588
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
589
+ return data_sampler
590
+ elif sampler_cfg.TYPE == "densepose_coarse_segm_confidence":
591
+ data_sampler = PredictionToGroundTruthSampler()
592
+ # transform densepose pred -> gt
593
+ data_sampler.register_sampler(
594
+ "pred_densepose",
595
+ "gt_densepose",
596
+ DensePoseConfidenceBasedSampler(
597
+ confidence_channel="coarse_segm_confidence",
598
+ count_per_class=sampler_cfg.COUNT_PER_CLASS,
599
+ search_proportion=0.5,
600
+ ),
601
+ )
602
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
603
+ return data_sampler
604
+ elif sampler_cfg.TYPE == "densepose_cse_uniform":
605
+ assert embedder is not None
606
+ data_sampler = PredictionToGroundTruthSampler()
607
+ # transform densepose pred -> gt
608
+ data_sampler.register_sampler(
609
+ "pred_densepose",
610
+ "gt_densepose",
611
+ DensePoseCSEUniformSampler(
612
+ cfg=cfg,
613
+ use_gt_categories=sampler_cfg.USE_GROUND_TRUTH_CATEGORIES,
614
+ embedder=embedder,
615
+ count_per_class=sampler_cfg.COUNT_PER_CLASS,
616
+ ),
617
+ )
618
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
619
+ return data_sampler
620
+ elif sampler_cfg.TYPE == "densepose_cse_coarse_segm_confidence":
621
+ assert embedder is not None
622
+ data_sampler = PredictionToGroundTruthSampler()
623
+ # transform densepose pred -> gt
624
+ data_sampler.register_sampler(
625
+ "pred_densepose",
626
+ "gt_densepose",
627
+ DensePoseCSEConfidenceBasedSampler(
628
+ cfg=cfg,
629
+ use_gt_categories=sampler_cfg.USE_GROUND_TRUTH_CATEGORIES,
630
+ embedder=embedder,
631
+ confidence_channel="coarse_segm_confidence",
632
+ count_per_class=sampler_cfg.COUNT_PER_CLASS,
633
+ search_proportion=0.5,
634
+ ),
635
+ )
636
+ data_sampler.register_sampler("pred_densepose", "gt_masks", MaskFromDensePoseSampler())
637
+ return data_sampler
638
+
639
+ raise ValueError(f"Unknown data sampler type {sampler_cfg.TYPE}")
640
+
641
+
642
+ def build_data_filter(cfg: CfgNode):
643
+ if cfg.TYPE == "detection_score":
644
+ min_score = cfg.MIN_VALUE
645
+ return ScoreBasedFilter(min_score=min_score)
646
+ raise ValueError(f"Unknown data filter type {cfg.TYPE}")
647
+
648
+
649
+ def build_inference_based_loader(
650
+ cfg: CfgNode,
651
+ dataset_cfg: CfgNode,
652
+ model: torch.nn.Module,
653
+ embedder: Optional[torch.nn.Module] = None,
654
+ ) -> InferenceBasedLoader:
655
+ """
656
+ Constructs data loader based on inference results of a model.
657
+ """
658
+ dataset = build_bootstrap_dataset(dataset_cfg.DATASET, dataset_cfg.IMAGE_LOADER)
659
+ meta = MetadataCatalog.get(dataset_cfg.DATASET)
660
+ training_sampler = TrainingSampler(len(dataset))
661
+ data_loader = torch.utils.data.DataLoader(
662
+ dataset, # pyre-ignore[6]
663
+ batch_size=dataset_cfg.IMAGE_LOADER.BATCH_SIZE,
664
+ sampler=training_sampler,
665
+ num_workers=dataset_cfg.IMAGE_LOADER.NUM_WORKERS,
666
+ collate_fn=trivial_batch_collator,
667
+ worker_init_fn=worker_init_reset_seed,
668
+ )
669
+ return InferenceBasedLoader(
670
+ model,
671
+ data_loader=data_loader,
672
+ data_sampler=build_data_sampler(cfg, dataset_cfg.DATA_SAMPLER, embedder),
673
+ data_filter=build_data_filter(dataset_cfg.FILTER),
674
+ shuffle=True,
675
+ batch_size=dataset_cfg.INFERENCE.OUTPUT_BATCH_SIZE,
676
+ inference_batch_size=dataset_cfg.INFERENCE.INPUT_BATCH_SIZE,
677
+ category_to_class_mapping=meta.category_to_class_mapping,
678
+ )
679
+
680
+
681
+ def has_inference_based_loaders(cfg: CfgNode) -> bool:
682
+ """
683
+ Returns True, if at least one inferense-based loader must
684
+ be instantiated for training
685
+ """
686
+ return len(cfg.BOOTSTRAP_DATASETS) > 0
687
+
688
+
689
+ def build_inference_based_loaders(
690
+ cfg: CfgNode, model: torch.nn.Module
691
+ ) -> Tuple[List[InferenceBasedLoader], List[float]]:
692
+ loaders = []
693
+ ratios = []
694
+ embedder = build_densepose_embedder(cfg).to(device=model.device) # pyre-ignore[16]
695
+ for dataset_spec in cfg.BOOTSTRAP_DATASETS:
696
+ dataset_cfg = get_bootstrap_dataset_config().clone()
697
+ dataset_cfg.merge_from_other_cfg(CfgNode(dataset_spec))
698
+ loader = build_inference_based_loader(cfg, dataset_cfg, model, embedder)
699
+ loaders.append(loader)
700
+ ratios.append(dataset_cfg.RATIO)
701
+ return loaders, ratios
702
+
703
+
704
+ def build_video_list_dataset(meta: Metadata, cfg: CfgNode):
705
+ video_list_fpath = meta.video_list_fpath
706
+ video_base_path = meta.video_base_path
707
+ category = meta.category
708
+ if cfg.TYPE == "video_keyframe":
709
+ frame_selector = build_frame_selector(cfg.SELECT)
710
+ transform = build_transform(cfg.TRANSFORM, data_type="image")
711
+ video_list = video_list_from_file(video_list_fpath, video_base_path)
712
+ keyframe_helper_fpath = getattr(cfg, "KEYFRAME_HELPER", None)
713
+ return VideoKeyframeDataset(
714
+ video_list, category, frame_selector, transform, keyframe_helper_fpath
715
+ )
716
+
717
+
718
+ class _BootstrapDatasetFactoryCatalog(UserDict):
719
+ """
720
+ A global dictionary that stores information about bootstrapped datasets creation functions
721
+ from metadata and config, for diverse DatasetType
722
+ """
723
+
724
+ def register(self, dataset_type: DatasetType, factory: Callable[[Metadata, CfgNode], Dataset]):
725
+ """
726
+ Args:
727
+ dataset_type (DatasetType): a DatasetType e.g. DatasetType.VIDEO_LIST
728
+ factory (Callable[Metadata, CfgNode]): a callable which takes Metadata and cfg
729
+ arguments and returns a dataset object.
730
+ """
731
+ assert dataset_type not in self, "Dataset '{}' is already registered!".format(dataset_type)
732
+ self[dataset_type] = factory
733
+
734
+
735
+ BootstrapDatasetFactoryCatalog = _BootstrapDatasetFactoryCatalog()
736
+ BootstrapDatasetFactoryCatalog.register(DatasetType.VIDEO_LIST, build_video_list_dataset)
densepose/data/combined_loader.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+
3
+ import random
4
+ from collections import deque
5
+ from typing import Any, Collection, Deque, Iterable, Iterator, List, Sequence
6
+
7
+ Loader = Iterable[Any]
8
+
9
+
10
+ def _pooled_next(iterator: Iterator[Any], pool: Deque[Any]):
11
+ if not pool:
12
+ pool.extend(next(iterator))
13
+ return pool.popleft()
14
+
15
+
16
+ class CombinedDataLoader:
17
+ """
18
+ Combines data loaders using the provided sampling ratios
19
+ """
20
+
21
+ BATCH_COUNT = 100
22
+
23
+ def __init__(self, loaders: Collection[Loader], batch_size: int, ratios: Sequence[float]):
24
+ self.loaders = loaders
25
+ self.batch_size = batch_size
26
+ self.ratios = ratios
27
+
28
+ def __iter__(self) -> Iterator[List[Any]]:
29
+ iters = [iter(loader) for loader in self.loaders]
30
+ indices = []
31
+ pool = [deque()] * len(iters)
32
+ # infinite iterator, as in D2
33
+ while True:
34
+ if not indices:
35
+ # just a buffer of indices, its size doesn't matter
36
+ # as long as it's a multiple of batch_size
37
+ k = self.batch_size * self.BATCH_COUNT
38
+ indices = random.choices(range(len(self.loaders)), self.ratios, k=k)
39
+ try:
40
+ batch = [_pooled_next(iters[i], pool[i]) for i in indices[: self.batch_size]]
41
+ except StopIteration:
42
+ break
43
+ indices = indices[self.batch_size :]
44
+ yield batch