util.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2019/8/23 21:59
  3. # @Author : zhoujun
  4. import json
  5. import pathlib
  6. import time
  7. import os
  8. import glob
  9. import cv2
  10. import yaml
  11. from typing import Mapping
  12. import matplotlib.pyplot as plt
  13. import numpy as np
  14. from argparse import ArgumentParser, RawDescriptionHelpFormatter
  15. def _check_image_file(path):
  16. img_end = {"jpg", "bmp", "png", "jpeg", "rgb", "tif", "tiff", "gif", "pdf"}
  17. return any([path.lower().endswith(e) for e in img_end])
  18. def get_image_file_list(img_file):
  19. imgs_lists = []
  20. if img_file is None or not os.path.exists(img_file):
  21. raise Exception("not found any img file in {}".format(img_file))
  22. img_end = {"jpg", "bmp", "png", "jpeg", "rgb", "tif", "tiff", "gif", "pdf"}
  23. if os.path.isfile(img_file) and _check_image_file(img_file):
  24. imgs_lists.append(img_file)
  25. elif os.path.isdir(img_file):
  26. for single_file in os.listdir(img_file):
  27. file_path = os.path.join(img_file, single_file)
  28. if os.path.isfile(file_path) and _check_image_file(file_path):
  29. imgs_lists.append(file_path)
  30. if len(imgs_lists) == 0:
  31. raise Exception("not found any img file in {}".format(img_file))
  32. imgs_lists = sorted(imgs_lists)
  33. return imgs_lists
  34. def setup_logger(log_file_path: str = None):
  35. import logging
  36. logging._warn_preinit_stderr = 0
  37. logger = logging.getLogger("DBNet.paddle")
  38. formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")
  39. ch = logging.StreamHandler()
  40. ch.setFormatter(formatter)
  41. logger.addHandler(ch)
  42. if log_file_path is not None:
  43. file_handle = logging.FileHandler(log_file_path)
  44. file_handle.setFormatter(formatter)
  45. logger.addHandler(file_handle)
  46. logger.setLevel(logging.DEBUG)
  47. return logger
  48. # --exeTime
  49. def exe_time(func):
  50. def newFunc(*args, **args2):
  51. t0 = time.time()
  52. back = func(*args, **args2)
  53. print("{} cost {:.3f}s".format(func.__name__, time.time() - t0))
  54. return back
  55. return newFunc
  56. def load(file_path: str):
  57. file_path = pathlib.Path(file_path)
  58. func_dict = {".txt": _load_txt, ".json": _load_json, ".list": _load_txt}
  59. assert file_path.suffix in func_dict
  60. return func_dict[file_path.suffix](file_path)
  61. def _load_txt(file_path: str):
  62. with open(file_path, "r", encoding="utf8") as f:
  63. content = [
  64. x.strip().strip("\ufeff").strip("\xef\xbb\xbf") for x in f.readlines()
  65. ]
  66. return content
  67. def _load_json(file_path: str):
  68. with open(file_path, "r", encoding="utf8") as f:
  69. content = json.load(f)
  70. return content
  71. def save(data, file_path):
  72. file_path = pathlib.Path(file_path)
  73. func_dict = {".txt": _save_txt, ".json": _save_json}
  74. assert file_path.suffix in func_dict
  75. return func_dict[file_path.suffix](data, file_path)
  76. def _save_txt(data, file_path):
  77. """
  78. 将一个list的数组写入txt文件里
  79. :param data:
  80. :param file_path:
  81. :return:
  82. """
  83. if not isinstance(data, list):
  84. data = [data]
  85. with open(file_path, mode="w", encoding="utf8") as f:
  86. f.write("\n".join(data))
  87. def _save_json(data, file_path):
  88. with open(file_path, "w", encoding="utf-8") as json_file:
  89. json.dump(data, json_file, ensure_ascii=False, indent=4)
  90. def show_img(imgs: np.ndarray, title="img"):
  91. color = len(imgs.shape) == 3 and imgs.shape[-1] == 3
  92. imgs = np.expand_dims(imgs, axis=0)
  93. for i, img in enumerate(imgs):
  94. plt.figure()
  95. plt.title("{}_{}".format(title, i))
  96. plt.imshow(img, cmap=None if color else "gray")
  97. plt.show()
  98. def draw_bbox(img_path, result, color=(255, 0, 0), thickness=2):
  99. if isinstance(img_path, str):
  100. img_path = cv2.imread(img_path)
  101. # img_path = cv2.cvtColor(img_path, cv2.COLOR_BGR2RGB)
  102. img_path = img_path.copy()
  103. for point in result:
  104. point = point.astype(int)
  105. cv2.polylines(img_path, [point], True, color, thickness)
  106. return img_path
  107. def cal_text_score(texts, gt_texts, training_masks, running_metric_text, thred=0.5):
  108. training_masks = training_masks.numpy()
  109. pred_text = texts.numpy() * training_masks
  110. pred_text[pred_text <= thred] = 0
  111. pred_text[pred_text > thred] = 1
  112. pred_text = pred_text.astype(np.int32)
  113. gt_text = gt_texts.numpy() * training_masks
  114. gt_text = gt_text.astype(np.int32)
  115. running_metric_text.update(gt_text, pred_text)
  116. score_text, _ = running_metric_text.get_scores()
  117. return score_text
  118. def order_points_clockwise(pts):
  119. rect = np.zeros((4, 2), dtype="float32")
  120. s = pts.sum(axis=1)
  121. rect[0] = pts[np.argmin(s)]
  122. rect[2] = pts[np.argmax(s)]
  123. diff = np.diff(pts, axis=1)
  124. rect[1] = pts[np.argmin(diff)]
  125. rect[3] = pts[np.argmax(diff)]
  126. return rect
  127. def order_points_clockwise_list(pts):
  128. pts = pts.tolist()
  129. pts.sort(key=lambda x: (x[1], x[0]))
  130. pts[:2] = sorted(pts[:2], key=lambda x: x[0])
  131. pts[2:] = sorted(pts[2:], key=lambda x: -x[0])
  132. pts = np.array(pts)
  133. return pts
  134. def get_datalist(train_data_path):
  135. """
  136. 获取训练和验证的数据list
  137. :param train_data_path: 训练的dataset文件列表,每个文件内以如下格式存储 ‘path/to/img\tlabel’
  138. :return:
  139. """
  140. train_data = []
  141. for p in train_data_path:
  142. with open(p, "r", encoding="utf-8") as f:
  143. for line in f.readlines():
  144. line = line.strip("\n").replace(".jpg ", ".jpg\t").split("\t")
  145. if len(line) > 1:
  146. img_path = pathlib.Path(line[0].strip(" "))
  147. label_path = pathlib.Path(line[1].strip(" "))
  148. if (
  149. img_path.exists()
  150. and img_path.stat().st_size > 0
  151. and label_path.exists()
  152. and label_path.stat().st_size > 0
  153. ):
  154. train_data.append((str(img_path), str(label_path)))
  155. return train_data
  156. def save_result(result_path, box_list, score_list, is_output_polygon):
  157. if is_output_polygon:
  158. with open(result_path, "wt") as res:
  159. for i, box in enumerate(box_list):
  160. box = box.reshape(-1).tolist()
  161. result = ",".join([str(int(x)) for x in box])
  162. score = score_list[i]
  163. res.write(result + "," + str(score) + "\n")
  164. else:
  165. with open(result_path, "wt") as res:
  166. for i, box in enumerate(box_list):
  167. score = score_list[i]
  168. box = box.reshape(-1).tolist()
  169. result = ",".join([str(int(x)) for x in box])
  170. res.write(result + "," + str(score) + "\n")
  171. def expand_polygon(polygon):
  172. """
  173. 对只有一个字符的框进行扩充
  174. """
  175. (x, y), (w, h), angle = cv2.minAreaRect(np.float32(polygon))
  176. if angle < -45:
  177. w, h = h, w
  178. angle += 90
  179. new_w = w + h
  180. box = ((x, y), (new_w, h), angle)
  181. points = cv2.boxPoints(box)
  182. return order_points_clockwise(points)
  183. def _merge_dict(config, merge_dct):
  184. """Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
  185. updating only top-level keys, dict_merge recurses down into dicts nested
  186. to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
  187. ``dct``.
  188. Args:
  189. config: dict onto which the merge is executed
  190. merge_dct: dct merged into config
  191. Returns: dct
  192. """
  193. for key, value in merge_dct.items():
  194. sub_keys = key.split(".")
  195. key = sub_keys[0]
  196. if key in config and len(sub_keys) > 1:
  197. _merge_dict(config[key], {".".join(sub_keys[1:]): value})
  198. elif (
  199. key in config
  200. and isinstance(config[key], dict)
  201. and isinstance(value, Mapping)
  202. ):
  203. _merge_dict(config[key], value)
  204. else:
  205. config[key] = value
  206. return config
  207. def print_dict(cfg, print_func=print, delimiter=0):
  208. """
  209. Recursively visualize a dict and
  210. indenting acrrording by the relationship of keys.
  211. """
  212. for k, v in sorted(cfg.items()):
  213. if isinstance(v, dict):
  214. print_func("{}{} : ".format(delimiter * " ", str(k)))
  215. print_dict(v, print_func, delimiter + 4)
  216. elif isinstance(v, list) and len(v) >= 1 and isinstance(v[0], dict):
  217. print_func("{}{} : ".format(delimiter * " ", str(k)))
  218. for value in v:
  219. print_dict(value, print_func, delimiter + 4)
  220. else:
  221. print_func("{}{} : {}".format(delimiter * " ", k, v))
  222. class Config(object):
  223. def __init__(self, config_path, BASE_KEY="base"):
  224. self.BASE_KEY = BASE_KEY
  225. self.cfg = self._load_config_with_base(config_path)
  226. def _load_config_with_base(self, file_path):
  227. """
  228. Load config from file.
  229. Args:
  230. file_path (str): Path of the config file to be loaded.
  231. Returns: global config
  232. """
  233. _, ext = os.path.splitext(file_path)
  234. assert ext in [".yml", ".yaml"], "only support yaml files for now"
  235. with open(file_path) as f:
  236. file_cfg = yaml.load(f, Loader=yaml.Loader)
  237. # NOTE: cfgs outside have higher priority than cfgs in _BASE_
  238. if self.BASE_KEY in file_cfg:
  239. all_base_cfg = dict()
  240. base_ymls = list(file_cfg[self.BASE_KEY])
  241. for base_yml in base_ymls:
  242. with open(base_yml) as f:
  243. base_cfg = self._load_config_with_base(base_yml)
  244. all_base_cfg = _merge_dict(all_base_cfg, base_cfg)
  245. del file_cfg[self.BASE_KEY]
  246. file_cfg = _merge_dict(all_base_cfg, file_cfg)
  247. file_cfg["filename"] = os.path.splitext(os.path.split(file_path)[-1])[0]
  248. return file_cfg
  249. def merge_dict(self, args):
  250. self.cfg = _merge_dict(self.cfg, args)
  251. def print_cfg(self, print_func=print):
  252. """
  253. Recursively visualize a dict and
  254. indenting according by the relationship of keys.
  255. """
  256. print_func("----------- Config -----------")
  257. print_dict(self.cfg, print_func)
  258. print_func("---------------------------------------------")
  259. def save(self, p):
  260. with open(p, "w") as f:
  261. yaml.dump(dict(self.cfg), f, default_flow_style=False, sort_keys=False)
  262. class ArgsParser(ArgumentParser):
  263. def __init__(self):
  264. super(ArgsParser, self).__init__(formatter_class=RawDescriptionHelpFormatter)
  265. self.add_argument("-c", "--config_file", help="configuration file to use")
  266. self.add_argument("-o", "--opt", nargs="*", help="set configuration options")
  267. self.add_argument(
  268. "-p",
  269. "--profiler_options",
  270. type=str,
  271. default=None,
  272. help="The option of profiler, which should be in format "
  273. '"key1=value1;key2=value2;key3=value3".',
  274. )
  275. def parse_args(self, argv=None):
  276. args = super(ArgsParser, self).parse_args(argv)
  277. assert (
  278. args.config_file is not None
  279. ), "Please specify --config_file=configure_file_path."
  280. args.opt = self._parse_opt(args.opt)
  281. return args
  282. def _parse_opt(self, opts):
  283. config = {}
  284. if not opts:
  285. return config
  286. for s in opts:
  287. s = s.strip()
  288. k, v = s.split("=", 1)
  289. if "." not in k:
  290. config[k] = yaml.load(v, Loader=yaml.Loader)
  291. else:
  292. keys = k.split(".")
  293. if keys[0] not in config:
  294. config[keys[0]] = {}
  295. cur = config[keys[0]]
  296. for idx, key in enumerate(keys[1:]):
  297. if idx == len(keys) - 2:
  298. cur[key] = yaml.load(v, Loader=yaml.Loader)
  299. else:
  300. cur[key] = {}
  301. cur = cur[key]
  302. return config
  303. if __name__ == "__main__":
  304. img = np.zeros((1, 3, 640, 640))
  305. show_img(img[0][0])
  306. plt.show()