sast_postprocess.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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,
  61. quad,
  62. begin_width_ratio=0.,
  63. end_width_ratio=1.):
  64. """
  65. Generate shrink_quad_along_width.
  66. """
  67. ratio_pair = np.array(
  68. [[begin_width_ratio], [end_width_ratio]], dtype=np.float32)
  69. p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair
  70. p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair
  71. return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])
  72. def expand_poly_along_width(self, poly, shrink_ratio_of_width=0.3):
  73. """
  74. expand poly along width.
  75. """
  76. point_num = poly.shape[0]
  77. left_quad = np.array(
  78. [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)
  79. left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \
  80. (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)
  81. left_quad_expand = self.shrink_quad_along_width(left_quad, left_ratio,
  82. 1.0)
  83. right_quad = np.array(
  84. [
  85. poly[point_num // 2 - 2], poly[point_num // 2 - 1],
  86. poly[point_num // 2], poly[point_num // 2 + 1]
  87. ],
  88. dtype=np.float32)
  89. right_ratio = 1.0 + \
  90. shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \
  91. (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)
  92. right_quad_expand = self.shrink_quad_along_width(right_quad, 0.0,
  93. right_ratio)
  94. poly[0] = left_quad_expand[0]
  95. poly[-1] = left_quad_expand[-1]
  96. poly[point_num // 2 - 1] = right_quad_expand[1]
  97. poly[point_num // 2] = right_quad_expand[2]
  98. return poly
  99. def restore_quad(self, tcl_map, tcl_map_thresh, tvo_map):
  100. """Restore quad."""
  101. xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)
  102. xy_text = xy_text[:, ::-1] # (n, 2)
  103. # Sort the text boxes via the y axis
  104. xy_text = xy_text[np.argsort(xy_text[:, 1])]
  105. scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]
  106. scores = scores[:, np.newaxis]
  107. # Restore
  108. point_num = int(tvo_map.shape[-1] / 2)
  109. assert point_num == 4
  110. tvo_map = tvo_map[xy_text[:, 1], xy_text[:, 0], :]
  111. xy_text_tile = np.tile(xy_text, (1, point_num)) # (n, point_num * 2)
  112. quads = xy_text_tile - tvo_map
  113. return scores, quads, xy_text
  114. def quad_area(self, quad):
  115. """
  116. compute area of a quad.
  117. """
  118. edge = [(quad[1][0] - quad[0][0]) * (quad[1][1] + quad[0][1]),
  119. (quad[2][0] - quad[1][0]) * (quad[2][1] + quad[1][1]),
  120. (quad[3][0] - quad[2][0]) * (quad[3][1] + quad[2][1]),
  121. (quad[0][0] - quad[3][0]) * (quad[0][1] + quad[3][1])]
  122. return np.sum(edge) / 2.
  123. def nms(self, dets):
  124. if self.is_python35:
  125. import lanms
  126. dets = lanms.merge_quadrangle_n9(dets, self.nms_thresh)
  127. else:
  128. dets = nms_locality(dets, self.nms_thresh)
  129. return dets
  130. def cluster_by_quads_tco(self, tcl_map, tcl_map_thresh, quads, tco_map):
  131. """
  132. Cluster pixels in tcl_map based on quads.
  133. """
  134. instance_count = quads.shape[0] + 1 # contain background
  135. instance_label_map = np.zeros(tcl_map.shape[:2], dtype=np.int32)
  136. if instance_count == 1:
  137. return instance_count, instance_label_map
  138. # predict text center
  139. xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)
  140. n = xy_text.shape[0]
  141. xy_text = xy_text[:, ::-1] # (n, 2)
  142. tco = tco_map[xy_text[:, 1], xy_text[:, 0], :] # (n, 2)
  143. pred_tc = xy_text - tco
  144. # get gt text center
  145. m = quads.shape[0]
  146. gt_tc = np.mean(quads, axis=1) # (m, 2)
  147. pred_tc_tile = np.tile(pred_tc[:, np.newaxis, :],
  148. (1, m, 1)) # (n, m, 2)
  149. gt_tc_tile = np.tile(gt_tc[np.newaxis, :, :], (n, 1, 1)) # (n, m, 2)
  150. dist_mat = np.linalg.norm(pred_tc_tile - gt_tc_tile, axis=2) # (n, m)
  151. xy_text_assign = np.argmin(dist_mat, axis=1) + 1 # (n,)
  152. instance_label_map[xy_text[:, 1], xy_text[:, 0]] = xy_text_assign
  153. return instance_count, instance_label_map
  154. def estimate_sample_pts_num(self, quad, xy_text):
  155. """
  156. Estimate sample points number.
  157. """
  158. eh = (np.linalg.norm(quad[0] - quad[3]) +
  159. np.linalg.norm(quad[1] - quad[2])) / 2.0
  160. ew = (np.linalg.norm(quad[0] - quad[1]) +
  161. np.linalg.norm(quad[2] - quad[3])) / 2.0
  162. dense_sample_pts_num = max(2, int(ew))
  163. dense_xy_center_line = xy_text[np.linspace(
  164. 0,
  165. xy_text.shape[0] - 1,
  166. dense_sample_pts_num,
  167. endpoint=True,
  168. dtype=np.float32).astype(np.int32)]
  169. dense_xy_center_line_diff = dense_xy_center_line[
  170. 1:] - dense_xy_center_line[:-1]
  171. estimate_arc_len = np.sum(
  172. np.linalg.norm(
  173. dense_xy_center_line_diff, axis=1))
  174. sample_pts_num = max(2, int(estimate_arc_len / eh))
  175. return sample_pts_num
  176. def detect_sast(self,
  177. tcl_map,
  178. tvo_map,
  179. tbo_map,
  180. tco_map,
  181. ratio_w,
  182. ratio_h,
  183. src_w,
  184. src_h,
  185. shrink_ratio_of_width=0.3,
  186. tcl_map_thresh=0.5,
  187. offset_expand=1.0,
  188. out_strid=4.0):
  189. """
  190. first resize the tcl_map, tvo_map and tbo_map to the input_size, then restore the polys
  191. """
  192. # restore quad
  193. scores, quads, xy_text = self.restore_quad(tcl_map, tcl_map_thresh,
  194. tvo_map)
  195. dets = np.hstack((quads, scores)).astype(np.float32, copy=False)
  196. dets = self.nms(dets)
  197. if dets.shape[0] == 0:
  198. return []
  199. quads = dets[:, :-1].reshape(-1, 4, 2)
  200. # Compute quad area
  201. quad_areas = []
  202. for quad in quads:
  203. quad_areas.append(-self.quad_area(quad))
  204. # instance segmentation
  205. # instance_count, instance_label_map = cv2.connectedComponents(tcl_map.astype(np.uint8), connectivity=8)
  206. instance_count, instance_label_map = self.cluster_by_quads_tco(
  207. tcl_map, tcl_map_thresh, quads, tco_map)
  208. # restore single poly with tcl instance.
  209. poly_list = []
  210. for instance_idx in range(1, instance_count):
  211. xy_text = np.argwhere(instance_label_map == instance_idx)[:, ::-1]
  212. quad = quads[instance_idx - 1]
  213. q_area = quad_areas[instance_idx - 1]
  214. if q_area < 5:
  215. continue
  216. #
  217. len1 = float(np.linalg.norm(quad[0] - quad[1]))
  218. len2 = float(np.linalg.norm(quad[1] - quad[2]))
  219. min_len = min(len1, len2)
  220. if min_len < 3:
  221. continue
  222. # filter small CC
  223. if xy_text.shape[0] <= 0:
  224. continue
  225. # filter low confidence instance
  226. xy_text_scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]
  227. if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.1:
  228. # if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.05:
  229. continue
  230. # sort xy_text
  231. left_center_pt = np.array(
  232. [[(quad[0, 0] + quad[-1, 0]) / 2.0,
  233. (quad[0, 1] + quad[-1, 1]) / 2.0]]) # (1, 2)
  234. right_center_pt = np.array(
  235. [[(quad[1, 0] + quad[2, 0]) / 2.0,
  236. (quad[1, 1] + quad[2, 1]) / 2.0]]) # (1, 2)
  237. proj_unit_vec = (right_center_pt - left_center_pt) / \
  238. (np.linalg.norm(right_center_pt - left_center_pt) + 1e-6)
  239. proj_value = np.sum(xy_text * proj_unit_vec, axis=1)
  240. xy_text = xy_text[np.argsort(proj_value)]
  241. # Sample pts in tcl map
  242. if self.sample_pts_num == 0:
  243. sample_pts_num = self.estimate_sample_pts_num(quad, xy_text)
  244. else:
  245. sample_pts_num = self.sample_pts_num
  246. xy_center_line = xy_text[np.linspace(
  247. 0,
  248. xy_text.shape[0] - 1,
  249. sample_pts_num,
  250. endpoint=True,
  251. dtype=np.float32).astype(np.int32)]
  252. point_pair_list = []
  253. for x, y in xy_center_line:
  254. # get corresponding offset
  255. offset = tbo_map[y, x, :].reshape(2, 2)
  256. if offset_expand != 1.0:
  257. offset_length = np.linalg.norm(
  258. offset, axis=1, keepdims=True)
  259. expand_length = np.clip(
  260. offset_length * (offset_expand - 1),
  261. a_min=0.5,
  262. a_max=3.0)
  263. offset_detal = offset / offset_length * expand_length
  264. offset = offset + offset_detal
  265. # original point
  266. ori_yx = np.array([y, x], dtype=np.float32)
  267. point_pair = (ori_yx + offset)[:, ::-1] * out_strid / np.array(
  268. [ratio_w, ratio_h]).reshape(-1, 2)
  269. point_pair_list.append(point_pair)
  270. # ndarry: (x, 2), expand poly along width
  271. detected_poly = self.point_pair2poly(point_pair_list)
  272. detected_poly = self.expand_poly_along_width(detected_poly,
  273. shrink_ratio_of_width)
  274. detected_poly[:, 0] = np.clip(
  275. detected_poly[:, 0], a_min=0, a_max=src_w)
  276. detected_poly[:, 1] = np.clip(
  277. detected_poly[:, 1], a_min=0, a_max=src_h)
  278. poly_list.append(detected_poly)
  279. return poly_list
  280. def __call__(self, outs_dict, shape_list):
  281. score_list = outs_dict['f_score']
  282. border_list = outs_dict['f_border']
  283. tvo_list = outs_dict['f_tvo']
  284. tco_list = outs_dict['f_tco']
  285. if isinstance(score_list, paddle.Tensor):
  286. score_list = score_list.numpy()
  287. border_list = border_list.numpy()
  288. tvo_list = tvo_list.numpy()
  289. tco_list = tco_list.numpy()
  290. img_num = len(shape_list)
  291. poly_lists = []
  292. for ino in range(img_num):
  293. p_score = score_list[ino].transpose((1, 2, 0))
  294. p_border = border_list[ino].transpose((1, 2, 0))
  295. p_tvo = tvo_list[ino].transpose((1, 2, 0))
  296. p_tco = tco_list[ino].transpose((1, 2, 0))
  297. src_h, src_w, ratio_h, ratio_w = shape_list[ino]
  298. poly_list = self.detect_sast(
  299. p_score,
  300. p_tvo,
  301. p_border,
  302. p_tco,
  303. ratio_w,
  304. ratio_h,
  305. src_w,
  306. src_h,
  307. shrink_ratio_of_width=self.shrink_ratio_of_width,
  308. tcl_map_thresh=self.tcl_map_thresh,
  309. offset_expand=self.expand_scale)
  310. poly_lists.append({'points': np.array(poly_list)})
  311. return poly_lists