gaur3009 commited on
Commit
a2d5f7e
·
verified ·
1 Parent(s): b5153ef

Create apply_net.py

Browse files
Files changed (1) hide show
  1. apply_net.py +353 -0
apply_net.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import logging
4
+ import os
5
+ import sys
6
+ from typing import Any, ClassVar, Dict, List
7
+ import torch
8
+
9
+ from detectron2.config import CfgNode, get_cfg
10
+ from detectron2.data.detection_utils import read_image
11
+ from detectron2.engine.defaults import DefaultPredictor
12
+ from detectron2.structures.instances import Instances
13
+ from detectron2.utils.logger import setup_logger
14
+
15
+ from densepose import add_densepose_config
16
+ from densepose.structures import DensePoseChartPredictorOutput, DensePoseEmbeddingPredictorOutput
17
+ from densepose.utils.logger import verbosity_to_level
18
+ from densepose.vis.base import CompoundVisualizer
19
+ from densepose.vis.bounding_box import ScoredBoundingBoxVisualizer
20
+ from densepose.vis.densepose_outputs_vertex import (
21
+ DensePoseOutputsTextureVisualizer,
22
+ DensePoseOutputsVertexVisualizer,
23
+ get_texture_atlases,
24
+ )
25
+ from densepose.vis.densepose_results import (
26
+ DensePoseResultsContourVisualizer,
27
+ DensePoseResultsFineSegmentationVisualizer,
28
+ DensePoseResultsUVisualizer,
29
+ DensePoseResultsVVisualizer,
30
+ )
31
+ from densepose.vis.densepose_results_textures import (
32
+ DensePoseResultsVisualizerWithTexture,
33
+ get_texture_atlas,
34
+ )
35
+ from densepose.vis.extractor import (
36
+ CompoundExtractor,
37
+ DensePoseOutputsExtractor,
38
+ DensePoseResultExtractor,
39
+ create_extractor,
40
+ )
41
+
42
+ DOC = """Apply Net - a tool to print / visualize DensePose results
43
+ """
44
+
45
+ LOGGER_NAME = "apply_net"
46
+ logger = logging.getLogger(LOGGER_NAME)
47
+
48
+ _ACTION_REGISTRY: Dict[str, "Action"] = {}
49
+
50
+
51
+ class Action:
52
+ @classmethod
53
+ def add_arguments(cls: type, parser: argparse.ArgumentParser):
54
+ parser.add_argument(
55
+ "-v",
56
+ "--verbosity",
57
+ action="count",
58
+ help="Verbose mode. Multiple -v options increase the verbosity.",
59
+ )
60
+
61
+
62
+ def register_action(cls: type):
63
+ """
64
+ Decorator for action classes to automate action registration
65
+ """
66
+ global _ACTION_REGISTRY
67
+ _ACTION_REGISTRY[cls.COMMAND] = cls
68
+ return cls
69
+
70
+
71
+ class InferenceAction(Action):
72
+ @classmethod
73
+ def add_arguments(cls: type, parser: argparse.ArgumentParser):
74
+ super(InferenceAction, cls).add_arguments(parser)
75
+ parser.add_argument("cfg", metavar="<config>", help="Config file")
76
+ parser.add_argument("model", metavar="<model>", help="Model file")
77
+ parser.add_argument(
78
+ "--opts",
79
+ help="Modify config options using the command-line 'KEY VALUE' pairs",
80
+ default=[],
81
+ nargs=argparse.REMAINDER,
82
+ )
83
+
84
+ @classmethod
85
+ def execute(cls: type, args: argparse.Namespace, human_img):
86
+ logger.info(f"Loading config from {args.cfg}")
87
+ opts = []
88
+ cfg = cls.setup_config(args.cfg, args.model, args, opts)
89
+ logger.info(f"Loading model from {args.model}")
90
+ predictor = DefaultPredictor(cfg)
91
+ # logger.info(f"Loading data from {args.input}")
92
+ # file_list = cls._get_input_file_list(args.input)
93
+ # if len(file_list) == 0:
94
+ # logger.warning(f"No input images for {args.input}")
95
+ # return
96
+ context = cls.create_context(args, cfg)
97
+ # for file_name in file_list:
98
+ # img = read_image(file_name, format="BGR") # predictor expects BGR image.
99
+ with torch.no_grad():
100
+ outputs = predictor(human_img)["instances"]
101
+ out_pose = cls.execute_on_outputs(context, {"image": human_img}, outputs)
102
+ cls.postexecute(context)
103
+ return out_pose
104
+
105
+ @classmethod
106
+ def setup_config(
107
+ cls: type, config_fpath: str, model_fpath: str, args: argparse.Namespace, opts: List[str]
108
+ ):
109
+ cfg = get_cfg()
110
+ add_densepose_config(cfg)
111
+ cfg.merge_from_file(config_fpath)
112
+ cfg.merge_from_list(args.opts)
113
+ if opts:
114
+ cfg.merge_from_list(opts)
115
+ cfg.MODEL.WEIGHTS = model_fpath
116
+ cfg.freeze()
117
+ return cfg
118
+
119
+ @classmethod
120
+ def _get_input_file_list(cls: type, input_spec: str):
121
+ if os.path.isdir(input_spec):
122
+ file_list = [
123
+ os.path.join(input_spec, fname)
124
+ for fname in os.listdir(input_spec)
125
+ if os.path.isfile(os.path.join(input_spec, fname))
126
+ ]
127
+ elif os.path.isfile(input_spec):
128
+ file_list = [input_spec]
129
+ else:
130
+ file_list = glob.glob(input_spec)
131
+ return file_list
132
+
133
+
134
+ @register_action
135
+ class DumpAction(InferenceAction):
136
+ """
137
+ Dump action that outputs results to a pickle file
138
+ """
139
+
140
+ COMMAND: ClassVar[str] = "dump"
141
+
142
+ @classmethod
143
+ def add_parser(cls: type, subparsers: argparse._SubParsersAction):
144
+ parser = subparsers.add_parser(cls.COMMAND, help="Dump model outputs to a file.")
145
+ cls.add_arguments(parser)
146
+ parser.set_defaults(func=cls.execute)
147
+
148
+ @classmethod
149
+ def add_arguments(cls: type, parser: argparse.ArgumentParser):
150
+ super(DumpAction, cls).add_arguments(parser)
151
+ parser.add_argument(
152
+ "--output",
153
+ metavar="<dump_file>",
154
+ default="results.pkl",
155
+ help="File name to save dump to",
156
+ )
157
+
158
+ @classmethod
159
+ def execute_on_outputs(
160
+ cls: type, context: Dict[str, Any], entry: Dict[str, Any], outputs: Instances
161
+ ):
162
+ image_fpath = entry["file_name"]
163
+ logger.info(f"Processing {image_fpath}")
164
+ result = {"file_name": image_fpath}
165
+ if outputs.has("scores"):
166
+ result["scores"] = outputs.get("scores").cpu()
167
+ if outputs.has("pred_boxes"):
168
+ result["pred_boxes_XYXY"] = outputs.get("pred_boxes").tensor.cpu()
169
+ if outputs.has("pred_densepose"):
170
+ if isinstance(outputs.pred_densepose, DensePoseChartPredictorOutput):
171
+ extractor = DensePoseResultExtractor()
172
+ elif isinstance(outputs.pred_densepose, DensePoseEmbeddingPredictorOutput):
173
+ extractor = DensePoseOutputsExtractor()
174
+ result["pred_densepose"] = extractor(outputs)[0]
175
+ context["results"].append(result)
176
+
177
+ @classmethod
178
+ def create_context(cls: type, args: argparse.Namespace, cfg: CfgNode):
179
+ context = {"results": [], "out_fname": args.output}
180
+ return context
181
+
182
+ @classmethod
183
+ def postexecute(cls: type, context: Dict[str, Any]):
184
+ out_fname = context["out_fname"]
185
+ out_dir = os.path.dirname(out_fname)
186
+ if len(out_dir) > 0 and not os.path.exists(out_dir):
187
+ os.makedirs(out_dir)
188
+ with open(out_fname, "wb") as hFile:
189
+ torch.save(context["results"], hFile)
190
+ logger.info(f"Output saved to {out_fname}")
191
+
192
+
193
+ @register_action
194
+ class ShowAction(InferenceAction):
195
+ """
196
+ Show action that visualizes selected entries on an image
197
+ """
198
+
199
+ COMMAND: ClassVar[str] = "show"
200
+ VISUALIZERS: ClassVar[Dict[str, object]] = {
201
+ "dp_contour": DensePoseResultsContourVisualizer,
202
+ "dp_segm": DensePoseResultsFineSegmentationVisualizer,
203
+ "dp_u": DensePoseResultsUVisualizer,
204
+ "dp_v": DensePoseResultsVVisualizer,
205
+ "dp_iuv_texture": DensePoseResultsVisualizerWithTexture,
206
+ "dp_cse_texture": DensePoseOutputsTextureVisualizer,
207
+ "dp_vertex": DensePoseOutputsVertexVisualizer,
208
+ "bbox": ScoredBoundingBoxVisualizer,
209
+ }
210
+
211
+ @classmethod
212
+ def add_parser(cls: type, subparsers: argparse._SubParsersAction):
213
+ parser = subparsers.add_parser(cls.COMMAND, help="Visualize selected entries")
214
+ cls.add_arguments(parser)
215
+ parser.set_defaults(func=cls.execute)
216
+
217
+ @classmethod
218
+ def add_arguments(cls: type, parser: argparse.ArgumentParser):
219
+ super(ShowAction, cls).add_arguments(parser)
220
+ parser.add_argument(
221
+ "visualizations",
222
+ metavar="<visualizations>",
223
+ help="Comma separated list of visualizations, possible values: "
224
+ "[{}]".format(",".join(sorted(cls.VISUALIZERS.keys()))),
225
+ )
226
+ parser.add_argument(
227
+ "--min_score",
228
+ metavar="<score>",
229
+ default=0.8,
230
+ type=float,
231
+ help="Minimum detection score to visualize",
232
+ )
233
+ parser.add_argument(
234
+ "--nms_thresh", metavar="<threshold>", default=None, type=float, help="NMS threshold"
235
+ )
236
+ parser.add_argument(
237
+ "--texture_atlas",
238
+ metavar="<texture_atlas>",
239
+ default=None,
240
+ help="Texture atlas file (for IUV texture transfer)",
241
+ )
242
+ parser.add_argument(
243
+ "--texture_atlases_map",
244
+ metavar="<texture_atlases_map>",
245
+ default=None,
246
+ help="JSON string of a dict containing texture atlas files for each mesh",
247
+ )
248
+ parser.add_argument(
249
+ "--output",
250
+ metavar="<image_file>",
251
+ default="outputres.png",
252
+ help="File name to save output to",
253
+ )
254
+
255
+ @classmethod
256
+ def setup_config(
257
+ cls: type, config_fpath: str, model_fpath: str, args: argparse.Namespace, opts: List[str]
258
+ ):
259
+ opts.append("MODEL.ROI_HEADS.SCORE_THRESH_TEST")
260
+ opts.append(str(args.min_score))
261
+ if args.nms_thresh is not None:
262
+ opts.append("MODEL.ROI_HEADS.NMS_THRESH_TEST")
263
+ opts.append(str(args.nms_thresh))
264
+ cfg = super(ShowAction, cls).setup_config(config_fpath, model_fpath, args, opts)
265
+ return cfg
266
+
267
+ @classmethod
268
+ def execute_on_outputs(
269
+ cls: type, context: Dict[str, Any], entry: Dict[str, Any], outputs: Instances
270
+ ):
271
+ import cv2
272
+ import numpy as np
273
+ visualizer = context["visualizer"]
274
+ extractor = context["extractor"]
275
+ # image_fpath = entry["file_name"]
276
+ # logger.info(f"Processing {image_fpath}")
277
+ image = cv2.cvtColor(entry["image"], cv2.COLOR_BGR2GRAY)
278
+ image = np.tile(image[:, :, np.newaxis], [1, 1, 3])
279
+ data = extractor(outputs)
280
+ image_vis = visualizer.visualize(image, data)
281
+
282
+ return image_vis
283
+ entry_idx = context["entry_idx"] + 1
284
+ out_fname = './image-densepose/' + image_fpath.split('/')[-1]
285
+ out_dir = './image-densepose'
286
+ out_dir = os.path.dirname(out_fname)
287
+ if len(out_dir) > 0 and not os.path.exists(out_dir):
288
+ os.makedirs(out_dir)
289
+ cv2.imwrite(out_fname, image_vis)
290
+ logger.info(f"Output saved to {out_fname}")
291
+ context["entry_idx"] += 1
292
+
293
+ @classmethod
294
+ def postexecute(cls: type, context: Dict[str, Any]):
295
+ pass
296
+ # python ./apply_net.py show ./configs/densepose_rcnn_R_50_FPN_s1x.yaml https://dl.fbaipublicfiles.com/densepose/densepose_rcnn_R_50_FPN_s1x/165712039/model_final_162be9.pkl /home/alin0222/DressCode/upper_body/images dp_segm -v --opts MODEL.DEVICE cpu
297
+
298
+ @classmethod
299
+ def _get_out_fname(cls: type, entry_idx: int, fname_base: str):
300
+ base, ext = os.path.splitext(fname_base)
301
+ return base + ".{0:04d}".format(entry_idx) + ext
302
+
303
+ @classmethod
304
+ def create_context(cls: type, args: argparse.Namespace, cfg: CfgNode) -> Dict[str, Any]:
305
+ vis_specs = args.visualizations.split(",")
306
+ visualizers = []
307
+ extractors = []
308
+ for vis_spec in vis_specs:
309
+ texture_atlas = get_texture_atlas(args.texture_atlas)
310
+ texture_atlases_dict = get_texture_atlases(args.texture_atlases_map)
311
+ vis = cls.VISUALIZERS[vis_spec](
312
+ cfg=cfg,
313
+ texture_atlas=texture_atlas,
314
+ texture_atlases_dict=texture_atlases_dict,
315
+ )
316
+ visualizers.append(vis)
317
+ extractor = create_extractor(vis)
318
+ extractors.append(extractor)
319
+ visualizer = CompoundVisualizer(visualizers)
320
+ extractor = CompoundExtractor(extractors)
321
+ context = {
322
+ "extractor": extractor,
323
+ "visualizer": visualizer,
324
+ "out_fname": args.output,
325
+ "entry_idx": 0,
326
+ }
327
+ return context
328
+
329
+
330
+ def create_argument_parser() -> argparse.ArgumentParser:
331
+ parser = argparse.ArgumentParser(
332
+ description=DOC,
333
+ formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=120),
334
+ )
335
+ parser.set_defaults(func=lambda _: parser.print_help(sys.stdout))
336
+ subparsers = parser.add_subparsers(title="Actions")
337
+ for _, action in _ACTION_REGISTRY.items():
338
+ action.add_parser(subparsers)
339
+ return parser
340
+
341
+
342
+ def main():
343
+ parser = create_argument_parser()
344
+ args = parser.parse_args()
345
+ verbosity = getattr(args, "verbosity", None)
346
+ global logger
347
+ logger = setup_logger(name=LOGGER_NAME)
348
+ logger.setLevel(verbosity_to_level(verbosity))
349
+ args.func(args)
350
+
351
+
352
+ if __name__ == "__main__":
353
+ main()