vehicleplate_postprocess.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. import paddle
  16. from paddle.nn import functional as F
  17. import re
  18. from shapely.geometry import Polygon
  19. import cv2
  20. import copy
  21. def build_post_process(config, global_config=None):
  22. support_dict = ['DBPostProcess', 'CTCLabelDecode']
  23. config = copy.deepcopy(config)
  24. module_name = config.pop('name')
  25. if module_name == "None":
  26. return
  27. if global_config is not None:
  28. config.update(global_config)
  29. assert module_name in support_dict, Exception(
  30. 'post process only support {}'.format(support_dict))
  31. module_class = eval(module_name)(**config)
  32. return module_class
  33. class DBPostProcess(object):
  34. """
  35. The post process for Differentiable Binarization (DB).
  36. """
  37. def __init__(self,
  38. thresh=0.3,
  39. box_thresh=0.7,
  40. max_candidates=1000,
  41. unclip_ratio=2.0,
  42. use_dilation=False,
  43. score_mode="fast",
  44. **kwargs):
  45. self.thresh = thresh
  46. self.box_thresh = box_thresh
  47. self.max_candidates = max_candidates
  48. self.unclip_ratio = unclip_ratio
  49. self.min_size = 3
  50. self.score_mode = score_mode
  51. assert score_mode in [
  52. "slow", "fast"
  53. ], "Score mode must be in [slow, fast] but got: {}".format(score_mode)
  54. self.dilation_kernel = None if not use_dilation else np.array(
  55. [[1, 1], [1, 1]])
  56. def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
  57. '''
  58. _bitmap: single map with shape (1, H, W),
  59. whose values are binarized as {0, 1}
  60. '''
  61. bitmap = _bitmap
  62. height, width = bitmap.shape
  63. outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST,
  64. cv2.CHAIN_APPROX_SIMPLE)
  65. if len(outs) == 3:
  66. img, contours, _ = outs[0], outs[1], outs[2]
  67. elif len(outs) == 2:
  68. contours, _ = outs[0], outs[1]
  69. num_contours = min(len(contours), self.max_candidates)
  70. boxes = []
  71. scores = []
  72. for index in range(num_contours):
  73. contour = contours[index]
  74. points, sside = self.get_mini_boxes(contour)
  75. if sside < self.min_size:
  76. continue
  77. points = np.array(points)
  78. if self.score_mode == "fast":
  79. score = self.box_score_fast(pred, points.reshape(-1, 2))
  80. else:
  81. score = self.box_score_slow(pred, contour)
  82. if self.box_thresh > score:
  83. continue
  84. box = self.unclip(points).reshape(-1, 1, 2)
  85. box, sside = self.get_mini_boxes(box)
  86. if sside < self.min_size + 2:
  87. continue
  88. box = np.array(box)
  89. box[:, 0] = np.clip(
  90. np.round(box[:, 0] / width * dest_width), 0, dest_width)
  91. box[:, 1] = np.clip(
  92. np.round(box[:, 1] / height * dest_height), 0, dest_height)
  93. boxes.append(box.astype(np.int16))
  94. scores.append(score)
  95. return np.array(boxes, dtype=np.int16), scores
  96. def unclip(self, box):
  97. try:
  98. import pyclipper
  99. except Exception as e:
  100. raise RuntimeError(
  101. 'Unable to use vehicleplate postprocess in PP-Vehicle, please install pyclipper, for example: `pip install pyclipper`, see https://github.com/fonttools/pyclipper'
  102. )
  103. unclip_ratio = self.unclip_ratio
  104. poly = Polygon(box)
  105. distance = poly.area * unclip_ratio / poly.length
  106. offset = pyclipper.PyclipperOffset()
  107. offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
  108. expanded = np.array(offset.Execute(distance))
  109. return expanded
  110. def get_mini_boxes(self, contour):
  111. bounding_box = cv2.minAreaRect(contour)
  112. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  113. index_1, index_2, index_3, index_4 = 0, 1, 2, 3
  114. if points[1][1] > points[0][1]:
  115. index_1 = 0
  116. index_4 = 1
  117. else:
  118. index_1 = 1
  119. index_4 = 0
  120. if points[3][1] > points[2][1]:
  121. index_2 = 2
  122. index_3 = 3
  123. else:
  124. index_2 = 3
  125. index_3 = 2
  126. box = [
  127. points[index_1], points[index_2], points[index_3], points[index_4]
  128. ]
  129. return box, min(bounding_box[1])
  130. def box_score_fast(self, bitmap, _box):
  131. '''
  132. box_score_fast: use bbox mean score as the mean score
  133. '''
  134. h, w = bitmap.shape[:2]
  135. box = _box.copy()
  136. xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1)
  137. xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1)
  138. ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1)
  139. ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1)
  140. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  141. box[:, 0] = box[:, 0] - xmin
  142. box[:, 1] = box[:, 1] - ymin
  143. cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
  144. return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
  145. def box_score_slow(self, bitmap, contour):
  146. '''
  147. box_score_slow: use polyon mean score as the mean score
  148. '''
  149. h, w = bitmap.shape[:2]
  150. contour = contour.copy()
  151. contour = np.reshape(contour, (-1, 2))
  152. xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
  153. xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
  154. ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
  155. ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)
  156. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  157. contour[:, 0] = contour[:, 0] - xmin
  158. contour[:, 1] = contour[:, 1] - ymin
  159. cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1)
  160. return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
  161. def __call__(self, outs_dict, shape_list):
  162. pred = outs_dict['maps']
  163. if isinstance(pred, paddle.Tensor):
  164. pred = pred.numpy()
  165. pred = pred[:, 0, :, :]
  166. segmentation = pred > self.thresh
  167. boxes_batch = []
  168. for batch_index in range(pred.shape[0]):
  169. src_h, src_w = shape_list[batch_index]
  170. if self.dilation_kernel is not None:
  171. mask = cv2.dilate(
  172. np.array(segmentation[batch_index]).astype(np.uint8),
  173. self.dilation_kernel)
  174. else:
  175. mask = segmentation[batch_index]
  176. boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask,
  177. src_w, src_h)
  178. boxes_batch.append({'points': boxes})
  179. return boxes_batch
  180. class BaseRecLabelDecode(object):
  181. """ Convert between text-label and text-index """
  182. def __init__(self, character_dict_path=None, use_space_char=False):
  183. self.beg_str = "sos"
  184. self.end_str = "eos"
  185. self.character_str = []
  186. if character_dict_path is None:
  187. self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
  188. dict_character = list(self.character_str)
  189. else:
  190. with open(character_dict_path, "rb") as fin:
  191. lines = fin.readlines()
  192. for line in lines:
  193. line = line.decode('utf-8').strip("\n").strip("\r\n")
  194. self.character_str.append(line)
  195. if use_space_char:
  196. self.character_str.append(" ")
  197. dict_character = list(self.character_str)
  198. dict_character = self.add_special_char(dict_character)
  199. self.dict = {}
  200. for i, char in enumerate(dict_character):
  201. self.dict[char] = i
  202. self.character = dict_character
  203. def add_special_char(self, dict_character):
  204. return dict_character
  205. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  206. """ convert text-index into text-label. """
  207. result_list = []
  208. ignored_tokens = self.get_ignored_tokens()
  209. batch_size = len(text_index)
  210. for batch_idx in range(batch_size):
  211. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  212. if is_remove_duplicate:
  213. selection[1:] = text_index[batch_idx][1:] != text_index[
  214. batch_idx][:-1]
  215. for ignored_token in ignored_tokens:
  216. selection &= text_index[batch_idx] != ignored_token
  217. char_list = [
  218. self.character[text_id]
  219. for text_id in text_index[batch_idx][selection]
  220. ]
  221. if text_prob is not None:
  222. conf_list = text_prob[batch_idx][selection]
  223. else:
  224. conf_list = [1] * len(selection)
  225. if len(conf_list) == 0:
  226. conf_list = [0]
  227. text = ''.join(char_list)
  228. result_list.append((text, np.mean(conf_list).tolist()))
  229. return result_list
  230. def get_ignored_tokens(self):
  231. return [0] # for ctc blank
  232. class CTCLabelDecode(BaseRecLabelDecode):
  233. """ Convert between text-label and text-index """
  234. def __init__(self, character_dict_path=None, use_space_char=False,
  235. **kwargs):
  236. super(CTCLabelDecode, self).__init__(character_dict_path,
  237. use_space_char)
  238. def __call__(self, preds, label=None, *args, **kwargs):
  239. if isinstance(preds, tuple) or isinstance(preds, list):
  240. preds = preds[-1]
  241. if isinstance(preds, paddle.Tensor):
  242. preds = preds.numpy()
  243. preds_idx = preds.argmax(axis=2)
  244. preds_prob = preds.max(axis=2)
  245. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  246. if label is None:
  247. return text
  248. label = self.decode(label)
  249. return text, label
  250. def add_special_char(self, dict_character):
  251. dict_character = ['blank'] + dict_character
  252. return dict_character