predict_rec.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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 sys
  16. from PIL import Image
  17. __dir__ = os.path.dirname(os.path.abspath(__file__))
  18. sys.path.append(__dir__)
  19. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "../..")))
  20. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  21. import cv2
  22. import numpy as np
  23. import math
  24. import time
  25. import traceback
  26. import paddle
  27. import tools.infer.utility as utility
  28. from ppocr.postprocess import build_post_process
  29. from ppocr.utils.logging import get_logger
  30. from ppocr.utils.utility import get_image_file_list, check_and_read
  31. logger = get_logger()
  32. class TextRecognizer(object):
  33. def __init__(self, args, logger=None):
  34. if os.path.exists(f"{args.rec_model_dir}/inference.yml"):
  35. model_config = utility.load_config(f"{args.rec_model_dir}/inference.yml")
  36. model_name = model_config.get("Global", {}).get("model_name", "")
  37. if model_name and model_name not in [
  38. "PP-OCRv5_mobile_rec",
  39. "PP-OCRv5_server_rec",
  40. "korean_PP-OCRv5_mobile_rec",
  41. "eslav_PP-OCRv5_mobile_rec",
  42. "latin_PP-OCRv5_mobile_rec",
  43. "en_PP-OCRv5_mobile_rec",
  44. "th_PP-OCRv5_mobile_rec",
  45. "el_PP-OCRv5_mobile_rec",
  46. ]:
  47. raise ValueError(
  48. f"{model_name} is not supported. Please check if the model is supported by the PaddleOCR wheel."
  49. )
  50. if args.rec_char_dict_path == "./ppocr/utils/ppocr_keys_v1.txt":
  51. rec_char_list = model_config.get("PostProcess", {}).get(
  52. "character_dict", []
  53. )
  54. if rec_char_list:
  55. new_rec_char_dict_path = f"{args.rec_model_dir}/ppocr_keys.txt"
  56. with open(new_rec_char_dict_path, "w", encoding="utf-8") as f:
  57. f.writelines([char + "\n" for char in rec_char_list])
  58. args.rec_char_dict_path = new_rec_char_dict_path
  59. if logger is None:
  60. logger = get_logger()
  61. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  62. self.rec_batch_num = args.rec_batch_num
  63. self.rec_algorithm = args.rec_algorithm
  64. postprocess_params = {
  65. "name": "CTCLabelDecode",
  66. "character_dict_path": args.rec_char_dict_path,
  67. "use_space_char": args.use_space_char,
  68. }
  69. if self.rec_algorithm == "SRN":
  70. postprocess_params = {
  71. "name": "SRNLabelDecode",
  72. "character_dict_path": args.rec_char_dict_path,
  73. "use_space_char": args.use_space_char,
  74. }
  75. elif self.rec_algorithm == "RARE":
  76. postprocess_params = {
  77. "name": "AttnLabelDecode",
  78. "character_dict_path": args.rec_char_dict_path,
  79. "use_space_char": args.use_space_char,
  80. }
  81. elif self.rec_algorithm == "NRTR":
  82. postprocess_params = {
  83. "name": "NRTRLabelDecode",
  84. "character_dict_path": args.rec_char_dict_path,
  85. "use_space_char": args.use_space_char,
  86. }
  87. elif self.rec_algorithm == "SAR":
  88. postprocess_params = {
  89. "name": "SARLabelDecode",
  90. "character_dict_path": args.rec_char_dict_path,
  91. "use_space_char": args.use_space_char,
  92. }
  93. elif self.rec_algorithm == "VisionLAN":
  94. postprocess_params = {
  95. "name": "VLLabelDecode",
  96. "character_dict_path": args.rec_char_dict_path,
  97. "use_space_char": args.use_space_char,
  98. "max_text_length": args.max_text_length,
  99. }
  100. elif self.rec_algorithm == "ViTSTR":
  101. postprocess_params = {
  102. "name": "ViTSTRLabelDecode",
  103. "character_dict_path": args.rec_char_dict_path,
  104. "use_space_char": args.use_space_char,
  105. }
  106. elif self.rec_algorithm == "ABINet":
  107. postprocess_params = {
  108. "name": "ABINetLabelDecode",
  109. "character_dict_path": args.rec_char_dict_path,
  110. "use_space_char": args.use_space_char,
  111. }
  112. elif self.rec_algorithm == "SPIN":
  113. postprocess_params = {
  114. "name": "SPINLabelDecode",
  115. "character_dict_path": args.rec_char_dict_path,
  116. "use_space_char": args.use_space_char,
  117. }
  118. elif self.rec_algorithm == "RobustScanner":
  119. postprocess_params = {
  120. "name": "SARLabelDecode",
  121. "character_dict_path": args.rec_char_dict_path,
  122. "use_space_char": args.use_space_char,
  123. "rm_symbol": True,
  124. }
  125. elif self.rec_algorithm == "RFL":
  126. postprocess_params = {
  127. "name": "RFLLabelDecode",
  128. "character_dict_path": None,
  129. "use_space_char": args.use_space_char,
  130. }
  131. elif self.rec_algorithm == "SATRN":
  132. postprocess_params = {
  133. "name": "SATRNLabelDecode",
  134. "character_dict_path": args.rec_char_dict_path,
  135. "use_space_char": args.use_space_char,
  136. "rm_symbol": True,
  137. }
  138. elif self.rec_algorithm in ["CPPD", "CPPDPadding"]:
  139. postprocess_params = {
  140. "name": "CPPDLabelDecode",
  141. "character_dict_path": args.rec_char_dict_path,
  142. "use_space_char": args.use_space_char,
  143. "rm_symbol": True,
  144. }
  145. elif self.rec_algorithm == "PREN":
  146. postprocess_params = {"name": "PRENLabelDecode"}
  147. elif self.rec_algorithm == "CAN":
  148. self.inverse = args.rec_image_inverse
  149. postprocess_params = {
  150. "name": "CANLabelDecode",
  151. "character_dict_path": args.rec_char_dict_path,
  152. "use_space_char": args.use_space_char,
  153. }
  154. elif self.rec_algorithm == "LaTeXOCR":
  155. postprocess_params = {
  156. "name": "LaTeXOCRDecode",
  157. "rec_char_dict_path": args.rec_char_dict_path,
  158. }
  159. elif self.rec_algorithm == "ParseQ":
  160. postprocess_params = {
  161. "name": "ParseQLabelDecode",
  162. "character_dict_path": args.rec_char_dict_path,
  163. "use_space_char": args.use_space_char,
  164. }
  165. self.postprocess_op = build_post_process(postprocess_params)
  166. self.postprocess_params = postprocess_params
  167. (
  168. self.predictor,
  169. self.input_tensor,
  170. self.output_tensors,
  171. self.config,
  172. ) = utility.create_predictor(args, "rec", logger)
  173. self.benchmark = args.benchmark
  174. self.use_onnx = args.use_onnx
  175. if args.benchmark:
  176. import auto_log
  177. pid = os.getpid()
  178. gpu_id = utility.get_infer_gpuid()
  179. self.autolog = auto_log.AutoLogger(
  180. model_name="rec",
  181. model_precision=args.precision,
  182. batch_size=args.rec_batch_num,
  183. data_shape="dynamic",
  184. save_path=None, # not used if logger is not None
  185. inference_config=self.config,
  186. pids=pid,
  187. process_name=None,
  188. gpu_ids=gpu_id if args.use_gpu else None,
  189. time_keys=["preprocess_time", "inference_time", "postprocess_time"],
  190. warmup=0,
  191. logger=logger,
  192. )
  193. self.return_word_box = args.return_word_box
  194. def resize_norm_img(self, img, max_wh_ratio):
  195. imgC, imgH, imgW = self.rec_image_shape
  196. if self.rec_algorithm == "NRTR" or self.rec_algorithm == "ViTSTR":
  197. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  198. # return padding_im
  199. image_pil = Image.fromarray(np.uint8(img))
  200. if self.rec_algorithm == "ViTSTR":
  201. img = image_pil.resize([imgW, imgH], Image.BICUBIC)
  202. else:
  203. img = image_pil.resize([imgW, imgH], Image.Resampling.LANCZOS)
  204. img = np.array(img)
  205. norm_img = np.expand_dims(img, -1)
  206. norm_img = norm_img.transpose((2, 0, 1))
  207. if self.rec_algorithm == "ViTSTR":
  208. norm_img = norm_img.astype(np.float32) / 255.0
  209. else:
  210. norm_img = norm_img.astype(np.float32) / 128.0 - 1.0
  211. return norm_img
  212. elif self.rec_algorithm == "RFL":
  213. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  214. resized_image = cv2.resize(img, (imgW, imgH), interpolation=cv2.INTER_CUBIC)
  215. resized_image = resized_image.astype("float32")
  216. resized_image = resized_image / 255
  217. resized_image = resized_image[np.newaxis, :]
  218. resized_image -= 0.5
  219. resized_image /= 0.5
  220. return resized_image
  221. assert imgC == img.shape[2]
  222. imgW = int((imgH * max_wh_ratio))
  223. if self.use_onnx:
  224. w = self.input_tensor.shape[3:][0]
  225. if isinstance(w, str):
  226. pass
  227. elif w is not None and w > 0:
  228. imgW = w
  229. h, w = img.shape[:2]
  230. ratio = w / float(h)
  231. if math.ceil(imgH * ratio) > imgW:
  232. resized_w = imgW
  233. else:
  234. resized_w = int(math.ceil(imgH * ratio))
  235. if self.rec_algorithm == "RARE":
  236. if resized_w > self.rec_image_shape[2]:
  237. resized_w = self.rec_image_shape[2]
  238. imgW = self.rec_image_shape[2]
  239. resized_image = cv2.resize(img, (resized_w, imgH))
  240. resized_image = resized_image.astype("float32")
  241. resized_image = resized_image.transpose((2, 0, 1)) / 255
  242. resized_image -= 0.5
  243. resized_image /= 0.5
  244. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  245. padding_im[:, :, 0:resized_w] = resized_image
  246. return padding_im
  247. def resize_norm_img_vl(self, img, image_shape):
  248. imgC, imgH, imgW = image_shape
  249. img = img[:, :, ::-1] # bgr2rgb
  250. resized_image = cv2.resize(img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  251. resized_image = resized_image.astype("float32")
  252. resized_image = resized_image.transpose((2, 0, 1)) / 255
  253. return resized_image
  254. def resize_norm_img_srn(self, img, image_shape):
  255. imgC, imgH, imgW = image_shape
  256. img_black = np.zeros((imgH, imgW))
  257. im_hei = img.shape[0]
  258. im_wid = img.shape[1]
  259. if im_wid <= im_hei * 1:
  260. img_new = cv2.resize(img, (imgH * 1, imgH))
  261. elif im_wid <= im_hei * 2:
  262. img_new = cv2.resize(img, (imgH * 2, imgH))
  263. elif im_wid <= im_hei * 3:
  264. img_new = cv2.resize(img, (imgH * 3, imgH))
  265. else:
  266. img_new = cv2.resize(img, (imgW, imgH))
  267. img_np = np.asarray(img_new)
  268. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  269. img_black[:, 0 : img_np.shape[1]] = img_np
  270. img_black = img_black[:, :, np.newaxis]
  271. row, col, c = img_black.shape
  272. c = 1
  273. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  274. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  275. imgC, imgH, imgW = image_shape
  276. feature_dim = int((imgH / 8) * (imgW / 8))
  277. encoder_word_pos = (
  278. np.array(range(0, feature_dim)).reshape((feature_dim, 1)).astype("int64")
  279. )
  280. gsrm_word_pos = (
  281. np.array(range(0, max_text_length))
  282. .reshape((max_text_length, 1))
  283. .astype("int64")
  284. )
  285. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  286. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  287. [-1, 1, max_text_length, max_text_length]
  288. )
  289. gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1, [1, num_heads, 1, 1]).astype(
  290. "float32"
  291. ) * [-1e9]
  292. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  293. [-1, 1, max_text_length, max_text_length]
  294. )
  295. gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2, [1, num_heads, 1, 1]).astype(
  296. "float32"
  297. ) * [-1e9]
  298. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  299. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  300. return [
  301. encoder_word_pos,
  302. gsrm_word_pos,
  303. gsrm_slf_attn_bias1,
  304. gsrm_slf_attn_bias2,
  305. ]
  306. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  307. norm_img = self.resize_norm_img_srn(img, image_shape)
  308. norm_img = norm_img[np.newaxis, :]
  309. [
  310. encoder_word_pos,
  311. gsrm_word_pos,
  312. gsrm_slf_attn_bias1,
  313. gsrm_slf_attn_bias2,
  314. ] = self.srn_other_inputs(image_shape, num_heads, max_text_length)
  315. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  316. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  317. encoder_word_pos = encoder_word_pos.astype(np.int64)
  318. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  319. return (
  320. norm_img,
  321. encoder_word_pos,
  322. gsrm_word_pos,
  323. gsrm_slf_attn_bias1,
  324. gsrm_slf_attn_bias2,
  325. )
  326. def resize_norm_img_sar(self, img, image_shape, width_downsample_ratio=0.25):
  327. imgC, imgH, imgW_min, imgW_max = image_shape
  328. h = img.shape[0]
  329. w = img.shape[1]
  330. valid_ratio = 1.0
  331. # make sure new_width is an integral multiple of width_divisor.
  332. width_divisor = int(1 / width_downsample_ratio)
  333. # resize
  334. ratio = w / float(h)
  335. resize_w = math.ceil(imgH * ratio)
  336. if resize_w % width_divisor != 0:
  337. resize_w = round(resize_w / width_divisor) * width_divisor
  338. if imgW_min is not None:
  339. resize_w = max(imgW_min, resize_w)
  340. if imgW_max is not None:
  341. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  342. resize_w = min(imgW_max, resize_w)
  343. resized_image = cv2.resize(img, (resize_w, imgH))
  344. resized_image = resized_image.astype("float32")
  345. # norm
  346. if image_shape[0] == 1:
  347. resized_image = resized_image / 255
  348. resized_image = resized_image[np.newaxis, :]
  349. else:
  350. resized_image = resized_image.transpose((2, 0, 1)) / 255
  351. resized_image -= 0.5
  352. resized_image /= 0.5
  353. resize_shape = resized_image.shape
  354. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  355. padding_im[:, :, 0:resize_w] = resized_image
  356. pad_shape = padding_im.shape
  357. return padding_im, resize_shape, pad_shape, valid_ratio
  358. def resize_norm_img_spin(self, img):
  359. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  360. # return padding_im
  361. img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC)
  362. img = np.array(img, np.float32)
  363. img = np.expand_dims(img, -1)
  364. img = img.transpose((2, 0, 1))
  365. mean = [127.5]
  366. std = [127.5]
  367. mean = np.array(mean, dtype=np.float32)
  368. std = np.array(std, dtype=np.float32)
  369. mean = np.float32(mean.reshape(1, -1))
  370. stdinv = 1 / np.float32(std.reshape(1, -1))
  371. img -= mean
  372. img *= stdinv
  373. return img
  374. def resize_norm_img_svtr(self, img, image_shape):
  375. imgC, imgH, imgW = image_shape
  376. max_wh_ratio = imgW * 1.0 / imgH
  377. h, w = img.shape[0], img.shape[1]
  378. ratio = w * 1.0 / h
  379. max_wh_ratio = min(max(max_wh_ratio, ratio), max_wh_ratio)
  380. imgW = int(imgH * max_wh_ratio)
  381. if math.ceil(imgH * ratio) > imgW:
  382. resized_w = imgW
  383. else:
  384. resized_w = int(math.ceil(imgH * ratio))
  385. resized_image = cv2.resize(img, (resized_w, imgH))
  386. resized_image = resized_image.astype("float32")
  387. resized_image = resized_image.transpose((2, 0, 1)) / 255
  388. resized_image -= 0.5
  389. resized_image /= 0.5
  390. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  391. padding_im[:, :, 0:resized_w] = resized_image
  392. return padding_im
  393. def resize_norm_img_cppd_padding(
  394. self, img, image_shape, padding=True, interpolation=cv2.INTER_LINEAR
  395. ):
  396. imgC, imgH, imgW = image_shape
  397. h = img.shape[0]
  398. w = img.shape[1]
  399. if not padding:
  400. resized_image = cv2.resize(img, (imgW, imgH), interpolation=interpolation)
  401. resized_w = imgW
  402. else:
  403. ratio = w / float(h)
  404. if math.ceil(imgH * ratio) > imgW:
  405. resized_w = imgW
  406. else:
  407. resized_w = int(math.ceil(imgH * ratio))
  408. resized_image = cv2.resize(img, (resized_w, imgH))
  409. resized_image = resized_image.astype("float32")
  410. if image_shape[0] == 1:
  411. resized_image = resized_image / 255
  412. resized_image = resized_image[np.newaxis, :]
  413. else:
  414. resized_image = resized_image.transpose((2, 0, 1)) / 255
  415. resized_image -= 0.5
  416. resized_image /= 0.5
  417. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  418. padding_im[:, :, 0:resized_w] = resized_image
  419. return padding_im
  420. def resize_norm_img_abinet(self, img, image_shape):
  421. imgC, imgH, imgW = image_shape
  422. resized_image = cv2.resize(img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  423. resized_image = resized_image.astype("float32")
  424. resized_image = resized_image / 255.0
  425. mean = np.array([0.485, 0.456, 0.406])
  426. std = np.array([0.229, 0.224, 0.225])
  427. resized_image = (resized_image - mean[None, None, ...]) / std[None, None, ...]
  428. resized_image = resized_image.transpose((2, 0, 1))
  429. resized_image = resized_image.astype("float32")
  430. return resized_image
  431. def norm_img_can(self, img, image_shape):
  432. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image
  433. if self.inverse:
  434. img = 255 - img
  435. if self.rec_image_shape[0] == 1:
  436. h, w = img.shape
  437. _, imgH, imgW = self.rec_image_shape
  438. if h < imgH or w < imgW:
  439. padding_h = max(imgH - h, 0)
  440. padding_w = max(imgW - w, 0)
  441. img_padded = np.pad(
  442. img,
  443. ((0, padding_h), (0, padding_w)),
  444. "constant",
  445. constant_values=(255),
  446. )
  447. img = img_padded
  448. img = np.expand_dims(img, 0) / 255.0 # h,w,c -> c,h,w
  449. img = img.astype("float32")
  450. return img
  451. def pad_(self, img, divable=32):
  452. threshold = 128
  453. data = np.array(img.convert("LA"))
  454. if data[..., -1].var() == 0:
  455. data = (data[..., 0]).astype(np.uint8)
  456. else:
  457. data = (255 - data[..., -1]).astype(np.uint8)
  458. data = (data - data.min()) / (data.max() - data.min()) * 255
  459. if data.mean() > threshold:
  460. # To invert the text to white
  461. gray = 255 * (data < threshold).astype(np.uint8)
  462. else:
  463. gray = 255 * (data > threshold).astype(np.uint8)
  464. data = 255 - data
  465. coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  466. a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  467. rect = data[b : b + h, a : a + w]
  468. im = Image.fromarray(rect).convert("L")
  469. dims = []
  470. for x in [w, h]:
  471. div, mod = divmod(x, divable)
  472. dims.append(divable * (div + (1 if mod > 0 else 0)))
  473. padded = Image.new("L", dims, 255)
  474. padded.paste(im, (0, 0, im.size[0], im.size[1]))
  475. return padded
  476. def minmax_size_(
  477. self,
  478. img,
  479. max_dimensions,
  480. min_dimensions,
  481. ):
  482. if max_dimensions is not None:
  483. ratios = [a / b for a, b in zip(img.size, max_dimensions)]
  484. if any([r > 1 for r in ratios]):
  485. size = np.array(img.size) // max(ratios)
  486. img = img.resize(tuple(size.astype(int)), Image.BILINEAR)
  487. if min_dimensions is not None:
  488. # hypothesis: there is a dim in img smaller than min_dimensions, and return a proper dim >= min_dimensions
  489. padded_size = [
  490. max(img_dim, min_dim)
  491. for img_dim, min_dim in zip(img.size, min_dimensions)
  492. ]
  493. if padded_size != list(img.size): # assert hypothesis
  494. padded_im = Image.new("L", padded_size, 255)
  495. padded_im.paste(img, img.getbbox())
  496. img = padded_im
  497. return img
  498. def norm_img_latexocr(self, img):
  499. # CAN only predict gray scale image
  500. shape = (1, 1, 3)
  501. mean = [0.7931, 0.7931, 0.7931]
  502. std = [0.1738, 0.1738, 0.1738]
  503. scale = np.float32(1.0 / 255.0)
  504. min_dimensions = [32, 32]
  505. max_dimensions = [672, 192]
  506. mean = np.array(mean).reshape(shape).astype("float32")
  507. std = np.array(std).reshape(shape).astype("float32")
  508. im_h, im_w = img.shape[:2]
  509. if (
  510. min_dimensions[0] <= im_w <= max_dimensions[0]
  511. and min_dimensions[1] <= im_h <= max_dimensions[1]
  512. ):
  513. pass
  514. else:
  515. img = Image.fromarray(np.uint8(img))
  516. img = self.minmax_size_(self.pad_(img), max_dimensions, min_dimensions)
  517. img = np.array(img)
  518. im_h, im_w = img.shape[:2]
  519. img = np.dstack([img, img, img])
  520. img = (img.astype("float32") * scale - mean) / std
  521. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  522. divide_h = math.ceil(im_h / 16) * 16
  523. divide_w = math.ceil(im_w / 16) * 16
  524. img = np.pad(
  525. img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  526. )
  527. img = img[:, :, np.newaxis].transpose(2, 0, 1)
  528. img = img.astype("float32")
  529. return img
  530. def __call__(self, img_list):
  531. img_num = len(img_list)
  532. # Calculate the aspect ratio of all text bars
  533. width_list = []
  534. for img in img_list:
  535. width_list.append(img.shape[1] / float(img.shape[0]))
  536. # Sorting can speed up the recognition process
  537. indices = np.argsort(np.array(width_list))
  538. rec_res = [["", 0.0]] * img_num
  539. batch_num = self.rec_batch_num
  540. st = time.time()
  541. if self.benchmark:
  542. self.autolog.times.start()
  543. for beg_img_no in range(0, img_num, batch_num):
  544. end_img_no = min(img_num, beg_img_no + batch_num)
  545. norm_img_batch = []
  546. if self.rec_algorithm == "SRN":
  547. encoder_word_pos_list = []
  548. gsrm_word_pos_list = []
  549. gsrm_slf_attn_bias1_list = []
  550. gsrm_slf_attn_bias2_list = []
  551. if self.rec_algorithm == "SAR":
  552. valid_ratios = []
  553. imgC, imgH, imgW = self.rec_image_shape[:3]
  554. max_wh_ratio = imgW / imgH
  555. wh_ratio_list = []
  556. for ino in range(beg_img_no, end_img_no):
  557. h, w = img_list[indices[ino]].shape[0:2]
  558. wh_ratio = w * 1.0 / h
  559. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  560. wh_ratio_list.append(wh_ratio)
  561. for ino in range(beg_img_no, end_img_no):
  562. if self.rec_algorithm == "SAR":
  563. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  564. img_list[indices[ino]], self.rec_image_shape
  565. )
  566. norm_img = norm_img[np.newaxis, :]
  567. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  568. valid_ratios.append(valid_ratio)
  569. norm_img_batch.append(norm_img)
  570. elif self.rec_algorithm == "SRN":
  571. norm_img = self.process_image_srn(
  572. img_list[indices[ino]], self.rec_image_shape, 8, 25
  573. )
  574. encoder_word_pos_list.append(norm_img[1])
  575. gsrm_word_pos_list.append(norm_img[2])
  576. gsrm_slf_attn_bias1_list.append(norm_img[3])
  577. gsrm_slf_attn_bias2_list.append(norm_img[4])
  578. norm_img_batch.append(norm_img[0])
  579. elif self.rec_algorithm in ["SVTR", "SATRN", "ParseQ", "CPPD"]:
  580. norm_img = self.resize_norm_img_svtr(
  581. img_list[indices[ino]], self.rec_image_shape
  582. )
  583. norm_img = norm_img[np.newaxis, :]
  584. norm_img_batch.append(norm_img)
  585. elif self.rec_algorithm in ["CPPDPadding"]:
  586. norm_img = self.resize_norm_img_cppd_padding(
  587. img_list[indices[ino]], self.rec_image_shape
  588. )
  589. norm_img = norm_img[np.newaxis, :]
  590. norm_img_batch.append(norm_img)
  591. elif self.rec_algorithm in ["VisionLAN", "PREN"]:
  592. norm_img = self.resize_norm_img_vl(
  593. img_list[indices[ino]], self.rec_image_shape
  594. )
  595. norm_img = norm_img[np.newaxis, :]
  596. norm_img_batch.append(norm_img)
  597. elif self.rec_algorithm == "SPIN":
  598. norm_img = self.resize_norm_img_spin(img_list[indices[ino]])
  599. norm_img = norm_img[np.newaxis, :]
  600. norm_img_batch.append(norm_img)
  601. elif self.rec_algorithm == "ABINet":
  602. norm_img = self.resize_norm_img_abinet(
  603. img_list[indices[ino]], self.rec_image_shape
  604. )
  605. norm_img = norm_img[np.newaxis, :]
  606. norm_img_batch.append(norm_img)
  607. elif self.rec_algorithm == "RobustScanner":
  608. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  609. img_list[indices[ino]],
  610. self.rec_image_shape,
  611. width_downsample_ratio=0.25,
  612. )
  613. norm_img = norm_img[np.newaxis, :]
  614. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  615. valid_ratios = []
  616. valid_ratios.append(valid_ratio)
  617. norm_img_batch.append(norm_img)
  618. word_positions_list = []
  619. word_positions = np.array(range(0, 40)).astype("int64")
  620. word_positions = np.expand_dims(word_positions, axis=0)
  621. word_positions_list.append(word_positions)
  622. elif self.rec_algorithm == "CAN":
  623. norm_img = self.norm_img_can(img_list[indices[ino]], max_wh_ratio)
  624. norm_img = norm_img[np.newaxis, :]
  625. norm_img_batch.append(norm_img)
  626. norm_image_mask = np.ones(norm_img.shape, dtype="float32")
  627. word_label = np.ones([1, 36], dtype="int64")
  628. norm_img_mask_batch = []
  629. word_label_list = []
  630. norm_img_mask_batch.append(norm_image_mask)
  631. word_label_list.append(word_label)
  632. elif self.rec_algorithm == "LaTeXOCR":
  633. norm_img = self.norm_img_latexocr(img_list[indices[ino]])
  634. norm_img = norm_img[np.newaxis, :]
  635. norm_img_batch.append(norm_img)
  636. else:
  637. norm_img = self.resize_norm_img(
  638. img_list[indices[ino]], max_wh_ratio
  639. )
  640. norm_img = norm_img[np.newaxis, :]
  641. norm_img_batch.append(norm_img)
  642. norm_img_batch = np.concatenate(norm_img_batch)
  643. norm_img_batch = norm_img_batch.copy()
  644. if self.benchmark:
  645. self.autolog.times.stamp()
  646. if self.rec_algorithm == "SRN":
  647. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  648. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  649. gsrm_slf_attn_bias1_list = np.concatenate(gsrm_slf_attn_bias1_list)
  650. gsrm_slf_attn_bias2_list = np.concatenate(gsrm_slf_attn_bias2_list)
  651. inputs = [
  652. norm_img_batch,
  653. encoder_word_pos_list,
  654. gsrm_word_pos_list,
  655. gsrm_slf_attn_bias1_list,
  656. gsrm_slf_attn_bias2_list,
  657. ]
  658. if self.use_onnx:
  659. input_dict = {}
  660. input_dict[self.input_tensor.name] = norm_img_batch
  661. outputs = self.predictor.run(self.output_tensors, input_dict)
  662. preds = {"predict": outputs[2]}
  663. else:
  664. input_names = self.predictor.get_input_names()
  665. for i in range(len(input_names)):
  666. input_tensor = self.predictor.get_input_handle(input_names[i])
  667. input_tensor.copy_from_cpu(inputs[i])
  668. self.predictor.run()
  669. outputs = []
  670. for output_tensor in self.output_tensors:
  671. output = output_tensor.copy_to_cpu()
  672. outputs.append(output)
  673. if self.benchmark:
  674. self.autolog.times.stamp()
  675. preds = {"predict": outputs[2]}
  676. elif self.rec_algorithm == "SAR":
  677. valid_ratios = np.concatenate(valid_ratios)
  678. inputs = [
  679. norm_img_batch,
  680. np.array([valid_ratios], dtype=np.float32).T,
  681. ]
  682. if self.use_onnx:
  683. input_dict = {}
  684. input_dict[self.input_tensor.name] = norm_img_batch
  685. outputs = self.predictor.run(self.output_tensors, input_dict)
  686. preds = outputs[0]
  687. else:
  688. input_names = self.predictor.get_input_names()
  689. for i in range(len(input_names)):
  690. input_tensor = self.predictor.get_input_handle(input_names[i])
  691. input_tensor.copy_from_cpu(inputs[i])
  692. self.predictor.run()
  693. outputs = []
  694. for output_tensor in self.output_tensors:
  695. output = output_tensor.copy_to_cpu()
  696. outputs.append(output)
  697. if self.benchmark:
  698. self.autolog.times.stamp()
  699. preds = outputs[0]
  700. elif self.rec_algorithm == "RobustScanner":
  701. valid_ratios = np.concatenate(valid_ratios)
  702. word_positions_list = np.concatenate(word_positions_list)
  703. inputs = [norm_img_batch, valid_ratios, word_positions_list]
  704. if self.use_onnx:
  705. input_dict = {}
  706. input_dict[self.input_tensor.name] = norm_img_batch
  707. outputs = self.predictor.run(self.output_tensors, input_dict)
  708. preds = outputs[0]
  709. else:
  710. input_names = self.predictor.get_input_names()
  711. for i in range(len(input_names)):
  712. input_tensor = self.predictor.get_input_handle(input_names[i])
  713. input_tensor.copy_from_cpu(inputs[i])
  714. self.predictor.run()
  715. outputs = []
  716. for output_tensor in self.output_tensors:
  717. output = output_tensor.copy_to_cpu()
  718. outputs.append(output)
  719. if self.benchmark:
  720. self.autolog.times.stamp()
  721. preds = outputs[0]
  722. elif self.rec_algorithm == "CAN":
  723. norm_img_mask_batch = np.concatenate(norm_img_mask_batch)
  724. word_label_list = np.concatenate(word_label_list)
  725. inputs = [norm_img_batch, norm_img_mask_batch, word_label_list]
  726. if self.use_onnx:
  727. input_dict = {}
  728. input_dict[self.input_tensor.name] = norm_img_batch
  729. outputs = self.predictor.run(self.output_tensors, input_dict)
  730. preds = outputs
  731. else:
  732. input_names = self.predictor.get_input_names()
  733. input_tensor = []
  734. for i in range(len(input_names)):
  735. input_tensor_i = self.predictor.get_input_handle(input_names[i])
  736. input_tensor_i.copy_from_cpu(inputs[i])
  737. input_tensor.append(input_tensor_i)
  738. self.input_tensor = input_tensor
  739. self.predictor.run()
  740. outputs = []
  741. for output_tensor in self.output_tensors:
  742. output = output_tensor.copy_to_cpu()
  743. outputs.append(output)
  744. if self.benchmark:
  745. self.autolog.times.stamp()
  746. preds = outputs
  747. elif self.rec_algorithm == "LaTeXOCR":
  748. inputs = [norm_img_batch]
  749. if self.use_onnx:
  750. input_dict = {}
  751. input_dict[self.input_tensor.name] = norm_img_batch
  752. outputs = self.predictor.run(self.output_tensors, input_dict)
  753. preds = outputs
  754. else:
  755. input_names = self.predictor.get_input_names()
  756. input_tensor = []
  757. for i in range(len(input_names)):
  758. input_tensor_i = self.predictor.get_input_handle(input_names[i])
  759. input_tensor_i.copy_from_cpu(inputs[i])
  760. input_tensor.append(input_tensor_i)
  761. self.input_tensor = input_tensor
  762. self.predictor.run()
  763. outputs = []
  764. for output_tensor in self.output_tensors:
  765. output = output_tensor.copy_to_cpu()
  766. outputs.append(output)
  767. if self.benchmark:
  768. self.autolog.times.stamp()
  769. preds = outputs
  770. else:
  771. if self.use_onnx:
  772. input_dict = {}
  773. input_dict[self.input_tensor.name] = norm_img_batch
  774. outputs = self.predictor.run(self.output_tensors, input_dict)
  775. preds = outputs[0]
  776. else:
  777. self.input_tensor.copy_from_cpu(norm_img_batch)
  778. self.predictor.run()
  779. outputs = []
  780. for output_tensor in self.output_tensors:
  781. output = output_tensor.copy_to_cpu()
  782. outputs.append(output)
  783. if self.benchmark:
  784. self.autolog.times.stamp()
  785. if len(outputs) != 1:
  786. preds = outputs
  787. else:
  788. preds = outputs[0]
  789. if self.postprocess_params["name"] == "CTCLabelDecode":
  790. rec_result = self.postprocess_op(
  791. preds,
  792. return_word_box=self.return_word_box,
  793. wh_ratio_list=wh_ratio_list,
  794. max_wh_ratio=max_wh_ratio,
  795. )
  796. elif self.postprocess_params["name"] == "LaTeXOCRDecode":
  797. preds = [p.reshape([-1]) for p in preds]
  798. rec_result = self.postprocess_op(preds)
  799. else:
  800. rec_result = self.postprocess_op(preds)
  801. for rno in range(len(rec_result)):
  802. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  803. if self.benchmark:
  804. self.autolog.times.end(stamp=True)
  805. return rec_res, time.time() - st
  806. def main(args):
  807. image_file_list = get_image_file_list(args.image_dir)
  808. valid_image_file_list = []
  809. img_list = []
  810. # logger
  811. log_file = args.save_log_path
  812. if os.path.isdir(args.save_log_path) or (
  813. not os.path.exists(args.save_log_path) and args.save_log_path.endswith("/")
  814. ):
  815. log_file = os.path.join(log_file, "benchmark_recognition.log")
  816. logger = get_logger(log_file=log_file)
  817. # create text recognizer
  818. text_recognizer = TextRecognizer(args)
  819. logger.info(
  820. "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', "
  821. "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320"
  822. )
  823. # warmup 2 times
  824. if args.warmup:
  825. img = np.random.uniform(0, 255, [48, 320, 3]).astype(np.uint8)
  826. for i in range(2):
  827. res = text_recognizer([img] * int(args.rec_batch_num))
  828. for image_file in image_file_list:
  829. img, flag, _ = check_and_read(image_file)
  830. if not flag:
  831. img = cv2.imread(image_file)
  832. if img is None:
  833. logger.info("error in loading image:{}".format(image_file))
  834. continue
  835. valid_image_file_list.append(image_file)
  836. img_list.append(img)
  837. try:
  838. rec_res, _ = text_recognizer(img_list)
  839. except Exception as E:
  840. logger.info(traceback.format_exc())
  841. logger.info(E)
  842. exit()
  843. for ino in range(len(img_list)):
  844. logger.info(
  845. "Predicts of {}:{}".format(valid_image_file_list[ino], rec_res[ino])
  846. )
  847. if args.benchmark:
  848. text_recognizer.autolog.report()
  849. if __name__ == "__main__":
  850. main(utility.parse_args())