fce_targets.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. """
  15. This code is refer from:
  16. https://github.com/open-mmlab/mmocr/blob/main/mmocr/datasets/pipelines/textdet_targets/fcenet_targets.py
  17. """
  18. import cv2
  19. import numpy as np
  20. from numpy.fft import fft
  21. from numpy.linalg import norm
  22. import sys
  23. def vector_slope(vec):
  24. assert len(vec) == 2
  25. return abs(vec[1] / (vec[0] + 1e-8))
  26. class FCENetTargets:
  27. """Generate the ground truth targets of FCENet: Fourier Contour Embedding
  28. for Arbitrary-Shaped Text Detection.
  29. [https://arxiv.org/abs/2104.10442]
  30. Args:
  31. fourier_degree (int): The maximum Fourier transform degree k.
  32. resample_step (float): The step size for resampling the text center
  33. line (TCL). It's better not to exceed half of the minimum width.
  34. center_region_shrink_ratio (float): The shrink ratio of text center
  35. region.
  36. level_size_divisors (tuple(int)): The downsample ratio on each level.
  37. level_proportion_range (tuple(tuple(int))): The range of text sizes
  38. assigned to each level.
  39. """
  40. def __init__(self,
  41. fourier_degree=5,
  42. resample_step=4.0,
  43. center_region_shrink_ratio=0.3,
  44. level_size_divisors=(8, 16, 32),
  45. level_proportion_range=((0, 0.25), (0.2, 0.65), (0.55, 1.0)),
  46. orientation_thr=2.0,
  47. **kwargs):
  48. super().__init__()
  49. assert isinstance(level_size_divisors, tuple)
  50. assert isinstance(level_proportion_range, tuple)
  51. assert len(level_size_divisors) == len(level_proportion_range)
  52. self.fourier_degree = fourier_degree
  53. self.resample_step = resample_step
  54. self.center_region_shrink_ratio = center_region_shrink_ratio
  55. self.level_size_divisors = level_size_divisors
  56. self.level_proportion_range = level_proportion_range
  57. self.orientation_thr = orientation_thr
  58. def vector_angle(self, vec1, vec2):
  59. if vec1.ndim > 1:
  60. unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8).reshape((-1, 1))
  61. else:
  62. unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8)
  63. if vec2.ndim > 1:
  64. unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8).reshape((-1, 1))
  65. else:
  66. unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8)
  67. return np.arccos(
  68. np.clip(
  69. np.sum(unit_vec1 * unit_vec2, axis=-1), -1.0, 1.0))
  70. def resample_line(self, line, n):
  71. """Resample n points on a line.
  72. Args:
  73. line (ndarray): The points composing a line.
  74. n (int): The resampled points number.
  75. Returns:
  76. resampled_line (ndarray): The points composing the resampled line.
  77. """
  78. assert line.ndim == 2
  79. assert line.shape[0] >= 2
  80. assert line.shape[1] == 2
  81. assert isinstance(n, int)
  82. assert n > 0
  83. length_list = [
  84. norm(line[i + 1] - line[i]) for i in range(len(line) - 1)
  85. ]
  86. total_length = sum(length_list)
  87. length_cumsum = np.cumsum([0.0] + length_list)
  88. delta_length = total_length / (float(n) + 1e-8)
  89. current_edge_ind = 0
  90. resampled_line = [line[0]]
  91. for i in range(1, n):
  92. current_line_len = i * delta_length
  93. while current_edge_ind + 1 < len(
  94. length_cumsum) and current_line_len >= length_cumsum[
  95. current_edge_ind + 1]:
  96. current_edge_ind += 1
  97. current_edge_end_shift = current_line_len - length_cumsum[
  98. current_edge_ind]
  99. if current_edge_ind >= len(length_list):
  100. break
  101. end_shift_ratio = current_edge_end_shift / length_list[
  102. current_edge_ind]
  103. current_point = line[current_edge_ind] + (line[current_edge_ind + 1]
  104. - line[current_edge_ind]
  105. ) * end_shift_ratio
  106. resampled_line.append(current_point)
  107. resampled_line.append(line[-1])
  108. resampled_line = np.array(resampled_line)
  109. return resampled_line
  110. def reorder_poly_edge(self, points):
  111. """Get the respective points composing head edge, tail edge, top
  112. sideline and bottom sideline.
  113. Args:
  114. points (ndarray): The points composing a text polygon.
  115. Returns:
  116. head_edge (ndarray): The two points composing the head edge of text
  117. polygon.
  118. tail_edge (ndarray): The two points composing the tail edge of text
  119. polygon.
  120. top_sideline (ndarray): The points composing top curved sideline of
  121. text polygon.
  122. bot_sideline (ndarray): The points composing bottom curved sideline
  123. of text polygon.
  124. """
  125. assert points.ndim == 2
  126. assert points.shape[0] >= 4
  127. assert points.shape[1] == 2
  128. head_inds, tail_inds = self.find_head_tail(points, self.orientation_thr)
  129. head_edge, tail_edge = points[head_inds], points[tail_inds]
  130. pad_points = np.vstack([points, points])
  131. if tail_inds[1] < 1:
  132. tail_inds[1] = len(points)
  133. sideline1 = pad_points[head_inds[1]:tail_inds[1]]
  134. sideline2 = pad_points[tail_inds[1]:(head_inds[1] + len(points))]
  135. sideline_mean_shift = np.mean(
  136. sideline1, axis=0) - np.mean(
  137. sideline2, axis=0)
  138. if sideline_mean_shift[1] > 0:
  139. top_sideline, bot_sideline = sideline2, sideline1
  140. else:
  141. top_sideline, bot_sideline = sideline1, sideline2
  142. return head_edge, tail_edge, top_sideline, bot_sideline
  143. def find_head_tail(self, points, orientation_thr):
  144. """Find the head edge and tail edge of a text polygon.
  145. Args:
  146. points (ndarray): The points composing a text polygon.
  147. orientation_thr (float): The threshold for distinguishing between
  148. head edge and tail edge among the horizontal and vertical edges
  149. of a quadrangle.
  150. Returns:
  151. head_inds (list): The indexes of two points composing head edge.
  152. tail_inds (list): The indexes of two points composing tail edge.
  153. """
  154. assert points.ndim == 2
  155. assert points.shape[0] >= 4
  156. assert points.shape[1] == 2
  157. assert isinstance(orientation_thr, float)
  158. if len(points) > 4:
  159. pad_points = np.vstack([points, points[0]])
  160. edge_vec = pad_points[1:] - pad_points[:-1]
  161. theta_sum = []
  162. adjacent_vec_theta = []
  163. for i, edge_vec1 in enumerate(edge_vec):
  164. adjacent_ind = [x % len(edge_vec) for x in [i - 1, i + 1]]
  165. adjacent_edge_vec = edge_vec[adjacent_ind]
  166. temp_theta_sum = np.sum(
  167. self.vector_angle(edge_vec1, adjacent_edge_vec))
  168. temp_adjacent_theta = self.vector_angle(adjacent_edge_vec[0],
  169. adjacent_edge_vec[1])
  170. theta_sum.append(temp_theta_sum)
  171. adjacent_vec_theta.append(temp_adjacent_theta)
  172. theta_sum_score = np.array(theta_sum) / np.pi
  173. adjacent_theta_score = np.array(adjacent_vec_theta) / np.pi
  174. poly_center = np.mean(points, axis=0)
  175. edge_dist = np.maximum(
  176. norm(
  177. pad_points[1:] - poly_center, axis=-1),
  178. norm(
  179. pad_points[:-1] - poly_center, axis=-1))
  180. dist_score = edge_dist / np.max(edge_dist)
  181. position_score = np.zeros(len(edge_vec))
  182. score = 0.5 * theta_sum_score + 0.15 * adjacent_theta_score
  183. score += 0.35 * dist_score
  184. if len(points) % 2 == 0:
  185. position_score[(len(score) // 2 - 1)] += 1
  186. position_score[-1] += 1
  187. score += 0.1 * position_score
  188. pad_score = np.concatenate([score, score])
  189. score_matrix = np.zeros((len(score), len(score) - 3))
  190. x = np.arange(len(score) - 3) / float(len(score) - 4)
  191. gaussian = 1. / (np.sqrt(2. * np.pi) * 0.5) * np.exp(-np.power(
  192. (x - 0.5) / 0.5, 2.) / 2)
  193. gaussian = gaussian / np.max(gaussian)
  194. for i in range(len(score)):
  195. score_matrix[i, :] = score[i] + pad_score[(i + 2):(i + len(
  196. score) - 1)] * gaussian * 0.3
  197. head_start, tail_increment = np.unravel_index(score_matrix.argmax(),
  198. score_matrix.shape)
  199. tail_start = (head_start + tail_increment + 2) % len(points)
  200. head_end = (head_start + 1) % len(points)
  201. tail_end = (tail_start + 1) % len(points)
  202. if head_end > tail_end:
  203. head_start, tail_start = tail_start, head_start
  204. head_end, tail_end = tail_end, head_end
  205. head_inds = [head_start, head_end]
  206. tail_inds = [tail_start, tail_end]
  207. else:
  208. if vector_slope(points[1] - points[0]) + vector_slope(points[
  209. 3] - points[2]) < vector_slope(points[2] - points[
  210. 1]) + vector_slope(points[0] - points[3]):
  211. horizontal_edge_inds = [[0, 1], [2, 3]]
  212. vertical_edge_inds = [[3, 0], [1, 2]]
  213. else:
  214. horizontal_edge_inds = [[3, 0], [1, 2]]
  215. vertical_edge_inds = [[0, 1], [2, 3]]
  216. vertical_len_sum = norm(points[vertical_edge_inds[0][0]] - points[
  217. vertical_edge_inds[0][1]]) + norm(points[vertical_edge_inds[1][
  218. 0]] - points[vertical_edge_inds[1][1]])
  219. horizontal_len_sum = norm(points[horizontal_edge_inds[0][
  220. 0]] - points[horizontal_edge_inds[0][1]]) + norm(points[
  221. horizontal_edge_inds[1][0]] - points[horizontal_edge_inds[1]
  222. [1]])
  223. if vertical_len_sum > horizontal_len_sum * orientation_thr:
  224. head_inds = horizontal_edge_inds[0]
  225. tail_inds = horizontal_edge_inds[1]
  226. else:
  227. head_inds = vertical_edge_inds[0]
  228. tail_inds = vertical_edge_inds[1]
  229. return head_inds, tail_inds
  230. def resample_sidelines(self, sideline1, sideline2, resample_step):
  231. """Resample two sidelines to be of the same points number according to
  232. step size.
  233. Args:
  234. sideline1 (ndarray): The points composing a sideline of a text
  235. polygon.
  236. sideline2 (ndarray): The points composing another sideline of a
  237. text polygon.
  238. resample_step (float): The resampled step size.
  239. Returns:
  240. resampled_line1 (ndarray): The resampled line 1.
  241. resampled_line2 (ndarray): The resampled line 2.
  242. """
  243. assert sideline1.ndim == sideline2.ndim == 2
  244. assert sideline1.shape[1] == sideline2.shape[1] == 2
  245. assert sideline1.shape[0] >= 2
  246. assert sideline2.shape[0] >= 2
  247. assert isinstance(resample_step, float)
  248. length1 = sum([
  249. norm(sideline1[i + 1] - sideline1[i])
  250. for i in range(len(sideline1) - 1)
  251. ])
  252. length2 = sum([
  253. norm(sideline2[i + 1] - sideline2[i])
  254. for i in range(len(sideline2) - 1)
  255. ])
  256. total_length = (length1 + length2) / 2
  257. resample_point_num = max(int(float(total_length) / resample_step), 1)
  258. resampled_line1 = self.resample_line(sideline1, resample_point_num)
  259. resampled_line2 = self.resample_line(sideline2, resample_point_num)
  260. return resampled_line1, resampled_line2
  261. def generate_center_region_mask(self, img_size, text_polys):
  262. """Generate text center region mask.
  263. Args:
  264. img_size (tuple): The image size of (height, width).
  265. text_polys (list[list[ndarray]]): The list of text polygons.
  266. Returns:
  267. center_region_mask (ndarray): The text center region mask.
  268. """
  269. assert isinstance(img_size, tuple)
  270. # assert check_argument.is_2dlist(text_polys)
  271. h, w = img_size
  272. center_region_mask = np.zeros((h, w), np.uint8)
  273. center_region_boxes = []
  274. for poly in text_polys:
  275. # assert len(poly) == 1
  276. polygon_points = poly.reshape(-1, 2)
  277. _, _, top_line, bot_line = self.reorder_poly_edge(polygon_points)
  278. resampled_top_line, resampled_bot_line = self.resample_sidelines(
  279. top_line, bot_line, self.resample_step)
  280. resampled_bot_line = resampled_bot_line[::-1]
  281. if len(resampled_top_line) != len(resampled_bot_line):
  282. continue
  283. center_line = (resampled_top_line + resampled_bot_line) / 2
  284. line_head_shrink_len = norm(resampled_top_line[0] -
  285. resampled_bot_line[0]) / 4.0
  286. line_tail_shrink_len = norm(resampled_top_line[-1] -
  287. resampled_bot_line[-1]) / 4.0
  288. head_shrink_num = int(line_head_shrink_len // self.resample_step)
  289. tail_shrink_num = int(line_tail_shrink_len // self.resample_step)
  290. if len(center_line) > head_shrink_num + tail_shrink_num + 2:
  291. center_line = center_line[head_shrink_num:len(center_line) -
  292. tail_shrink_num]
  293. resampled_top_line = resampled_top_line[head_shrink_num:len(
  294. resampled_top_line) - tail_shrink_num]
  295. resampled_bot_line = resampled_bot_line[head_shrink_num:len(
  296. resampled_bot_line) - tail_shrink_num]
  297. for i in range(0, len(center_line) - 1):
  298. tl = center_line[i] + (resampled_top_line[i] - center_line[i]
  299. ) * self.center_region_shrink_ratio
  300. tr = center_line[i + 1] + (resampled_top_line[i + 1] -
  301. center_line[i + 1]
  302. ) * self.center_region_shrink_ratio
  303. br = center_line[i + 1] + (resampled_bot_line[i + 1] -
  304. center_line[i + 1]
  305. ) * self.center_region_shrink_ratio
  306. bl = center_line[i] + (resampled_bot_line[i] - center_line[i]
  307. ) * self.center_region_shrink_ratio
  308. current_center_box = np.vstack([tl, tr, br,
  309. bl]).astype(np.int32)
  310. center_region_boxes.append(current_center_box)
  311. cv2.fillPoly(center_region_mask, center_region_boxes, 1)
  312. return center_region_mask
  313. def resample_polygon(self, polygon, n=400):
  314. """Resample one polygon with n points on its boundary.
  315. Args:
  316. polygon (list[float]): The input polygon.
  317. n (int): The number of resampled points.
  318. Returns:
  319. resampled_polygon (list[float]): The resampled polygon.
  320. """
  321. length = []
  322. for i in range(len(polygon)):
  323. p1 = polygon[i]
  324. if i == len(polygon) - 1:
  325. p2 = polygon[0]
  326. else:
  327. p2 = polygon[i + 1]
  328. length.append(((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5)
  329. total_length = sum(length)
  330. n_on_each_line = (np.array(length) / (total_length + 1e-8)) * n
  331. n_on_each_line = n_on_each_line.astype(np.int32)
  332. new_polygon = []
  333. for i in range(len(polygon)):
  334. num = n_on_each_line[i]
  335. p1 = polygon[i]
  336. if i == len(polygon) - 1:
  337. p2 = polygon[0]
  338. else:
  339. p2 = polygon[i + 1]
  340. if num == 0:
  341. continue
  342. dxdy = (p2 - p1) / num
  343. for j in range(num):
  344. point = p1 + dxdy * j
  345. new_polygon.append(point)
  346. return np.array(new_polygon)
  347. def normalize_polygon(self, polygon):
  348. """Normalize one polygon so that its start point is at right most.
  349. Args:
  350. polygon (list[float]): The origin polygon.
  351. Returns:
  352. new_polygon (lost[float]): The polygon with start point at right.
  353. """
  354. temp_polygon = polygon - polygon.mean(axis=0)
  355. x = np.abs(temp_polygon[:, 0])
  356. y = temp_polygon[:, 1]
  357. index_x = np.argsort(x)
  358. index_y = np.argmin(y[index_x[:8]])
  359. index = index_x[index_y]
  360. new_polygon = np.concatenate([polygon[index:], polygon[:index]])
  361. return new_polygon
  362. def poly2fourier(self, polygon, fourier_degree):
  363. """Perform Fourier transformation to generate Fourier coefficients ck
  364. from polygon.
  365. Args:
  366. polygon (ndarray): An input polygon.
  367. fourier_degree (int): The maximum Fourier degree K.
  368. Returns:
  369. c (ndarray(complex)): Fourier coefficients.
  370. """
  371. points = polygon[:, 0] + polygon[:, 1] * 1j
  372. c_fft = fft(points) / len(points)
  373. c = np.hstack((c_fft[-fourier_degree:], c_fft[:fourier_degree + 1]))
  374. return c
  375. def clockwise(self, c, fourier_degree):
  376. """Make sure the polygon reconstructed from Fourier coefficients c in
  377. the clockwise direction.
  378. Args:
  379. polygon (list[float]): The origin polygon.
  380. Returns:
  381. new_polygon (lost[float]): The polygon in clockwise point order.
  382. """
  383. if np.abs(c[fourier_degree + 1]) > np.abs(c[fourier_degree - 1]):
  384. return c
  385. elif np.abs(c[fourier_degree + 1]) < np.abs(c[fourier_degree - 1]):
  386. return c[::-1]
  387. else:
  388. if np.abs(c[fourier_degree + 2]) > np.abs(c[fourier_degree - 2]):
  389. return c
  390. else:
  391. return c[::-1]
  392. def cal_fourier_signature(self, polygon, fourier_degree):
  393. """Calculate Fourier signature from input polygon.
  394. Args:
  395. polygon (ndarray): The input polygon.
  396. fourier_degree (int): The maximum Fourier degree K.
  397. Returns:
  398. fourier_signature (ndarray): An array shaped (2k+1, 2) containing
  399. real part and image part of 2k+1 Fourier coefficients.
  400. """
  401. resampled_polygon = self.resample_polygon(polygon)
  402. resampled_polygon = self.normalize_polygon(resampled_polygon)
  403. fourier_coeff = self.poly2fourier(resampled_polygon, fourier_degree)
  404. fourier_coeff = self.clockwise(fourier_coeff, fourier_degree)
  405. real_part = np.real(fourier_coeff).reshape((-1, 1))
  406. image_part = np.imag(fourier_coeff).reshape((-1, 1))
  407. fourier_signature = np.hstack([real_part, image_part])
  408. return fourier_signature
  409. def generate_fourier_maps(self, img_size, text_polys):
  410. """Generate Fourier coefficient maps.
  411. Args:
  412. img_size (tuple): The image size of (height, width).
  413. text_polys (list[list[ndarray]]): The list of text polygons.
  414. Returns:
  415. fourier_real_map (ndarray): The Fourier coefficient real part maps.
  416. fourier_image_map (ndarray): The Fourier coefficient image part
  417. maps.
  418. """
  419. assert isinstance(img_size, tuple)
  420. h, w = img_size
  421. k = self.fourier_degree
  422. real_map = np.zeros((k * 2 + 1, h, w), dtype=np.float32)
  423. imag_map = np.zeros((k * 2 + 1, h, w), dtype=np.float32)
  424. for poly in text_polys:
  425. mask = np.zeros((h, w), dtype=np.uint8)
  426. polygon = np.array(poly).reshape((1, -1, 2))
  427. cv2.fillPoly(mask, polygon.astype(np.int32), 1)
  428. fourier_coeff = self.cal_fourier_signature(polygon[0], k)
  429. for i in range(-k, k + 1):
  430. if i != 0:
  431. real_map[i + k, :, :] = mask * fourier_coeff[i + k, 0] + (
  432. 1 - mask) * real_map[i + k, :, :]
  433. imag_map[i + k, :, :] = mask * fourier_coeff[i + k, 1] + (
  434. 1 - mask) * imag_map[i + k, :, :]
  435. else:
  436. yx = np.argwhere(mask > 0.5)
  437. k_ind = np.ones((len(yx)), dtype=np.int64) * k
  438. y, x = yx[:, 0], yx[:, 1]
  439. real_map[k_ind, y, x] = fourier_coeff[k, 0] - x
  440. imag_map[k_ind, y, x] = fourier_coeff[k, 1] - y
  441. return real_map, imag_map
  442. def generate_text_region_mask(self, img_size, text_polys):
  443. """Generate text center region mask and geometry attribute maps.
  444. Args:
  445. img_size (tuple): The image size (height, width).
  446. text_polys (list[list[ndarray]]): The list of text polygons.
  447. Returns:
  448. text_region_mask (ndarray): The text region mask.
  449. """
  450. assert isinstance(img_size, tuple)
  451. h, w = img_size
  452. text_region_mask = np.zeros((h, w), dtype=np.uint8)
  453. for poly in text_polys:
  454. polygon = np.array(poly, dtype=np.int32).reshape((1, -1, 2))
  455. cv2.fillPoly(text_region_mask, polygon, 1)
  456. return text_region_mask
  457. def generate_effective_mask(self, mask_size: tuple, polygons_ignore):
  458. """Generate effective mask by setting the ineffective regions to 0 and
  459. effective regions to 1.
  460. Args:
  461. mask_size (tuple): The mask size.
  462. polygons_ignore (list[[ndarray]]: The list of ignored text
  463. polygons.
  464. Returns:
  465. mask (ndarray): The effective mask of (height, width).
  466. """
  467. mask = np.ones(mask_size, dtype=np.uint8)
  468. for poly in polygons_ignore:
  469. instance = poly.reshape(-1, 2).astype(np.int32).reshape(1, -1, 2)
  470. cv2.fillPoly(mask, instance, 0)
  471. return mask
  472. def generate_level_targets(self, img_size, text_polys, ignore_polys):
  473. """Generate ground truth target on each level.
  474. Args:
  475. img_size (list[int]): Shape of input image.
  476. text_polys (list[list[ndarray]]): A list of ground truth polygons.
  477. ignore_polys (list[list[ndarray]]): A list of ignored polygons.
  478. Returns:
  479. level_maps (list(ndarray)): A list of ground target on each level.
  480. """
  481. h, w = img_size
  482. lv_size_divs = self.level_size_divisors
  483. lv_proportion_range = self.level_proportion_range
  484. lv_text_polys = [[] for i in range(len(lv_size_divs))]
  485. lv_ignore_polys = [[] for i in range(len(lv_size_divs))]
  486. level_maps = []
  487. for poly in text_polys:
  488. polygon = np.array(poly, dtype=np.int32).reshape((1, -1, 2))
  489. _, _, box_w, box_h = cv2.boundingRect(polygon)
  490. proportion = max(box_h, box_w) / (h + 1e-8)
  491. for ind, proportion_range in enumerate(lv_proportion_range):
  492. if proportion_range[0] < proportion < proportion_range[1]:
  493. lv_text_polys[ind].append(poly / lv_size_divs[ind])
  494. for ignore_poly in ignore_polys:
  495. polygon = np.array(ignore_poly, dtype=np.int32).reshape((1, -1, 2))
  496. _, _, box_w, box_h = cv2.boundingRect(polygon)
  497. proportion = max(box_h, box_w) / (h + 1e-8)
  498. for ind, proportion_range in enumerate(lv_proportion_range):
  499. if proportion_range[0] < proportion < proportion_range[1]:
  500. lv_ignore_polys[ind].append(ignore_poly / lv_size_divs[ind])
  501. for ind, size_divisor in enumerate(lv_size_divs):
  502. current_level_maps = []
  503. level_img_size = (h // size_divisor, w // size_divisor)
  504. text_region = self.generate_text_region_mask(
  505. level_img_size, lv_text_polys[ind])[None]
  506. current_level_maps.append(text_region)
  507. center_region = self.generate_center_region_mask(
  508. level_img_size, lv_text_polys[ind])[None]
  509. current_level_maps.append(center_region)
  510. effective_mask = self.generate_effective_mask(
  511. level_img_size, lv_ignore_polys[ind])[None]
  512. current_level_maps.append(effective_mask)
  513. fourier_real_map, fourier_image_maps = self.generate_fourier_maps(
  514. level_img_size, lv_text_polys[ind])
  515. current_level_maps.append(fourier_real_map)
  516. current_level_maps.append(fourier_image_maps)
  517. level_maps.append(np.concatenate(current_level_maps))
  518. return level_maps
  519. def generate_targets(self, results):
  520. """Generate the ground truth targets for FCENet.
  521. Args:
  522. results (dict): The input result dictionary.
  523. Returns:
  524. results (dict): The output result dictionary.
  525. """
  526. assert isinstance(results, dict)
  527. image = results['image']
  528. polygons = results['polys']
  529. ignore_tags = results['ignore_tags']
  530. h, w, _ = image.shape
  531. polygon_masks = []
  532. polygon_masks_ignore = []
  533. for tag, polygon in zip(ignore_tags, polygons):
  534. if tag is True:
  535. polygon_masks_ignore.append(polygon)
  536. else:
  537. polygon_masks.append(polygon)
  538. level_maps = self.generate_level_targets((h, w), polygon_masks,
  539. polygon_masks_ignore)
  540. mapping = {
  541. 'p3_maps': level_maps[0],
  542. 'p4_maps': level_maps[1],
  543. 'p5_maps': level_maps[2]
  544. }
  545. for key, value in mapping.items():
  546. results[key] = value
  547. return results
  548. def __call__(self, results):
  549. results = self.generate_targets(results)
  550. return results