processors.py 7.5 KB

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