cfg_utils.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import ast
  2. import yaml
  3. import copy
  4. import argparse
  5. from argparse import ArgumentParser, RawDescriptionHelpFormatter
  6. class ArgsParser(ArgumentParser):
  7. def __init__(self):
  8. super(ArgsParser, self).__init__(
  9. formatter_class=RawDescriptionHelpFormatter)
  10. self.add_argument(
  11. "-o", "--opt", nargs='*', help="set configuration options")
  12. def parse_args(self, argv=None):
  13. args = super(ArgsParser, self).parse_args(argv)
  14. assert args.config is not None, \
  15. "Please specify --config=configure_file_path."
  16. args.opt = self._parse_opt(args.opt)
  17. return args
  18. def _parse_opt(self, opts):
  19. config = {}
  20. if not opts:
  21. return config
  22. for s in opts:
  23. s = s.strip()
  24. k, v = s.split('=', 1)
  25. if '.' not in k:
  26. config[k] = yaml.load(v, Loader=yaml.Loader)
  27. else:
  28. keys = k.split('.')
  29. if keys[0] not in config:
  30. config[keys[0]] = {}
  31. cur = config[keys[0]]
  32. for idx, key in enumerate(keys[1:]):
  33. if idx == len(keys) - 2:
  34. cur[key] = yaml.load(v, Loader=yaml.Loader)
  35. else:
  36. cur[key] = {}
  37. cur = cur[key]
  38. return config
  39. def argsparser():
  40. parser = ArgsParser()
  41. parser.add_argument(
  42. "--config",
  43. type=str,
  44. default=None,
  45. help=("Path of configure"),
  46. required=True)
  47. parser.add_argument(
  48. "--image_file", type=str, default=None, help="Path of image file.")
  49. parser.add_argument(
  50. "--image_dir",
  51. type=str,
  52. default=None,
  53. help="Dir of image file, `image_file` has a higher priority.")
  54. parser.add_argument(
  55. "--video_file",
  56. type=str,
  57. default=None,
  58. help="Path of video file, `video_file` or `camera_id` has a highest priority."
  59. )
  60. parser.add_argument(
  61. "--video_dir",
  62. type=str,
  63. default=None,
  64. help="Dir of video file, `video_file` has a higher priority.")
  65. parser.add_argument(
  66. "--rtsp",
  67. type=str,
  68. nargs='+',
  69. default=None,
  70. help="list of rtsp inputs, for one or multiple rtsp input.")
  71. parser.add_argument(
  72. "--camera_id",
  73. type=int,
  74. default=-1,
  75. help="device id of camera to predict.")
  76. parser.add_argument(
  77. "--output_dir",
  78. type=str,
  79. default="output",
  80. help="Directory of output visualization files.")
  81. parser.add_argument(
  82. "--pushurl",
  83. type=str,
  84. default="",
  85. help="url of output visualization stream.")
  86. parser.add_argument(
  87. "--run_mode",
  88. type=str,
  89. default='paddle',
  90. help="mode of running(paddle/trt_fp32/trt_fp16/trt_int8)")
  91. parser.add_argument(
  92. "--device",
  93. type=str,
  94. default='cpu',
  95. help="Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU."
  96. )
  97. parser.add_argument(
  98. "--enable_mkldnn",
  99. type=ast.literal_eval,
  100. default=False,
  101. help="Whether use mkldnn with CPU.")
  102. parser.add_argument(
  103. "--cpu_threads", type=int, default=1, help="Num of threads with CPU.")
  104. parser.add_argument(
  105. "--trt_min_shape", type=int, default=1, help="min_shape for TensorRT.")
  106. parser.add_argument(
  107. "--trt_max_shape",
  108. type=int,
  109. default=1280,
  110. help="max_shape for TensorRT.")
  111. parser.add_argument(
  112. "--trt_opt_shape",
  113. type=int,
  114. default=640,
  115. help="opt_shape for TensorRT.")
  116. parser.add_argument(
  117. "--trt_calib_mode",
  118. type=bool,
  119. default=False,
  120. help="If the model is produced by TRT offline quantitative "
  121. "calibration, trt_calib_mode need to set True.")
  122. parser.add_argument(
  123. "--do_entrance_counting",
  124. action='store_true',
  125. help="Whether counting the numbers of identifiers entering "
  126. "or getting out from the entrance. Note that only support single-class MOT."
  127. )
  128. parser.add_argument(
  129. "--do_break_in_counting",
  130. action='store_true',
  131. help="Whether counting the numbers of identifiers break in "
  132. "the area. Note that only support single-class MOT and "
  133. "the video should be taken by a static camera.")
  134. parser.add_argument(
  135. "--illegal_parking_time",
  136. type=int,
  137. default=-1,
  138. help="illegal parking time which units are seconds, default is -1 which means not recognition illegal parking"
  139. )
  140. parser.add_argument(
  141. "--region_type",
  142. type=str,
  143. default='horizontal',
  144. help="Area type for entrance counting or break in counting, 'horizontal' and "
  145. "'vertical' used when do entrance counting. 'custom' used when do break in counting. "
  146. "Note that only support single-class MOT, and the video should be taken by a static camera."
  147. )
  148. parser.add_argument(
  149. '--region_polygon',
  150. nargs='+',
  151. type=int,
  152. default=[],
  153. help="Clockwise point coords (x0,y0,x1,y1...) of polygon of area when "
  154. "do_break_in_counting. Note that only support single-class MOT and "
  155. "the video should be taken by a static camera.")
  156. parser.add_argument(
  157. "--secs_interval",
  158. type=int,
  159. default=2,
  160. help="The seconds interval to count after tracking")
  161. parser.add_argument(
  162. "--draw_center_traj",
  163. action='store_true',
  164. help="Whether drawing the trajectory of center")
  165. return parser
  166. def merge_cfg(args):
  167. # load config
  168. with open(args.config) as f:
  169. pred_config = yaml.safe_load(f)
  170. def merge(cfg, arg):
  171. # update cfg from arg directly
  172. merge_cfg = copy.deepcopy(cfg)
  173. for k, v in cfg.items():
  174. if k in arg:
  175. merge_cfg[k] = arg[k]
  176. else:
  177. if isinstance(v, dict):
  178. merge_cfg[k] = merge(v, arg)
  179. return merge_cfg
  180. def merge_opt(cfg, arg):
  181. merge_cfg = copy.deepcopy(cfg)
  182. # merge opt
  183. if 'opt' in arg.keys() and arg['opt']:
  184. for name, value in arg['opt'].items(
  185. ): # example: {'MOT': {'batch_size': 3}}
  186. if name not in merge_cfg.keys():
  187. print("No", name, "in config file!")
  188. continue
  189. for sub_k, sub_v in value.items():
  190. if sub_k not in merge_cfg[name].keys():
  191. print("No", sub_k, "in config file of", name, "!")
  192. continue
  193. merge_cfg[name][sub_k] = sub_v
  194. return merge_cfg
  195. args_dict = vars(args)
  196. pred_config = merge(pred_config, args_dict)
  197. pred_config = merge_opt(pred_config, args_dict)
  198. return pred_config
  199. def print_arguments(cfg):
  200. print('----------- Running Arguments -----------')
  201. buffer = yaml.dump(cfg)
  202. print(buffer)
  203. print('------------------------------------------')