sast_postprocess.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. __dir__ = os.path.dirname(__file__)
  20. sys.path.append(__dir__)
  21. sys.path.append(os.path.join(__dir__, '..'))
  22. import numpy as np
  23. from .locality_aware_nms import nms_locality
  24. import paddle
  25. import cv2
  26. import time
  27. class SASTPostProcess(object):
  28. """
  29. The post process for SAST.
  30. """
  31. def __init__(self,
  32. score_thresh=0.5,
  33. nms_thresh=0.2,
  34. sample_pts_num=2,
  35. shrink_ratio_of_width=0.3,
  36. expand_scale=1.0,
  37. tcl_map_thresh=0.5,
  38. **kwargs):
  39. self.score_thresh = score_thresh
  40. self.nms_thresh = nms_thresh
  41. self.sample_pts_num = sample_pts_num
  42. self.shrink_ratio_of_width = shrink_ratio_of_width
  43. self.expand_scale = expand_scale
  44. self.tcl_map_thresh = tcl_map_thresh
  45. # c++ la-nms is faster, but only support python 3.5
  46. self.is_python35 = False
  47. if sys.version_info.major == 3 and sys.version_info.minor == 5:
  48. self.is_python35 = True
  49. def point_pair2poly(self, point_pair_list):
  50. """
  51. Transfer vertical point_pairs into poly point in clockwise.
  52. """
  53. # constract poly
  54. point_num = len(point_pair_list) * 2
  55. point_list = [0] * point_num
  56. for idx, point_pair in enumerate(point_pair_list):
  57. point_list[idx] = point_pair[0]
  58. point_list[point_num - 1 - idx] = point_pair[1]
  59. return np.array(point_list).reshape(-1, 2)
  60. def shrink_quad_along_width(self, quad, begin_width_ratio=0., end_width_ratio=1.):
  61. """
  62. Generate shrink_quad_along_width.
  63. """
  64. ratio_pair = np.array([[begin_width_ratio], [end_width_ratio]], dtype=np.float32)
  65. p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair
  66. p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair
  67. return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])
  68. def expand_poly_along_width(self, poly, shrink_ratio_of_width=0.3):
  69. """
  70. expand poly along width.
  71. """
  72. point_num = poly.shape[0]
  73. left_quad = np.array([poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)
  74. left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \
  75. (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)
  76. left_quad_expand = self.shrink_quad_along_width(left_quad, left_ratio, 1.0)
  77. right_quad = np.array([poly[point_num // 2 - 2], poly[point_num // 2 - 1],
  78. poly[point_num // 2], poly[point_num // 2 + 1]], dtype=np.float32)
  79. right_ratio = 1.0 + \
  80. shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \
  81. (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)
  82. right_quad_expand = self.shrink_quad_along_width(right_quad, 0.0, right_ratio)
  83. poly[0] = left_quad_expand[0]
  84. poly[-1] = left_quad_expand[-1]
  85. poly[point_num // 2 - 1] = right_quad_expand[1]
  86. poly[point_num // 2] = right_quad_expand[2]
  87. return poly
  88. def restore_quad(self, tcl_map, tcl_map_thresh, tvo_map):
  89. """Restore quad."""
  90. xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)
  91. xy_text = xy_text[:, ::-1] # (n, 2)
  92. # Sort the text boxes via the y axis
  93. xy_text = xy_text[np.argsort(xy_text[:, 1])]
  94. scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]
  95. scores = scores[:, np.newaxis]
  96. # Restore
  97. point_num = int(tvo_map.shape[-1] / 2)
  98. assert point_num == 4
  99. tvo_map = tvo_map[xy_text[:, 1], xy_text[:, 0], :]
  100. xy_text_tile = np.tile(xy_text, (1, point_num)) # (n, point_num * 2)
  101. quads = xy_text_tile - tvo_map
  102. return scores, quads, xy_text
  103. def quad_area(self, quad):
  104. """
  105. compute area of a quad.
  106. """
  107. edge = [
  108. (quad[1][0] - quad[0][0]) * (quad[1][1] + quad[0][1]),
  109. (quad[2][0] - quad[1][0]) * (quad[2][1] + quad[1][1]),
  110. (quad[3][0] - quad[2][0]) * (quad[3][1] + quad[2][1]),
  111. (quad[0][0] - quad[3][0]) * (quad[0][1] + quad[3][1])
  112. ]
  113. return np.sum(edge) / 2.
  114. def nms(self, dets):
  115. if self.is_python35:
  116. import lanms
  117. dets = lanms.merge_quadrangle_n9(dets, self.nms_thresh)
  118. else:
  119. dets = nms_locality(dets, self.nms_thresh)
  120. return dets
  121. def cluster_by_quads_tco(self, tcl_map, tcl_map_thresh, quads, tco_map):
  122. """
  123. Cluster pixels in tcl_map based on quads.
  124. """
  125. instance_count = quads.shape[0] + 1 # contain background
  126. instance_label_map = np.zeros(tcl_map.shape[:2], dtype=np.int32)
  127. if instance_count == 1:
  128. return instance_count, instance_label_map
  129. # predict text center
  130. xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)
  131. n = xy_text.shape[0]
  132. xy_text = xy_text[:, ::-1] # (n, 2)
  133. tco = tco_map[xy_text[:, 1], xy_text[:, 0], :] # (n, 2)
  134. pred_tc = xy_text - tco
  135. # get gt text center
  136. m = quads.shape[0]
  137. gt_tc = np.mean(quads, axis=1) # (m, 2)
  138. pred_tc_tile = np.tile(pred_tc[:, np.newaxis, :], (1, m, 1)) # (n, m, 2)
  139. gt_tc_tile = np.tile(gt_tc[np.newaxis, :, :], (n, 1, 1)) # (n, m, 2)
  140. dist_mat = np.linalg.norm(pred_tc_tile - gt_tc_tile, axis=2) # (n, m)
  141. xy_text_assign = np.argmin(dist_mat, axis=1) + 1 # (n,)
  142. instance_label_map[xy_text[:, 1], xy_text[:, 0]] = xy_text_assign
  143. return instance_count, instance_label_map
  144. def estimate_sample_pts_num(self, quad, xy_text):
  145. """
  146. Estimate sample points number.
  147. """
  148. eh = (np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - quad[2])) / 2.0
  149. ew = (np.linalg.norm(quad[0] - quad[1]) + np.linalg.norm(quad[2] - quad[3])) / 2.0
  150. dense_sample_pts_num = max(2, int(ew))
  151. dense_xy_center_line = xy_text[np.linspace(0, xy_text.shape[0] - 1, dense_sample_pts_num,
  152. endpoint=True, dtype=np.float32).astype(np.int32)]
  153. dense_xy_center_line_diff = dense_xy_center_line[1:] - dense_xy_center_line[:-1]
  154. estimate_arc_len = np.sum(np.linalg.norm(dense_xy_center_line_diff, axis=1))
  155. sample_pts_num = max(2, int(estimate_arc_len / eh))
  156. return sample_pts_num
  157. def detect_sast(self, tcl_map, tvo_map, tbo_map, tco_map, ratio_w, ratio_h, src_w, src_h,
  158. shrink_ratio_of_width=0.3, tcl_map_thresh=0.5, offset_expand=1.0, out_strid=4.0):
  159. """
  160. first resize the tcl_map, tvo_map and tbo_map to the input_size, then restore the polys
  161. """
  162. # restore quad
  163. scores, quads, xy_text = self.restore_quad(tcl_map, tcl_map_thresh, tvo_map)
  164. dets = np.hstack((quads, scores)).astype(np.float32, copy=False)
  165. dets = self.nms(dets)
  166. if dets.shape[0] == 0:
  167. return []
  168. quads = dets[:, :-1].reshape(-1, 4, 2)
  169. # Compute quad area
  170. quad_areas = []
  171. for quad in quads:
  172. quad_areas.append(-self.quad_area(quad))
  173. # instance segmentation
  174. # instance_count, instance_label_map = cv2.connectedComponents(tcl_map.astype(np.uint8), connectivity=8)
  175. instance_count, instance_label_map = self.cluster_by_quads_tco(tcl_map, tcl_map_thresh, quads, tco_map)
  176. # restore single poly with tcl instance.
  177. poly_list = []
  178. for instance_idx in range(1, instance_count):
  179. xy_text = np.argwhere(instance_label_map == instance_idx)[:, ::-1]
  180. quad = quads[instance_idx - 1]
  181. q_area = quad_areas[instance_idx - 1]
  182. if q_area < 5:
  183. continue
  184. #
  185. len1 = float(np.linalg.norm(quad[0] -quad[1]))
  186. len2 = float(np.linalg.norm(quad[1] -quad[2]))
  187. min_len = min(len1, len2)
  188. if min_len < 3:
  189. continue
  190. # filter small CC
  191. if xy_text.shape[0] <= 0:
  192. continue
  193. # filter low confidence instance
  194. xy_text_scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]
  195. if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.1:
  196. # if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.05:
  197. continue
  198. # sort xy_text
  199. left_center_pt = np.array([[(quad[0, 0] + quad[-1, 0]) / 2.0,
  200. (quad[0, 1] + quad[-1, 1]) / 2.0]]) # (1, 2)
  201. right_center_pt = np.array([[(quad[1, 0] + quad[2, 0]) / 2.0,
  202. (quad[1, 1] + quad[2, 1]) / 2.0]]) # (1, 2)
  203. proj_unit_vec = (right_center_pt - left_center_pt) / \
  204. (np.linalg.norm(right_center_pt - left_center_pt) + 1e-6)
  205. proj_value = np.sum(xy_text * proj_unit_vec, axis=1)
  206. xy_text = xy_text[np.argsort(proj_value)]
  207. # Sample pts in tcl map
  208. if self.sample_pts_num == 0:
  209. sample_pts_num = self.estimate_sample_pts_num(quad, xy_text)
  210. else:
  211. sample_pts_num = self.sample_pts_num
  212. xy_center_line = xy_text[np.linspace(0, xy_text.shape[0] - 1, sample_pts_num,
  213. endpoint=True, dtype=np.float32).astype(np.int32)]
  214. point_pair_list = []
  215. for x, y in xy_center_line:
  216. # get corresponding offset
  217. offset = tbo_map[y, x, :].reshape(2, 2)
  218. if offset_expand != 1.0:
  219. offset_length = np.linalg.norm(offset, axis=1, keepdims=True)
  220. expand_length = np.clip(offset_length * (offset_expand - 1), a_min=0.5, a_max=3.0)
  221. offset_detal = offset / offset_length * expand_length
  222. offset = offset + offset_detal
  223. # original point
  224. ori_yx = np.array([y, x], dtype=np.float32)
  225. point_pair = (ori_yx + offset)[:, ::-1]* out_strid / np.array([ratio_w, ratio_h]).reshape(-1, 2)
  226. point_pair_list.append(point_pair)
  227. # ndarry: (x, 2), expand poly along width
  228. detected_poly = self.point_pair2poly(point_pair_list)
  229. detected_poly = self.expand_poly_along_width(detected_poly, shrink_ratio_of_width)
  230. detected_poly[:, 0] = np.clip(detected_poly[:, 0], a_min=0, a_max=src_w)
  231. detected_poly[:, 1] = np.clip(detected_poly[:, 1], a_min=0, a_max=src_h)
  232. poly_list.append(detected_poly)
  233. return poly_list
  234. def __call__(self, outs_dict, shape_list):
  235. score_list = outs_dict['f_score']
  236. border_list = outs_dict['f_border']
  237. tvo_list = outs_dict['f_tvo']
  238. tco_list = outs_dict['f_tco']
  239. if isinstance(score_list, paddle.Tensor):
  240. score_list = score_list.numpy()
  241. border_list = border_list.numpy()
  242. tvo_list = tvo_list.numpy()
  243. tco_list = tco_list.numpy()
  244. img_num = len(shape_list)
  245. poly_lists = []
  246. for ino in range(img_num):
  247. p_score = score_list[ino].transpose((1,2,0))
  248. p_border = border_list[ino].transpose((1,2,0))
  249. p_tvo = tvo_list[ino].transpose((1,2,0))
  250. p_tco = tco_list[ino].transpose((1,2,0))
  251. src_h, src_w, ratio_h, ratio_w = shape_list[ino]
  252. poly_list = self.detect_sast(p_score, p_tvo, p_border, p_tco, ratio_w, ratio_h, src_w, src_h,
  253. shrink_ratio_of_width=self.shrink_ratio_of_width,
  254. tcl_map_thresh=self.tcl_map_thresh, offset_expand=self.expand_scale)
  255. poly_lists.append({'points': np.array(poly_list)})
  256. return poly_lists