fce_targets.py 26 KB

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