text_rec.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 ...results import TextRecResult
  27. from ..base import BaseComponent
  28. __all__ = [
  29. "OCRReisizeNormImg",
  30. # "LaTeXOCRReisizeNormImg",
  31. "CTCLabelDecode",
  32. # "LaTeXOCRDecode",
  33. ]
  34. class OCRReisizeNormImg(BaseComponent):
  35. """for ocr image resize and normalization"""
  36. INPUT_KEYS = ["img", "img_size"]
  37. OUTPUT_KEYS = ["img"]
  38. DEAULT_INPUTS = {"img": "img", "img_size": "img_size"}
  39. DEAULT_OUTPUTS = {"img": "img"}
  40. def __init__(self, rec_image_shape=[3, 48, 320]):
  41. super().__init__()
  42. self.rec_image_shape = rec_image_shape
  43. def resize_norm_img(self, img, max_wh_ratio):
  44. """resize and normalize the img"""
  45. imgC, imgH, imgW = self.rec_image_shape
  46. assert imgC == img.shape[2]
  47. imgW = int((imgH * max_wh_ratio))
  48. h, w = img.shape[:2]
  49. ratio = w / float(h)
  50. if math.ceil(imgH * ratio) > imgW:
  51. resized_w = imgW
  52. else:
  53. resized_w = int(math.ceil(imgH * ratio))
  54. resized_image = cv2.resize(img, (resized_w, imgH))
  55. resized_image = resized_image.astype("float32")
  56. resized_image = resized_image.transpose((2, 0, 1)) / 255
  57. resized_image -= 0.5
  58. resized_image /= 0.5
  59. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  60. padding_im[:, :, 0:resized_w] = resized_image
  61. return padding_im
  62. def apply(self, img, img_size):
  63. """apply"""
  64. imgC, imgH, imgW = self.rec_image_shape
  65. max_wh_ratio = imgW / imgH
  66. w, h = img_size[:2]
  67. wh_ratio = w * 1.0 / h
  68. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  69. img = self.resize_norm_img(img, max_wh_ratio)
  70. return {"img": img}
  71. # class LaTeXOCRReisizeNormImg(BaseComponent):
  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(BaseComponent):
  168. """Convert between text-label and text-index"""
  169. INPUT_KEYS = ["pred", "img_path"]
  170. OUTPUT_KEYS = ["text_rec_res"]
  171. DEAULT_INPUTS = {"pred": "pred", "img_path": "img_path"}
  172. DEAULT_OUTPUTS = {"text_rec_res": "text_rec_res"}
  173. ENABLE_BATCH = True
  174. def __init__(self, character_str=None, use_space_char=True):
  175. super().__init__()
  176. self.reverse = False
  177. character_list = (
  178. list(character_str)
  179. if character_str is not None
  180. else list("0123456789abcdefghijklmnopqrstuvwxyz")
  181. )
  182. if use_space_char:
  183. character_list.append(" ")
  184. character_list = self.add_special_char(character_list)
  185. self.dict = {}
  186. for i, char in enumerate(character_list):
  187. self.dict[char] = i
  188. self.character = character_list
  189. def pred_reverse(self, pred):
  190. """pred_reverse"""
  191. pred_re = []
  192. c_current = ""
  193. for c in pred:
  194. if not bool(re.search("[a-zA-Z0-9 :*./%+-]", c)):
  195. if c_current != "":
  196. pred_re.append(c_current)
  197. pred_re.append(c)
  198. c_current = ""
  199. else:
  200. c_current += c
  201. if c_current != "":
  202. pred_re.append(c_current)
  203. return "".join(pred_re[::-1])
  204. def add_special_char(self, character_list):
  205. """add_special_char"""
  206. return character_list
  207. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  208. """convert text-index into text-label."""
  209. result_list = []
  210. ignored_tokens = self.get_ignored_tokens()
  211. batch_size = len(text_index)
  212. for batch_idx in range(batch_size):
  213. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  214. if is_remove_duplicate:
  215. selection[1:] = text_index[batch_idx][1:] != text_index[batch_idx][:-1]
  216. for ignored_token in ignored_tokens:
  217. selection &= text_index[batch_idx] != ignored_token
  218. char_list = [
  219. self.character[text_id] for text_id in text_index[batch_idx][selection]
  220. ]
  221. if text_prob is not None:
  222. conf_list = text_prob[batch_idx][selection]
  223. else:
  224. conf_list = [1] * len(selection)
  225. if len(conf_list) == 0:
  226. conf_list = [0]
  227. text = "".join(char_list)
  228. if self.reverse: # for arabic rec
  229. text = self.pred_reverse(text)
  230. result_list.append((text, np.mean(conf_list).tolist()))
  231. return result_list
  232. def get_ignored_tokens(self):
  233. """get_ignored_tokens"""
  234. return [0] # for ctc blank
  235. def apply(self, pred, img_path):
  236. """apply"""
  237. preds = np.array(pred)
  238. if isinstance(preds, tuple) or isinstance(preds, list):
  239. preds = preds[-1]
  240. preds_idx = preds.argmax(axis=2)
  241. preds_prob = preds.max(axis=2)
  242. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  243. return [
  244. {
  245. "text_rec_res": TextRecResult(
  246. {"img_path": path, "rec_text": t[0], "rec_score": t[1]}
  247. )
  248. }
  249. for path, t in zip(img_path, text)
  250. ]
  251. class CTCLabelDecode(BaseRecLabelDecode):
  252. """Convert between text-label and text-index"""
  253. def __init__(self, character_list=None, use_space_char=True):
  254. super().__init__(character_list, use_space_char=use_space_char)
  255. def apply(self, pred, img_path):
  256. """apply"""
  257. preds = np.array(pred)
  258. preds_idx = preds.argmax(axis=2)
  259. preds_prob = preds.max(axis=2)
  260. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  261. return [
  262. {
  263. "text_rec_res": TextRecResult(
  264. {"img_path": path, "rec_text": t[0], "rec_score": t[1]}
  265. )
  266. }
  267. for path, t in zip(img_path, text)
  268. ]
  269. def add_special_char(self, character_list):
  270. """add_special_char"""
  271. character_list = ["blank"] + character_list
  272. return character_list
  273. # class LaTeXOCRDecode(object):
  274. # """Convert between latex-symbol and symbol-index"""
  275. # def __init__(self, post_process_cfg=None, **kwargs):
  276. # assert post_process_cfg["name"] == "LaTeXOCRDecode"
  277. # super(LaTeXOCRDecode, self).__init__()
  278. # character_list = post_process_cfg["character_dict"]
  279. # temp_path = tempfile.gettempdir()
  280. # rec_char_dict_path = os.path.join(temp_path, "latexocr_tokenizer.json")
  281. # try:
  282. # with open(rec_char_dict_path, "w") as f:
  283. # json.dump(character_list, f)
  284. # except Exception as e:
  285. # print(f"创建 latexocr_tokenizer.json 文件失败, 原因{str(e)}")
  286. # self.tokenizer = TokenizerFast.from_file(rec_char_dict_path)
  287. # def post_process(self, s):
  288. # text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  289. # letter = "[a-zA-Z]"
  290. # noletter = "[\W_^\d]"
  291. # names = [x[0].replace(" ", "") for x in re.findall(text_reg, s)]
  292. # s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  293. # news = s
  294. # while True:
  295. # s = news
  296. # news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  297. # news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  298. # news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  299. # if news == s:
  300. # break
  301. # return s
  302. # def decode(self, tokens):
  303. # if len(tokens.shape) == 1:
  304. # tokens = tokens[None, :]
  305. # dec = [self.tokenizer.decode(tok) for tok in tokens]
  306. # dec_str_list = [
  307. # "".join(detok.split(" "))
  308. # .replace("Ġ", " ")
  309. # .replace("[EOS]", "")
  310. # .replace("[BOS]", "")
  311. # .replace("[PAD]", "")
  312. # .strip()
  313. # for detok in dec
  314. # ]
  315. # return [str(self.post_process(dec_str)) for dec_str in dec_str_list]
  316. # def __call__(self, data):
  317. # preds = data[K.REC_PROBS]
  318. # text = self.decode(preds)
  319. # data[K.REC_TEXT] = text[0]
  320. # return data
  321. # class SaveTextRecResults(BaseComponent):
  322. # """SaveTextRecResults"""
  323. # _TEXT_REC_RES_SUFFIX = "_text_rec"
  324. # _FILE_EXT = ".txt"
  325. # def __init__(self, save_dir):
  326. # super().__init__()
  327. # self.save_dir = save_dir
  328. # # We use python backend to save text object
  329. # self._writer = TextWriter(backend="python")
  330. # def apply(self, data):
  331. # """apply"""
  332. # ori_path = data[K.IM_PATH]
  333. # file_name = os.path.basename(ori_path)
  334. # file_name = self._replace_ext(file_name, self._FILE_EXT)
  335. # text_rec_res_save_path = os.path.join(self.save_dir, file_name)
  336. # rec_res = ""
  337. # for text, score in zip(data[K.REC_TEXT], data[K.REC_SCORE]):
  338. # line = text + "\t" + str(score) + "\n"
  339. # rec_res += line
  340. # text_rec_res_save_path = self._add_suffix(
  341. # text_rec_res_save_path, self._TEXT_REC_RES_SUFFIX
  342. # )
  343. # self._write_txt(text_rec_res_save_path, rec_res)
  344. # return data
  345. # @classmethod
  346. # def get_input_keys(cls):
  347. # """get_input_keys"""
  348. # return [K.IM_PATH, K.REC_TEXT, K.REC_SCORE]
  349. # @classmethod
  350. # def get_output_keys(cls):
  351. # """get_output_keys"""
  352. # return []
  353. # def _write_txt(self, path, txt_str):
  354. # """_write_txt"""
  355. # if os.path.exists(path):
  356. # logging.warning(f"{path} already exists. Overwriting it.")
  357. # self._writer.write(path, txt_str)
  358. # @staticmethod
  359. # def _add_suffix(path, suffix):
  360. # """_add_suffix"""
  361. # stem, ext = os.path.splitext(path)
  362. # return stem + suffix + ext
  363. # @staticmethod
  364. # def _replace_ext(path, new_ext):
  365. # """_replace_ext"""
  366. # stem, _ = os.path.splitext(path)
  367. # return stem + new_ext
  368. # class PrintResult(BaseComponent):
  369. # """Print Result Transform"""
  370. # def apply(self, data):
  371. # """apply"""
  372. # logging.info("The prediction result is:")
  373. # logging.info(data[K.REC_TEXT])
  374. # return data
  375. # @classmethod
  376. # def get_input_keys(cls):
  377. # """get input keys"""
  378. # return [K.REC_TEXT]
  379. # @classmethod
  380. # def get_output_keys(cls):
  381. # """get output keys"""
  382. # return []