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. class OCRReisizeNormImg:
  28. """for ocr image resize and normalization"""
  29. def __init__(self, rec_image_shape=[3, 48, 320]):
  30. super().__init__()
  31. self.rec_image_shape = rec_image_shape
  32. def resize_norm_img(self, img, max_wh_ratio):
  33. """resize and normalize the img"""
  34. imgC, imgH, imgW = self.rec_image_shape
  35. assert imgC == img.shape[2]
  36. imgW = int((imgH * max_wh_ratio))
  37. h, w = img.shape[:2]
  38. ratio = w / float(h)
  39. if math.ceil(imgH * ratio) > imgW:
  40. resized_w = imgW
  41. else:
  42. resized_w = int(math.ceil(imgH * ratio))
  43. resized_image = cv2.resize(img, (resized_w, imgH))
  44. resized_image = resized_image.astype("float32")
  45. resized_image = resized_image.transpose((2, 0, 1)) / 255
  46. resized_image -= 0.5
  47. resized_image /= 0.5
  48. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  49. padding_im[:, :, 0:resized_w] = resized_image
  50. return padding_im
  51. @benchmark.timeit
  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. class BaseRecLabelDecode:
  64. """Convert between text-label and text-index"""
  65. def __init__(self, character_str=None, use_space_char=True):
  66. super().__init__()
  67. self.reverse = False
  68. character_list = (
  69. list(character_str)
  70. if character_str is not None
  71. else list("0123456789abcdefghijklmnopqrstuvwxyz")
  72. )
  73. if use_space_char:
  74. character_list.append(" ")
  75. character_list = self.add_special_char(character_list)
  76. self.dict = {}
  77. for i, char in enumerate(character_list):
  78. self.dict[char] = i
  79. self.character = character_list
  80. def pred_reverse(self, pred):
  81. """pred_reverse"""
  82. pred_re = []
  83. c_current = ""
  84. for c in pred:
  85. if not bool(re.search("[a-zA-Z0-9 :*./%+-]", c)):
  86. if c_current != "":
  87. pred_re.append(c_current)
  88. pred_re.append(c)
  89. c_current = ""
  90. else:
  91. c_current += c
  92. if c_current != "":
  93. pred_re.append(c_current)
  94. return "".join(pred_re[::-1])
  95. def add_special_char(self, character_list):
  96. """add_special_char"""
  97. return character_list
  98. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  99. """convert text-index into text-label."""
  100. result_list = []
  101. ignored_tokens = self.get_ignored_tokens()
  102. batch_size = len(text_index)
  103. for batch_idx in range(batch_size):
  104. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  105. if is_remove_duplicate:
  106. selection[1:] = text_index[batch_idx][1:] != text_index[batch_idx][:-1]
  107. for ignored_token in ignored_tokens:
  108. selection &= text_index[batch_idx] != ignored_token
  109. char_list = [
  110. self.character[text_id] for text_id in text_index[batch_idx][selection]
  111. ]
  112. if text_prob is not None:
  113. conf_list = text_prob[batch_idx][selection]
  114. else:
  115. conf_list = [1] * len(selection)
  116. if len(conf_list) == 0:
  117. conf_list = [0]
  118. text = "".join(char_list)
  119. if self.reverse: # for arabic rec
  120. text = self.pred_reverse(text)
  121. result_list.append((text, np.mean(conf_list).tolist()))
  122. return result_list
  123. def get_ignored_tokens(self):
  124. """get_ignored_tokens"""
  125. return [0] # for ctc blank
  126. @benchmark.timeit
  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. class CTCLabelDecode(BaseRecLabelDecode):
  142. """Convert between text-label and text-index"""
  143. def __init__(self, character_list=None, use_space_char=True):
  144. super().__init__(character_list, use_space_char=use_space_char)
  145. @benchmark.timeit
  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. class ToBatch:
  163. """A class for batching and padding images to a uniform width."""
  164. def __pad_imgs(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  165. """Pad images to the maximum width in the batch.
  166. Args:
  167. imgs (list of np.ndarrays): List of images to pad.
  168. Returns:
  169. list of np.ndarrays: List of padded images.
  170. """
  171. max_width = max(img.shape[2] for img in imgs)
  172. padded_imgs = []
  173. for img in imgs:
  174. _, height, width = img.shape
  175. pad_width = max_width - width
  176. padded_img = np.pad(
  177. img,
  178. ((0, 0), (0, 0), (0, pad_width)),
  179. mode="constant",
  180. constant_values=0,
  181. )
  182. padded_imgs.append(padded_img)
  183. return padded_imgs
  184. @benchmark.timeit
  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)]