transforms.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. import re
  17. import numpy as np
  18. from PIL import Image
  19. import cv2
  20. import math
  21. import paddle
  22. import json
  23. import tempfile
  24. from tokenizers import Tokenizer as TokenizerFast
  25. from ....utils import logging
  26. from ...base.predictor import BaseTransform
  27. from ...base.predictor.io.writers import TextWriter
  28. from .keys import TextRecKeys as K
  29. __all__ = ['OCRReisizeNormImg', 'LaTeXOCRReisizeNormImg', 'CTCLabelDecode', 'LaTeXOCRDecode', 'SaveTextRecResults']
  30. class OCRReisizeNormImg(BaseTransform):
  31. """ for ocr image resize and normalization """
  32. def __init__(self, rec_image_shape=[3, 48, 320]):
  33. super().__init__()
  34. self.rec_image_shape = rec_image_shape
  35. def resize_norm_img(self, img, max_wh_ratio):
  36. """ resize and normalize the img """
  37. imgC, imgH, imgW = self.rec_image_shape
  38. assert imgC == img.shape[2]
  39. imgW = int((imgH * max_wh_ratio))
  40. h, w = img.shape[:2]
  41. ratio = w / float(h)
  42. if math.ceil(imgH * ratio) > imgW:
  43. resized_w = imgW
  44. else:
  45. resized_w = int(math.ceil(imgH * ratio))
  46. resized_image = cv2.resize(img, (resized_w, imgH))
  47. resized_image = resized_image.astype('float32')
  48. resized_image = resized_image.transpose((2, 0, 1)) / 255
  49. resized_image -= 0.5
  50. resized_image /= 0.5
  51. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  52. padding_im[:, :, 0:resized_w] = resized_image
  53. return padding_im
  54. def apply(self, data):
  55. """ apply """
  56. imgC, imgH, imgW = self.rec_image_shape
  57. max_wh_ratio = imgW / imgH
  58. w, h = data[K.ORI_IM_SIZE]
  59. wh_ratio = w * 1.0 / h
  60. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  61. data[K.IMAGE] = self.resize_norm_img(data[K.IMAGE], max_wh_ratio)
  62. return data
  63. @classmethod
  64. def get_input_keys(cls):
  65. """ get input keys """
  66. return [K.IMAGE, K.ORI_IM_SIZE]
  67. @classmethod
  68. def get_output_keys(cls):
  69. """ get output keys """
  70. return [K.IMAGE]
  71. class LaTeXOCRReisizeNormImg(BaseTransform):
  72. """ for ocr image resize and normalization """
  73. def __init__(self, rec_image_shape=[3, 48, 320]):
  74. super().__init__()
  75. self.rec_image_shape = rec_image_shape
  76. def pad_(self, img, divable=32):
  77. threshold = 128
  78. data = np.array(img.convert("LA"))
  79. if data[..., -1].var() == 0:
  80. data = (data[..., 0]).astype(np.uint8)
  81. else:
  82. data = (255 - data[..., -1]).astype(np.uint8)
  83. data = (data - data.min()) / (data.max() - data.min()) * 255
  84. if data.mean() > threshold:
  85. # To invert the text to white
  86. gray = 255 * (data < threshold).astype(np.uint8)
  87. else:
  88. gray = 255 * (data > threshold).astype(np.uint8)
  89. data = 255 - data
  90. coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  91. a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  92. rect = data[b: b + h, a: a + w]
  93. im = Image.fromarray(rect).convert("L")
  94. dims = []
  95. for x in [w, h]:
  96. div, mod = divmod(x, divable)
  97. dims.append(divable * (div + (1 if mod > 0 else 0)))
  98. padded = Image.new("L", dims, 255)
  99. padded.paste(im, (0, 0, im.size[0], im.size[1]))
  100. return padded
  101. def minmax_size_(
  102. self,
  103. img,
  104. max_dimensions,
  105. min_dimensions,
  106. ):
  107. if max_dimensions is not None:
  108. ratios = [a / b for a, b in zip(img.size, max_dimensions)]
  109. if any([r > 1 for r in ratios]):
  110. size = np.array(img.size) // max(ratios)
  111. img = img.resize(tuple(size.astype(int)), Image.BILINEAR)
  112. if min_dimensions is not None:
  113. # hypothesis: there is a dim in img smaller than min_dimensions, and return a proper dim >= min_dimensions
  114. padded_size = [
  115. max(img_dim, min_dim)
  116. for img_dim, min_dim in zip(img.size, min_dimensions)
  117. ]
  118. if padded_size != list(img.size): # assert hypothesis
  119. padded_im = Image.new("L", padded_size, 255)
  120. padded_im.paste(img, img.getbbox())
  121. img = padded_im
  122. return img
  123. def norm_img_latexocr(self, img):
  124. # CAN only predict gray scale image
  125. shape = (1, 1, 3)
  126. mean = [0.7931, 0.7931, 0.7931]
  127. std = [0.1738, 0.1738, 0.1738]
  128. scale = np.float32(1.0 / 255.0)
  129. min_dimensions = [32, 32]
  130. max_dimensions = [672, 192]
  131. mean = np.array(mean).reshape(shape).astype("float32")
  132. std = np.array(std).reshape(shape).astype("float32")
  133. im_h, im_w = img.shape[:2]
  134. if (
  135. min_dimensions[0] <= im_w <= max_dimensions[0]
  136. and min_dimensions[1] <= im_h <= max_dimensions[1]
  137. ):
  138. pass
  139. else:
  140. img = Image.fromarray(np.uint8(img))
  141. img = self.minmax_size_(self.pad_(img), max_dimensions, min_dimensions)
  142. img = np.array(img)
  143. im_h, im_w = img.shape[:2]
  144. img = np.dstack([img, img, img])
  145. img = (img.astype("float32") * scale - mean) / std
  146. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  147. divide_h = math.ceil(im_h / 16) * 16
  148. divide_w = math.ceil(im_w / 16) * 16
  149. img = np.pad(
  150. img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  151. )
  152. img = img[:, :, np.newaxis].transpose(2, 0, 1)
  153. img = img.astype("float32")
  154. return img
  155. def apply(self, data):
  156. """ apply """
  157. data[K.IMAGE] = self.norm_img_latexocr(data[K.IMAGE])
  158. return data
  159. @classmethod
  160. def get_input_keys(cls):
  161. """ get input keys """
  162. return [K.IMAGE, K.ORI_IM_SIZE]
  163. @classmethod
  164. def get_output_keys(cls):
  165. """ get output keys """
  166. return [K.IMAGE]
  167. class BaseRecLabelDecode(BaseTransform):
  168. """ Convert between text-label and text-index """
  169. def __init__(self, character_str=None, use_space_char=True):
  170. self.reverse = False
  171. character_list = list(
  172. character_str) if character_str is not None else list(
  173. "0123456789abcdefghijklmnopqrstuvwxyz")
  174. if use_space_char:
  175. character_list.append(" ")
  176. character_list = self.add_special_char(character_list)
  177. self.dict = {}
  178. for i, char in enumerate(character_list):
  179. self.dict[char] = i
  180. self.character = character_list
  181. def pred_reverse(self, pred):
  182. """ pred_reverse """
  183. pred_re = []
  184. c_current = ''
  185. for c in pred:
  186. if not bool(re.search('[a-zA-Z0-9 :*./%+-]', c)):
  187. if c_current != '':
  188. pred_re.append(c_current)
  189. pred_re.append(c)
  190. c_current = ''
  191. else:
  192. c_current += c
  193. if c_current != '':
  194. pred_re.append(c_current)
  195. return ''.join(pred_re[::-1])
  196. def add_special_char(self, character_list):
  197. """ add_special_char """
  198. return character_list
  199. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  200. """ convert text-index into text-label. """
  201. result_list = []
  202. ignored_tokens = self.get_ignored_tokens()
  203. batch_size = len(text_index)
  204. for batch_idx in range(batch_size):
  205. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  206. if is_remove_duplicate:
  207. selection[1:] = text_index[batch_idx][1:] != text_index[
  208. batch_idx][:-1]
  209. for ignored_token in ignored_tokens:
  210. selection &= text_index[batch_idx] != ignored_token
  211. char_list = [
  212. self.character[text_id]
  213. for text_id in text_index[batch_idx][selection]
  214. ]
  215. if text_prob is not None:
  216. conf_list = text_prob[batch_idx][selection]
  217. else:
  218. conf_list = [1] * len(selection)
  219. if len(conf_list) == 0:
  220. conf_list = [0]
  221. text = ''.join(char_list)
  222. if self.reverse: # for arabic rec
  223. text = self.pred_reverse(text)
  224. result_list.append((text, np.mean(conf_list).tolist()))
  225. return result_list
  226. def get_ignored_tokens(self):
  227. """ get_ignored_tokens """
  228. return [0] # for ctc blank
  229. def apply(self, data):
  230. """ apply """
  231. preds = data[K.REC_PROBS]
  232. if isinstance(preds, tuple) or isinstance(preds, list):
  233. preds = preds[-1]
  234. preds_idx = preds.argmax(axis=2)
  235. preds_prob = preds.max(axis=2)
  236. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  237. data[K.REC_TEXT] = []
  238. data[K.REC_SCORE] = []
  239. for t in text:
  240. data[K.REC_TEXT].append(t[0])
  241. data[K.REC_SCORE].append(t[1])
  242. return data
  243. @classmethod
  244. def get_input_keys(cls):
  245. """ get_input_keys """
  246. return [K.REC_PROBS]
  247. @classmethod
  248. def get_output_keys(cls):
  249. """ get_output_keys """
  250. return [K.REC_TEXT, K.REC_SCORE]
  251. class CTCLabelDecode(BaseRecLabelDecode):
  252. """ Convert between text-label and text-index """
  253. def __init__(self, post_process_cfg=None, use_space_char=True):
  254. assert post_process_cfg['name'] == 'CTCLabelDecode'
  255. character_list = post_process_cfg['character_dict']
  256. super().__init__(character_list, use_space_char=use_space_char)
  257. def apply(self, data):
  258. """ apply """
  259. preds = data[K.REC_PROBS]
  260. if isinstance(preds, tuple) or isinstance(preds, list):
  261. preds = preds[-1]
  262. preds_idx = preds.argmax(axis=2)
  263. preds_prob = preds.max(axis=2)
  264. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  265. data[K.REC_TEXT] = []
  266. data[K.REC_SCORE] = []
  267. for t in text:
  268. data[K.REC_TEXT].append(t[0])
  269. data[K.REC_SCORE].append(t[1])
  270. return data
  271. def add_special_char(self, character_list):
  272. """ add_special_char """
  273. character_list = ['blank'] + character_list
  274. return character_list
  275. @classmethod
  276. def get_input_keys(cls):
  277. """ get_input_keys """
  278. return [K.REC_PROBS]
  279. @classmethod
  280. def get_output_keys(cls):
  281. """ get_output_keys """
  282. return [K.REC_TEXT, K.REC_SCORE]
  283. class LaTeXOCRDecode(object):
  284. """Convert between latex-symbol and symbol-index"""
  285. def __init__(self, post_process_cfg=None, **kwargs):
  286. assert post_process_cfg['name'] == 'LaTeXOCRDecode'
  287. super(LaTeXOCRDecode, self).__init__()
  288. character_list = post_process_cfg['character_dict']
  289. temp_path = tempfile.gettempdir()
  290. rec_char_dict_path = os.path.join(temp_path, "latexocr_tokenizer.json")
  291. try:
  292. with open(rec_char_dict_path, "w") as f:
  293. json.dump(character_list, f)
  294. except Exception as e:
  295. print(f'创建 latexocr_tokenizer.json 文件失败, 原因{str(e)}')
  296. self.tokenizer = TokenizerFast.from_file(rec_char_dict_path)
  297. def post_process(self, s):
  298. text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  299. letter = "[a-zA-Z]"
  300. noletter = "[\W_^\d]"
  301. names = [x[0].replace(" ", "") for x in re.findall(text_reg, s)]
  302. s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  303. news = s
  304. while True:
  305. s = news
  306. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  307. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  308. news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  309. if news == s:
  310. break
  311. return s
  312. def decode(self, tokens):
  313. if len(tokens.shape) == 1:
  314. tokens = tokens[None, :]
  315. dec = [self.tokenizer.decode(tok) for tok in tokens]
  316. dec_str_list = [
  317. "".join(detok.split(" "))
  318. .replace("Ġ", " ")
  319. .replace("[EOS]", "")
  320. .replace("[BOS]", "")
  321. .replace("[PAD]", "")
  322. .strip()
  323. for detok in dec
  324. ]
  325. return [str(self.post_process(dec_str)) for dec_str in dec_str_list]
  326. def __call__(self, data):
  327. preds = data[K.REC_PROBS]
  328. text = self.decode(preds)
  329. data[K.REC_TEXT] = text[0]
  330. return data
  331. class SaveTextRecResults(BaseTransform):
  332. """ SaveTextRecResults """
  333. _TEXT_REC_RES_SUFFIX = '_text_rec'
  334. _FILE_EXT = '.txt'
  335. def __init__(self, save_dir):
  336. super().__init__()
  337. self.save_dir = save_dir
  338. # We use python backend to save text object
  339. self._writer = TextWriter(backend='python')
  340. def apply(self, data):
  341. """ apply """
  342. ori_path = data[K.IM_PATH]
  343. file_name = os.path.basename(ori_path)
  344. file_name = self._replace_ext(file_name, self._FILE_EXT)
  345. text_rec_res_save_path = os.path.join(self.save_dir, file_name)
  346. rec_res = ''
  347. for text, score in zip(data[K.REC_TEXT], data[K.REC_SCORE]):
  348. line = text + '\t' + str(score) + '\n'
  349. rec_res += line
  350. text_rec_res_save_path = self._add_suffix(text_rec_res_save_path,
  351. self._TEXT_REC_RES_SUFFIX)
  352. self._write_txt(text_rec_res_save_path, rec_res)
  353. return data
  354. @classmethod
  355. def get_input_keys(cls):
  356. """ get_input_keys """
  357. return [K.IM_PATH, K.REC_TEXT, K.REC_SCORE]
  358. @classmethod
  359. def get_output_keys(cls):
  360. """ get_output_keys """
  361. return []
  362. def _write_txt(self, path, txt_str):
  363. """ _write_txt """
  364. if os.path.exists(path):
  365. logging.warning(f"{path} already exists. Overwriting it.")
  366. self._writer.write(path, txt_str)
  367. @staticmethod
  368. def _add_suffix(path, suffix):
  369. """ _add_suffix """
  370. stem, ext = os.path.splitext(path)
  371. return stem + suffix + ext
  372. @staticmethod
  373. def _replace_ext(path, new_ext):
  374. """ _replace_ext """
  375. stem, _ = os.path.splitext(path)
  376. return stem + new_ext
  377. class PrintResult(BaseTransform):
  378. """ Print Result Transform """
  379. def apply(self, data):
  380. """ apply """
  381. logging.info("The prediction result is:")
  382. logging.info(data[K.REC_TEXT])
  383. return data
  384. @classmethod
  385. def get_input_keys(cls):
  386. """ get input keys """
  387. return [K.REC_TEXT]
  388. @classmethod
  389. def get_output_keys(cls):
  390. """ get output keys """
  391. return []