processors.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Copyright (c) 2024 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. import numpy as np
  15. from ...utils.benchmark import benchmark
  16. from ..common.vision import funcs as F
  17. @benchmark.timeit
  18. class Pad:
  19. """Pad the image."""
  20. def __init__(self, target_size, val=127.5):
  21. """
  22. Initialize the instance.
  23. Args:
  24. target_size (list|tuple|int): Target width and height of the image after
  25. padding.
  26. val (float, optional): Value to fill the padded area. Default: 127.5.
  27. """
  28. super().__init__()
  29. if isinstance(target_size, int):
  30. target_size = [target_size, target_size]
  31. self.target_size = target_size
  32. self.val = val
  33. def apply(self, img):
  34. """apply"""
  35. h, w = img.shape[:2]
  36. tw, th = self.target_size
  37. ph = th - h
  38. pw = tw - w
  39. if ph < 0 or pw < 0:
  40. raise ValueError(
  41. f"Input image ({w}, {h}) smaller than the target size ({tw}, {th})."
  42. )
  43. else:
  44. img = F.pad(img, pad=(0, ph, 0, pw), val=self.val)
  45. return [img, [img.shape[1], img.shape[0]]]
  46. def __call__(self, imgs):
  47. """apply"""
  48. return [self.apply(img) for img in imgs]
  49. @benchmark.timeit
  50. class TableLabelDecode:
  51. """decode the table model outputs(probs) to character str"""
  52. ENABLE_BATCH = True
  53. INPUT_KEYS = ["pred", "img_size", "ori_img_size"]
  54. OUTPUT_KEYS = ["bbox", "structure", "structure_score"]
  55. DEAULT_INPUTS = {
  56. "pred": "pred",
  57. "img_size": "img_size",
  58. "ori_img_size": "ori_img_size",
  59. }
  60. DEAULT_OUTPUTS = {
  61. "bbox": "bbox",
  62. "structure": "structure",
  63. "structure_score": "structure_score",
  64. }
  65. def __init__(self, model_name, merge_no_span_structure=True, dict_character=[]):
  66. super().__init__()
  67. if merge_no_span_structure:
  68. if "<td></td>" not in dict_character:
  69. dict_character.append("<td></td>")
  70. if "<td>" in dict_character:
  71. dict_character.remove("<td>")
  72. self.model_name = model_name
  73. dict_character = self.add_special_char(dict_character)
  74. self.dict = {}
  75. for i, char in enumerate(dict_character):
  76. self.dict[char] = i
  77. self.character = dict_character
  78. self.td_token = ["<td>", "<td", "<td></td>"]
  79. def add_special_char(self, dict_character):
  80. """add_special_char"""
  81. self.beg_str = "sos"
  82. self.end_str = "eos"
  83. dict_character = dict_character
  84. dict_character = [self.beg_str] + dict_character + [self.end_str]
  85. return dict_character
  86. def get_ignored_tokens(self):
  87. """get_ignored_tokens"""
  88. beg_idx = self.get_beg_end_flag_idx("beg")
  89. end_idx = self.get_beg_end_flag_idx("end")
  90. return [beg_idx, end_idx]
  91. def get_beg_end_flag_idx(self, beg_or_end):
  92. """get_beg_end_flag_idx"""
  93. if beg_or_end == "beg":
  94. idx = np.array(self.dict[self.beg_str])
  95. elif beg_or_end == "end":
  96. idx = np.array(self.dict[self.end_str])
  97. else:
  98. assert False, "unsupported type %s in get_beg_end_flag_idx" % beg_or_end
  99. return idx
  100. def __call__(self, pred, img_size, ori_img_size):
  101. """apply"""
  102. bbox_preds = np.array([list(pred[0][0])])
  103. structure_probs = np.array([list(pred[1][0])])
  104. bbox_list, structure_str_list, structure_score = self.decode(
  105. structure_probs, bbox_preds, img_size, ori_img_size
  106. )
  107. structure_str_list = [
  108. (["<table>"] + structure + ["</table>"]) for structure in structure_str_list
  109. ]
  110. return [
  111. {"bbox": bbox, "structure": structure, "structure_score": structure_score}
  112. for bbox, structure in zip(bbox_list, structure_str_list)
  113. ]
  114. def decode(self, structure_probs, bbox_preds, padding_size, ori_img_size):
  115. """convert text-label into text-index."""
  116. ignored_tokens = self.get_ignored_tokens()
  117. end_idx = self.dict[self.end_str]
  118. structure_idx = structure_probs.argmax(axis=2)
  119. structure_probs = structure_probs.max(axis=2)
  120. structure_batch_list = []
  121. bbox_batch_list = []
  122. batch_size = len(structure_idx)
  123. bbox_list = []
  124. scale_list = []
  125. scales = [0] * 8
  126. for batch_idx in range(batch_size):
  127. structure_list = []
  128. score_list = []
  129. for idx in range(len(structure_idx[batch_idx])):
  130. char_idx = int(structure_idx[batch_idx][idx])
  131. if idx > 0 and char_idx == end_idx:
  132. break
  133. if char_idx in ignored_tokens:
  134. continue
  135. text = self.character[char_idx]
  136. if text in self.td_token:
  137. bbox = bbox_preds[batch_idx, idx]
  138. h_scale, w_scale = self._get_bbox_scales(
  139. padding_size[batch_idx], ori_img_size[batch_idx]
  140. )
  141. scales[0::2] = [h_scale] * 4
  142. scales[1::2] = [w_scale] * 4
  143. bbox_list.append(bbox)
  144. scale_list.append(scales)
  145. structure_list.append(text)
  146. score_list.append(structure_probs[batch_idx, idx])
  147. structure_batch_list.append(structure_list)
  148. structure_score = np.mean(score_list)
  149. bbox_batch_array = np.multiply(np.array(bbox_list), np.array(scale_list))
  150. bbox_batch_list = [bbox_batch_array.astype(int).tolist()]
  151. return bbox_batch_list, structure_batch_list, structure_score
  152. def decode_label(self, batch):
  153. """convert text-label into text-index."""
  154. structure_idx = batch[1]
  155. gt_bbox_list = batch[2]
  156. shape_list = batch[-1]
  157. ignored_tokens = self.get_ignored_tokens()
  158. end_idx = self.dict[self.end_str]
  159. structure_batch_list = []
  160. bbox_batch_list = []
  161. batch_size = len(structure_idx)
  162. for batch_idx in range(batch_size):
  163. structure_list = []
  164. bbox_list = []
  165. for idx in range(len(structure_idx[batch_idx])):
  166. char_idx = int(structure_idx[batch_idx][idx])
  167. if idx > 0 and char_idx == end_idx:
  168. break
  169. if char_idx in ignored_tokens:
  170. continue
  171. structure_list.append(self.character[char_idx])
  172. bbox = gt_bbox_list[batch_idx][idx]
  173. if bbox.sum() != 0:
  174. bbox = self._bbox_decode(bbox, shape_list[batch_idx])
  175. bbox_list.append(bbox.astype(int))
  176. structure_batch_list.append(structure_list)
  177. bbox_batch_list.append(bbox_list)
  178. return bbox_batch_list, structure_batch_list
  179. def _get_bbox_scales(self, padding_shape, ori_shape):
  180. if self.model_name == "SLANet":
  181. w, h = ori_shape
  182. return w, h
  183. else:
  184. w, h = padding_shape
  185. ori_w, ori_h = ori_shape
  186. ratio_w = w / ori_w
  187. ratio_h = h / ori_h
  188. ratio = min(ratio_w, ratio_h)
  189. return w / ratio, h / ratio