processors.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 os
  15. import os.path as osp
  16. from typing import List
  17. import re
  18. import numpy as np
  19. from PIL import Image
  20. import cv2
  21. import math
  22. import json
  23. import tempfile
  24. from tokenizers import Tokenizer as TokenizerFast
  25. from ....utils import logging
  26. from ...utils.benchmark import benchmark
  27. @benchmark.timeit
  28. class OCRReisizeNormImg:
  29. """for ocr image resize and normalization"""
  30. def __init__(self, rec_image_shape=[3, 48, 320]):
  31. super().__init__()
  32. self.rec_image_shape = rec_image_shape
  33. def resize_norm_img(self, img, max_wh_ratio):
  34. """resize and normalize the img"""
  35. imgC, imgH, imgW = self.rec_image_shape
  36. assert imgC == img.shape[2]
  37. imgW = int((imgH * max_wh_ratio))
  38. h, w = img.shape[:2]
  39. ratio = w / float(h)
  40. if math.ceil(imgH * ratio) > imgW:
  41. resized_w = imgW
  42. else:
  43. resized_w = int(math.ceil(imgH * ratio))
  44. resized_image = cv2.resize(img, (resized_w, imgH))
  45. resized_image = resized_image.astype("float32")
  46. resized_image = resized_image.transpose((2, 0, 1)) / 255
  47. resized_image -= 0.5
  48. resized_image /= 0.5
  49. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  50. padding_im[:, :, 0:resized_w] = resized_image
  51. return padding_im
  52. def __call__(self, imgs):
  53. """apply"""
  54. return [self.resize(img) for img in imgs]
  55. def resize(self, img):
  56. imgC, imgH, imgW = self.rec_image_shape
  57. max_wh_ratio = imgW / imgH
  58. h, w = img.shape[:2]
  59. wh_ratio = w * 1.0 / h
  60. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  61. img = self.resize_norm_img(img, max_wh_ratio)
  62. return img
  63. @benchmark.timeit
  64. class BaseRecLabelDecode:
  65. """Convert between text-label and text-index"""
  66. def __init__(self, character_str=None, use_space_char=True):
  67. super().__init__()
  68. self.reverse = False
  69. character_list = (
  70. list(character_str)
  71. if character_str is not None
  72. else list("0123456789abcdefghijklmnopqrstuvwxyz")
  73. )
  74. if use_space_char:
  75. character_list.append(" ")
  76. character_list = self.add_special_char(character_list)
  77. self.dict = {}
  78. for i, char in enumerate(character_list):
  79. self.dict[char] = i
  80. self.character = character_list
  81. def pred_reverse(self, pred):
  82. """pred_reverse"""
  83. pred_re = []
  84. c_current = ""
  85. for c in pred:
  86. if not bool(re.search("[a-zA-Z0-9 :*./%+-]", c)):
  87. if c_current != "":
  88. pred_re.append(c_current)
  89. pred_re.append(c)
  90. c_current = ""
  91. else:
  92. c_current += c
  93. if c_current != "":
  94. pred_re.append(c_current)
  95. return "".join(pred_re[::-1])
  96. def add_special_char(self, character_list):
  97. """add_special_char"""
  98. return character_list
  99. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  100. """convert text-index into text-label."""
  101. result_list = []
  102. ignored_tokens = self.get_ignored_tokens()
  103. batch_size = len(text_index)
  104. for batch_idx in range(batch_size):
  105. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  106. if is_remove_duplicate:
  107. selection[1:] = text_index[batch_idx][1:] != text_index[batch_idx][:-1]
  108. for ignored_token in ignored_tokens:
  109. selection &= text_index[batch_idx] != ignored_token
  110. char_list = [
  111. self.character[text_id] for text_id in text_index[batch_idx][selection]
  112. ]
  113. if text_prob is not None:
  114. conf_list = text_prob[batch_idx][selection]
  115. else:
  116. conf_list = [1] * len(selection)
  117. if len(conf_list) == 0:
  118. conf_list = [0]
  119. text = "".join(char_list)
  120. if self.reverse: # for arabic rec
  121. text = self.pred_reverse(text)
  122. result_list.append((text, np.mean(conf_list).tolist()))
  123. return result_list
  124. def get_ignored_tokens(self):
  125. """get_ignored_tokens"""
  126. return [0] # for ctc blank
  127. def __call__(self, pred):
  128. """apply"""
  129. preds = np.array(pred)
  130. if isinstance(preds, tuple) or isinstance(preds, list):
  131. preds = preds[-1]
  132. preds_idx = preds.argmax(axis=-1)
  133. preds_prob = preds.max(axis=-1)
  134. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  135. texts = []
  136. scores = []
  137. for t in text:
  138. texts.append(t[0])
  139. scores.append(t[1])
  140. return texts, scores
  141. @benchmark.timeit
  142. class CTCLabelDecode(BaseRecLabelDecode):
  143. """Convert between text-label and text-index"""
  144. def __init__(self, character_list=None, use_space_char=True):
  145. super().__init__(character_list, use_space_char=use_space_char)
  146. def __call__(self, pred):
  147. """apply"""
  148. preds = np.array(pred[0])
  149. preds_idx = preds.argmax(axis=-1)
  150. preds_prob = preds.max(axis=-1)
  151. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  152. texts = []
  153. scores = []
  154. for t in text:
  155. texts.append(t[0])
  156. scores.append(t[1])
  157. return texts, scores
  158. def add_special_char(self, character_list):
  159. """add_special_char"""
  160. character_list = ["blank"] + character_list
  161. return character_list
  162. @benchmark.timeit
  163. class ToBatch:
  164. """A class for batching and padding images to a uniform width."""
  165. def __pad_imgs(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  166. """Pad images to the maximum width in the batch.
  167. Args:
  168. imgs (list of np.ndarrays): List of images to pad.
  169. Returns:
  170. list of np.ndarrays: List of padded images.
  171. """
  172. max_width = max(img.shape[2] for img in imgs)
  173. padded_imgs = []
  174. for img in imgs:
  175. _, height, width = img.shape
  176. pad_width = max_width - width
  177. padded_img = np.pad(
  178. img,
  179. ((0, 0), (0, 0), (0, pad_width)),
  180. mode="constant",
  181. constant_values=0,
  182. )
  183. padded_imgs.append(padded_img)
  184. return padded_imgs
  185. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  186. """Call method to pad images and stack them into a batch.
  187. Args:
  188. imgs (list of np.ndarrays): List of images to process.
  189. Returns:
  190. list of np.ndarrays: List containing a stacked tensor of the padded images.
  191. """
  192. imgs = self.__pad_imgs(imgs)
  193. return [np.stack(imgs, axis=0).astype(dtype=np.float32, copy=False)]