processors.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # copyright (c) 2024 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. import cv2
  15. import numpy as np
  16. from numpy import ndarray
  17. from ..common.vision import funcs as F
  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. class TableLabelDecode:
  50. """decode the table model outputs(probs) to character str"""
  51. ENABLE_BATCH = True
  52. INPUT_KEYS = ["pred", "img_size", "ori_img_size"]
  53. OUTPUT_KEYS = ["bbox", "structure", "structure_score"]
  54. DEAULT_INPUTS = {
  55. "pred": "pred",
  56. "img_size": "img_size",
  57. "ori_img_size": "ori_img_size",
  58. }
  59. DEAULT_OUTPUTS = {
  60. "bbox": "bbox",
  61. "structure": "structure",
  62. "structure_score": "structure_score",
  63. }
  64. def __init__(self, model_name, merge_no_span_structure=True, dict_character=[]):
  65. super().__init__()
  66. if merge_no_span_structure:
  67. if "<td></td>" not in dict_character:
  68. dict_character.append("<td></td>")
  69. if "<td>" in dict_character:
  70. dict_character.remove("<td>")
  71. self.model_name = model_name
  72. dict_character = self.add_special_char(dict_character)
  73. self.dict = {}
  74. for i, char in enumerate(dict_character):
  75. self.dict[char] = i
  76. self.character = dict_character
  77. self.td_token = ["<td>", "<td", "<td></td>"]
  78. def add_special_char(self, dict_character):
  79. """add_special_char"""
  80. self.beg_str = "sos"
  81. self.end_str = "eos"
  82. dict_character = dict_character
  83. dict_character = [self.beg_str] + dict_character + [self.end_str]
  84. return dict_character
  85. def get_ignored_tokens(self):
  86. """get_ignored_tokens"""
  87. beg_idx = self.get_beg_end_flag_idx("beg")
  88. end_idx = self.get_beg_end_flag_idx("end")
  89. return [beg_idx, end_idx]
  90. def get_beg_end_flag_idx(self, beg_or_end):
  91. """get_beg_end_flag_idx"""
  92. if beg_or_end == "beg":
  93. idx = np.array(self.dict[self.beg_str])
  94. elif beg_or_end == "end":
  95. idx = np.array(self.dict[self.end_str])
  96. else:
  97. assert False, "unsupported type %s in get_beg_end_flag_idx" % beg_or_end
  98. return idx
  99. def __call__(self, pred, img_size, ori_img_size):
  100. """apply"""
  101. bbox_preds, structure_probs = [], []
  102. for i in range(len(pred[0][0])):
  103. bbox_preds.append(pred[0][0][i])
  104. structure_probs.append(pred[1][0][i])
  105. bbox_preds = [bbox_preds]
  106. structure_probs = [structure_probs]
  107. bbox_preds = np.array(bbox_preds)
  108. structure_probs = np.array(structure_probs)
  109. bbox_list, structure_str_list, structure_score = self.decode(
  110. structure_probs, bbox_preds, img_size, ori_img_size
  111. )
  112. structure_str_list = [
  113. (
  114. ["<html>", "<body>", "<table>"]
  115. + structure
  116. + ["</table>", "</body>", "</html>"]
  117. )
  118. for structure in structure_str_list
  119. ]
  120. return [
  121. {"bbox": bbox, "structure": structure, "structure_score": structure_score}
  122. for bbox, structure in zip(bbox_list, structure_str_list)
  123. ]
  124. def decode(self, structure_probs, bbox_preds, padding_size, ori_img_size):
  125. """convert text-label into text-index."""
  126. ignored_tokens = self.get_ignored_tokens()
  127. end_idx = self.dict[self.end_str]
  128. structure_idx = structure_probs.argmax(axis=2)
  129. structure_probs = structure_probs.max(axis=2)
  130. structure_batch_list = []
  131. bbox_batch_list = []
  132. batch_size = len(structure_idx)
  133. for batch_idx in range(batch_size):
  134. structure_list = []
  135. bbox_list = []
  136. score_list = []
  137. for idx in range(len(structure_idx[batch_idx])):
  138. char_idx = int(structure_idx[batch_idx][idx])
  139. if idx > 0 and char_idx == end_idx:
  140. break
  141. if char_idx in ignored_tokens:
  142. continue
  143. text = self.character[char_idx]
  144. if text in self.td_token:
  145. bbox = bbox_preds[batch_idx, idx]
  146. bbox = self._bbox_decode(
  147. bbox, padding_size[batch_idx], ori_img_size[batch_idx]
  148. )
  149. bbox_list.append(bbox.astype(int))
  150. structure_list.append(text)
  151. score_list.append(structure_probs[batch_idx, idx])
  152. structure_batch_list.append(structure_list)
  153. structure_score = np.mean(score_list)
  154. bbox_batch_list.append(bbox_list)
  155. return bbox_batch_list, structure_batch_list, structure_score
  156. def decode_label(self, batch):
  157. """convert text-label into text-index."""
  158. structure_idx = batch[1]
  159. gt_bbox_list = batch[2]
  160. shape_list = batch[-1]
  161. ignored_tokens = self.get_ignored_tokens()
  162. end_idx = self.dict[self.end_str]
  163. structure_batch_list = []
  164. bbox_batch_list = []
  165. batch_size = len(structure_idx)
  166. for batch_idx in range(batch_size):
  167. structure_list = []
  168. bbox_list = []
  169. for idx in range(len(structure_idx[batch_idx])):
  170. char_idx = int(structure_idx[batch_idx][idx])
  171. if idx > 0 and char_idx == end_idx:
  172. break
  173. if char_idx in ignored_tokens:
  174. continue
  175. structure_list.append(self.character[char_idx])
  176. bbox = gt_bbox_list[batch_idx][idx]
  177. if bbox.sum() != 0:
  178. bbox = self._bbox_decode(bbox, shape_list[batch_idx])
  179. bbox_list.append(bbox.astype(int))
  180. structure_batch_list.append(structure_list)
  181. bbox_batch_list.append(bbox_list)
  182. return bbox_batch_list, structure_batch_list
  183. def _bbox_decode(self, bbox, padding_shape, ori_shape):
  184. if self.model_name == "SLANet":
  185. w, h = ori_shape
  186. bbox[0::2] *= w
  187. bbox[1::2] *= h
  188. else:
  189. w, h = padding_shape
  190. ori_w, ori_h = ori_shape
  191. ratio_w = w / ori_w
  192. ratio_h = h / ori_h
  193. ratio = min(ratio_w, ratio_h)
  194. bbox[0::2] *= w
  195. bbox[1::2] *= h
  196. bbox[0::2] /= ratio
  197. bbox[1::2] /= ratio
  198. return bbox