predict_rec.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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):
  34. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  35. self.rec_batch_num = args.rec_batch_num
  36. self.rec_algorithm = args.rec_algorithm
  37. postprocess_params = {
  38. 'name': 'CTCLabelDecode',
  39. "character_dict_path": args.rec_char_dict_path,
  40. "use_space_char": args.use_space_char
  41. }
  42. if self.rec_algorithm == "SRN":
  43. postprocess_params = {
  44. 'name': 'SRNLabelDecode',
  45. "character_dict_path": args.rec_char_dict_path,
  46. "use_space_char": args.use_space_char
  47. }
  48. elif self.rec_algorithm == "RARE":
  49. postprocess_params = {
  50. 'name': 'AttnLabelDecode',
  51. "character_dict_path": args.rec_char_dict_path,
  52. "use_space_char": args.use_space_char
  53. }
  54. elif self.rec_algorithm == 'NRTR':
  55. postprocess_params = {
  56. 'name': 'NRTRLabelDecode',
  57. "character_dict_path": args.rec_char_dict_path,
  58. "use_space_char": args.use_space_char
  59. }
  60. elif self.rec_algorithm == "SAR":
  61. postprocess_params = {
  62. 'name': 'SARLabelDecode',
  63. "character_dict_path": args.rec_char_dict_path,
  64. "use_space_char": args.use_space_char
  65. }
  66. elif self.rec_algorithm == "VisionLAN":
  67. postprocess_params = {
  68. 'name': 'VLLabelDecode',
  69. "character_dict_path": args.rec_char_dict_path,
  70. "use_space_char": args.use_space_char
  71. }
  72. elif self.rec_algorithm == 'ViTSTR':
  73. postprocess_params = {
  74. 'name': 'ViTSTRLabelDecode',
  75. "character_dict_path": args.rec_char_dict_path,
  76. "use_space_char": args.use_space_char
  77. }
  78. elif self.rec_algorithm == 'ABINet':
  79. postprocess_params = {
  80. 'name': 'ABINetLabelDecode',
  81. "character_dict_path": args.rec_char_dict_path,
  82. "use_space_char": args.use_space_char
  83. }
  84. elif self.rec_algorithm == "SPIN":
  85. postprocess_params = {
  86. 'name': 'SPINLabelDecode',
  87. "character_dict_path": args.rec_char_dict_path,
  88. "use_space_char": args.use_space_char
  89. }
  90. elif self.rec_algorithm == "RobustScanner":
  91. postprocess_params = {
  92. 'name': 'SARLabelDecode',
  93. "character_dict_path": args.rec_char_dict_path,
  94. "use_space_char": args.use_space_char,
  95. "rm_symbol": True
  96. }
  97. elif self.rec_algorithm == 'RFL':
  98. postprocess_params = {
  99. 'name': 'RFLLabelDecode',
  100. "character_dict_path": None,
  101. "use_space_char": args.use_space_char
  102. }
  103. elif self.rec_algorithm == "PREN":
  104. postprocess_params = {'name': 'PRENLabelDecode'}
  105. elif self.rec_algorithm == "CAN":
  106. self.inverse = args.rec_image_inverse
  107. postprocess_params = {
  108. 'name': 'CANLabelDecode',
  109. "character_dict_path": args.rec_char_dict_path,
  110. "use_space_char": args.use_space_char
  111. }
  112. self.postprocess_op = build_post_process(postprocess_params)
  113. self.predictor, self.input_tensor, self.output_tensors, self.config = \
  114. utility.create_predictor(args, 'rec', logger)
  115. self.benchmark = args.benchmark
  116. self.use_onnx = args.use_onnx
  117. if args.benchmark:
  118. import auto_log
  119. pid = os.getpid()
  120. gpu_id = utility.get_infer_gpuid()
  121. self.autolog = auto_log.AutoLogger(
  122. model_name="rec",
  123. model_precision=args.precision,
  124. batch_size=args.rec_batch_num,
  125. data_shape="dynamic",
  126. save_path=None, #args.save_log_path,
  127. inference_config=self.config,
  128. pids=pid,
  129. process_name=None,
  130. gpu_ids=gpu_id if args.use_gpu else None,
  131. time_keys=[
  132. 'preprocess_time', 'inference_time', 'postprocess_time'
  133. ],
  134. warmup=0,
  135. logger=logger)
  136. def resize_norm_img(self, img, max_wh_ratio):
  137. imgC, imgH, imgW = self.rec_image_shape
  138. if self.rec_algorithm == 'NRTR' or self.rec_algorithm == 'ViTSTR':
  139. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  140. # return padding_im
  141. image_pil = Image.fromarray(np.uint8(img))
  142. if self.rec_algorithm == 'ViTSTR':
  143. img = image_pil.resize([imgW, imgH], Image.BICUBIC)
  144. else:
  145. img = image_pil.resize([imgW, imgH], Image.ANTIALIAS)
  146. img = np.array(img)
  147. norm_img = np.expand_dims(img, -1)
  148. norm_img = norm_img.transpose((2, 0, 1))
  149. if self.rec_algorithm == 'ViTSTR':
  150. norm_img = norm_img.astype(np.float32) / 255.
  151. else:
  152. norm_img = norm_img.astype(np.float32) / 128. - 1.
  153. return norm_img
  154. elif self.rec_algorithm == 'RFL':
  155. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  156. resized_image = cv2.resize(
  157. img, (imgW, imgH), interpolation=cv2.INTER_CUBIC)
  158. resized_image = resized_image.astype('float32')
  159. resized_image = resized_image / 255
  160. resized_image = resized_image[np.newaxis, :]
  161. resized_image -= 0.5
  162. resized_image /= 0.5
  163. return resized_image
  164. assert imgC == img.shape[2]
  165. imgW = int((imgH * max_wh_ratio))
  166. if self.use_onnx:
  167. w = self.input_tensor.shape[3:][0]
  168. if w is not None and w > 0:
  169. imgW = w
  170. h, w = img.shape[:2]
  171. ratio = w / float(h)
  172. if math.ceil(imgH * ratio) > imgW:
  173. resized_w = imgW
  174. else:
  175. resized_w = int(math.ceil(imgH * ratio))
  176. if self.rec_algorithm == 'RARE':
  177. if resized_w > self.rec_image_shape[2]:
  178. resized_w = self.rec_image_shape[2]
  179. imgW = self.rec_image_shape[2]
  180. resized_image = cv2.resize(img, (resized_w, imgH))
  181. resized_image = resized_image.astype('float32')
  182. resized_image = resized_image.transpose((2, 0, 1)) / 255
  183. resized_image -= 0.5
  184. resized_image /= 0.5
  185. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  186. padding_im[:, :, 0:resized_w] = resized_image
  187. return padding_im
  188. def resize_norm_img_vl(self, img, image_shape):
  189. imgC, imgH, imgW = image_shape
  190. img = img[:, :, ::-1] # bgr2rgb
  191. resized_image = cv2.resize(
  192. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  193. resized_image = resized_image.astype('float32')
  194. resized_image = resized_image.transpose((2, 0, 1)) / 255
  195. return resized_image
  196. def resize_norm_img_srn(self, img, image_shape):
  197. imgC, imgH, imgW = image_shape
  198. img_black = np.zeros((imgH, imgW))
  199. im_hei = img.shape[0]
  200. im_wid = img.shape[1]
  201. if im_wid <= im_hei * 1:
  202. img_new = cv2.resize(img, (imgH * 1, imgH))
  203. elif im_wid <= im_hei * 2:
  204. img_new = cv2.resize(img, (imgH * 2, imgH))
  205. elif im_wid <= im_hei * 3:
  206. img_new = cv2.resize(img, (imgH * 3, imgH))
  207. else:
  208. img_new = cv2.resize(img, (imgW, imgH))
  209. img_np = np.asarray(img_new)
  210. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  211. img_black[:, 0:img_np.shape[1]] = img_np
  212. img_black = img_black[:, :, np.newaxis]
  213. row, col, c = img_black.shape
  214. c = 1
  215. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  216. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  217. imgC, imgH, imgW = image_shape
  218. feature_dim = int((imgH / 8) * (imgW / 8))
  219. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  220. (feature_dim, 1)).astype('int64')
  221. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  222. (max_text_length, 1)).astype('int64')
  223. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  224. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  225. [-1, 1, max_text_length, max_text_length])
  226. gsrm_slf_attn_bias1 = np.tile(
  227. gsrm_slf_attn_bias1,
  228. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  229. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  230. [-1, 1, max_text_length, max_text_length])
  231. gsrm_slf_attn_bias2 = np.tile(
  232. gsrm_slf_attn_bias2,
  233. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  234. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  235. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  236. return [
  237. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  238. gsrm_slf_attn_bias2
  239. ]
  240. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  241. norm_img = self.resize_norm_img_srn(img, image_shape)
  242. norm_img = norm_img[np.newaxis, :]
  243. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  244. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  245. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  246. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  247. encoder_word_pos = encoder_word_pos.astype(np.int64)
  248. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  249. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  250. gsrm_slf_attn_bias2)
  251. def resize_norm_img_sar(self, img, image_shape,
  252. width_downsample_ratio=0.25):
  253. imgC, imgH, imgW_min, imgW_max = image_shape
  254. h = img.shape[0]
  255. w = img.shape[1]
  256. valid_ratio = 1.0
  257. # make sure new_width is an integral multiple of width_divisor.
  258. width_divisor = int(1 / width_downsample_ratio)
  259. # resize
  260. ratio = w / float(h)
  261. resize_w = math.ceil(imgH * ratio)
  262. if resize_w % width_divisor != 0:
  263. resize_w = round(resize_w / width_divisor) * width_divisor
  264. if imgW_min is not None:
  265. resize_w = max(imgW_min, resize_w)
  266. if imgW_max is not None:
  267. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  268. resize_w = min(imgW_max, resize_w)
  269. resized_image = cv2.resize(img, (resize_w, imgH))
  270. resized_image = resized_image.astype('float32')
  271. # norm
  272. if image_shape[0] == 1:
  273. resized_image = resized_image / 255
  274. resized_image = resized_image[np.newaxis, :]
  275. else:
  276. resized_image = resized_image.transpose((2, 0, 1)) / 255
  277. resized_image -= 0.5
  278. resized_image /= 0.5
  279. resize_shape = resized_image.shape
  280. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  281. padding_im[:, :, 0:resize_w] = resized_image
  282. pad_shape = padding_im.shape
  283. return padding_im, resize_shape, pad_shape, valid_ratio
  284. def resize_norm_img_spin(self, img):
  285. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  286. # return padding_im
  287. img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC)
  288. img = np.array(img, np.float32)
  289. img = np.expand_dims(img, -1)
  290. img = img.transpose((2, 0, 1))
  291. mean = [127.5]
  292. std = [127.5]
  293. mean = np.array(mean, dtype=np.float32)
  294. std = np.array(std, dtype=np.float32)
  295. mean = np.float32(mean.reshape(1, -1))
  296. stdinv = 1 / np.float32(std.reshape(1, -1))
  297. img -= mean
  298. img *= stdinv
  299. return img
  300. def resize_norm_img_svtr(self, img, image_shape):
  301. imgC, imgH, imgW = image_shape
  302. resized_image = cv2.resize(
  303. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  304. resized_image = resized_image.astype('float32')
  305. resized_image = resized_image.transpose((2, 0, 1)) / 255
  306. resized_image -= 0.5
  307. resized_image /= 0.5
  308. return resized_image
  309. def resize_norm_img_abinet(self, img, image_shape):
  310. imgC, imgH, imgW = image_shape
  311. resized_image = cv2.resize(
  312. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  313. resized_image = resized_image.astype('float32')
  314. resized_image = resized_image / 255.
  315. mean = np.array([0.485, 0.456, 0.406])
  316. std = np.array([0.229, 0.224, 0.225])
  317. resized_image = (
  318. resized_image - mean[None, None, ...]) / std[None, None, ...]
  319. resized_image = resized_image.transpose((2, 0, 1))
  320. resized_image = resized_image.astype('float32')
  321. return resized_image
  322. def norm_img_can(self, img, image_shape):
  323. img = cv2.cvtColor(
  324. img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image
  325. if self.inverse:
  326. img = 255 - img
  327. if self.rec_image_shape[0] == 1:
  328. h, w = img.shape
  329. _, imgH, imgW = self.rec_image_shape
  330. if h < imgH or w < imgW:
  331. padding_h = max(imgH - h, 0)
  332. padding_w = max(imgW - w, 0)
  333. img_padded = np.pad(img, ((0, padding_h), (0, padding_w)),
  334. 'constant',
  335. constant_values=(255))
  336. img = img_padded
  337. img = np.expand_dims(img, 0) / 255.0 # h,w,c -> c,h,w
  338. img = img.astype('float32')
  339. return img
  340. def __call__(self, img_list):
  341. img_num = len(img_list)
  342. # Calculate the aspect ratio of all text bars
  343. width_list = []
  344. for img in img_list:
  345. width_list.append(img.shape[1] / float(img.shape[0]))
  346. # Sorting can speed up the recognition process
  347. indices = np.argsort(np.array(width_list))
  348. rec_res = [['', 0.0]] * img_num
  349. batch_num = self.rec_batch_num
  350. st = time.time()
  351. if self.benchmark:
  352. self.autolog.times.start()
  353. for beg_img_no in range(0, img_num, batch_num):
  354. end_img_no = min(img_num, beg_img_no + batch_num)
  355. norm_img_batch = []
  356. if self.rec_algorithm == "SRN":
  357. encoder_word_pos_list = []
  358. gsrm_word_pos_list = []
  359. gsrm_slf_attn_bias1_list = []
  360. gsrm_slf_attn_bias2_list = []
  361. if self.rec_algorithm == "SAR":
  362. valid_ratios = []
  363. imgC, imgH, imgW = self.rec_image_shape[:3]
  364. max_wh_ratio = imgW / imgH
  365. # max_wh_ratio = 0
  366. for ino in range(beg_img_no, end_img_no):
  367. h, w = img_list[indices[ino]].shape[0:2]
  368. wh_ratio = w * 1.0 / h
  369. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  370. for ino in range(beg_img_no, end_img_no):
  371. if self.rec_algorithm == "SAR":
  372. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  373. img_list[indices[ino]], self.rec_image_shape)
  374. norm_img = norm_img[np.newaxis, :]
  375. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  376. valid_ratios.append(valid_ratio)
  377. norm_img_batch.append(norm_img)
  378. elif self.rec_algorithm == "SRN":
  379. norm_img = self.process_image_srn(
  380. img_list[indices[ino]], self.rec_image_shape, 8, 25)
  381. encoder_word_pos_list.append(norm_img[1])
  382. gsrm_word_pos_list.append(norm_img[2])
  383. gsrm_slf_attn_bias1_list.append(norm_img[3])
  384. gsrm_slf_attn_bias2_list.append(norm_img[4])
  385. norm_img_batch.append(norm_img[0])
  386. elif self.rec_algorithm == "SVTR":
  387. norm_img = self.resize_norm_img_svtr(img_list[indices[ino]],
  388. self.rec_image_shape)
  389. norm_img = norm_img[np.newaxis, :]
  390. norm_img_batch.append(norm_img)
  391. elif self.rec_algorithm in ["VisionLAN", "PREN"]:
  392. norm_img = self.resize_norm_img_vl(img_list[indices[ino]],
  393. self.rec_image_shape)
  394. norm_img = norm_img[np.newaxis, :]
  395. norm_img_batch.append(norm_img)
  396. elif self.rec_algorithm == 'SPIN':
  397. norm_img = self.resize_norm_img_spin(img_list[indices[ino]])
  398. norm_img = norm_img[np.newaxis, :]
  399. norm_img_batch.append(norm_img)
  400. elif self.rec_algorithm == "ABINet":
  401. norm_img = self.resize_norm_img_abinet(
  402. img_list[indices[ino]], self.rec_image_shape)
  403. norm_img = norm_img[np.newaxis, :]
  404. norm_img_batch.append(norm_img)
  405. elif self.rec_algorithm == "RobustScanner":
  406. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  407. img_list[indices[ino]],
  408. self.rec_image_shape,
  409. width_downsample_ratio=0.25)
  410. norm_img = norm_img[np.newaxis, :]
  411. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  412. valid_ratios = []
  413. valid_ratios.append(valid_ratio)
  414. norm_img_batch.append(norm_img)
  415. word_positions_list = []
  416. word_positions = np.array(range(0, 40)).astype('int64')
  417. word_positions = np.expand_dims(word_positions, axis=0)
  418. word_positions_list.append(word_positions)
  419. elif self.rec_algorithm == "CAN":
  420. norm_img = self.norm_img_can(img_list[indices[ino]],
  421. max_wh_ratio)
  422. norm_img = norm_img[np.newaxis, :]
  423. norm_img_batch.append(norm_img)
  424. norm_image_mask = np.ones(norm_img.shape, dtype='float32')
  425. word_label = np.ones([1, 36], dtype='int64')
  426. norm_img_mask_batch = []
  427. word_label_list = []
  428. norm_img_mask_batch.append(norm_image_mask)
  429. word_label_list.append(word_label)
  430. else:
  431. norm_img = self.resize_norm_img(img_list[indices[ino]],
  432. max_wh_ratio)
  433. norm_img = norm_img[np.newaxis, :]
  434. norm_img_batch.append(norm_img)
  435. norm_img_batch = np.concatenate(norm_img_batch)
  436. norm_img_batch = norm_img_batch.copy()
  437. if self.benchmark:
  438. self.autolog.times.stamp()
  439. if self.rec_algorithm == "SRN":
  440. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  441. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  442. gsrm_slf_attn_bias1_list = np.concatenate(
  443. gsrm_slf_attn_bias1_list)
  444. gsrm_slf_attn_bias2_list = np.concatenate(
  445. gsrm_slf_attn_bias2_list)
  446. inputs = [
  447. norm_img_batch,
  448. encoder_word_pos_list,
  449. gsrm_word_pos_list,
  450. gsrm_slf_attn_bias1_list,
  451. gsrm_slf_attn_bias2_list,
  452. ]
  453. if self.use_onnx:
  454. input_dict = {}
  455. input_dict[self.input_tensor.name] = norm_img_batch
  456. outputs = self.predictor.run(self.output_tensors,
  457. input_dict)
  458. preds = {"predict": outputs[2]}
  459. else:
  460. input_names = self.predictor.get_input_names()
  461. for i in range(len(input_names)):
  462. input_tensor = self.predictor.get_input_handle(
  463. input_names[i])
  464. input_tensor.copy_from_cpu(inputs[i])
  465. self.predictor.run()
  466. outputs = []
  467. for output_tensor in self.output_tensors:
  468. output = output_tensor.copy_to_cpu()
  469. outputs.append(output)
  470. if self.benchmark:
  471. self.autolog.times.stamp()
  472. preds = {"predict": outputs[2]}
  473. elif self.rec_algorithm == "SAR":
  474. valid_ratios = np.concatenate(valid_ratios)
  475. inputs = [
  476. norm_img_batch,
  477. np.array(
  478. [valid_ratios], dtype=np.float32),
  479. ]
  480. if self.use_onnx:
  481. input_dict = {}
  482. input_dict[self.input_tensor.name] = norm_img_batch
  483. outputs = self.predictor.run(self.output_tensors,
  484. input_dict)
  485. preds = outputs[0]
  486. else:
  487. input_names = self.predictor.get_input_names()
  488. for i in range(len(input_names)):
  489. input_tensor = self.predictor.get_input_handle(
  490. input_names[i])
  491. input_tensor.copy_from_cpu(inputs[i])
  492. self.predictor.run()
  493. outputs = []
  494. for output_tensor in self.output_tensors:
  495. output = output_tensor.copy_to_cpu()
  496. outputs.append(output)
  497. if self.benchmark:
  498. self.autolog.times.stamp()
  499. preds = outputs[0]
  500. elif self.rec_algorithm == "RobustScanner":
  501. valid_ratios = np.concatenate(valid_ratios)
  502. word_positions_list = np.concatenate(word_positions_list)
  503. inputs = [norm_img_batch, valid_ratios, word_positions_list]
  504. if self.use_onnx:
  505. input_dict = {}
  506. input_dict[self.input_tensor.name] = norm_img_batch
  507. outputs = self.predictor.run(self.output_tensors,
  508. input_dict)
  509. preds = outputs[0]
  510. else:
  511. input_names = self.predictor.get_input_names()
  512. for i in range(len(input_names)):
  513. input_tensor = self.predictor.get_input_handle(
  514. input_names[i])
  515. input_tensor.copy_from_cpu(inputs[i])
  516. self.predictor.run()
  517. outputs = []
  518. for output_tensor in self.output_tensors:
  519. output = output_tensor.copy_to_cpu()
  520. outputs.append(output)
  521. if self.benchmark:
  522. self.autolog.times.stamp()
  523. preds = outputs[0]
  524. elif self.rec_algorithm == "CAN":
  525. norm_img_mask_batch = np.concatenate(norm_img_mask_batch)
  526. word_label_list = np.concatenate(word_label_list)
  527. inputs = [norm_img_batch, norm_img_mask_batch, word_label_list]
  528. if self.use_onnx:
  529. input_dict = {}
  530. input_dict[self.input_tensor.name] = norm_img_batch
  531. outputs = self.predictor.run(self.output_tensors,
  532. input_dict)
  533. preds = outputs
  534. else:
  535. input_names = self.predictor.get_input_names()
  536. input_tensor = []
  537. for i in range(len(input_names)):
  538. input_tensor_i = self.predictor.get_input_handle(
  539. input_names[i])
  540. input_tensor_i.copy_from_cpu(inputs[i])
  541. input_tensor.append(input_tensor_i)
  542. self.input_tensor = input_tensor
  543. self.predictor.run()
  544. outputs = []
  545. for output_tensor in self.output_tensors:
  546. output = output_tensor.copy_to_cpu()
  547. outputs.append(output)
  548. if self.benchmark:
  549. self.autolog.times.stamp()
  550. preds = outputs
  551. else:
  552. if self.use_onnx:
  553. input_dict = {}
  554. input_dict[self.input_tensor.name] = norm_img_batch
  555. outputs = self.predictor.run(self.output_tensors,
  556. input_dict)
  557. preds = outputs[0]
  558. else:
  559. self.input_tensor.copy_from_cpu(norm_img_batch)
  560. self.predictor.run()
  561. outputs = []
  562. for output_tensor in self.output_tensors:
  563. output = output_tensor.copy_to_cpu()
  564. outputs.append(output)
  565. if self.benchmark:
  566. self.autolog.times.stamp()
  567. if len(outputs) != 1:
  568. preds = outputs
  569. else:
  570. preds = outputs[0]
  571. rec_result = self.postprocess_op(preds)
  572. for rno in range(len(rec_result)):
  573. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  574. if self.benchmark:
  575. self.autolog.times.end(stamp=True)
  576. return rec_res, time.time() - st
  577. def main(args):
  578. image_file_list = get_image_file_list(args.image_dir)
  579. text_recognizer = TextRecognizer(args)
  580. valid_image_file_list = []
  581. img_list = []
  582. logger.info(
  583. "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', "
  584. "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320"
  585. )
  586. # warmup 2 times
  587. if args.warmup:
  588. img = np.random.uniform(0, 255, [48, 320, 3]).astype(np.uint8)
  589. for i in range(2):
  590. res = text_recognizer([img] * int(args.rec_batch_num))
  591. for image_file in image_file_list:
  592. img, flag, _ = check_and_read(image_file)
  593. if not flag:
  594. img = cv2.imread(image_file)
  595. if img is None:
  596. logger.info("error in loading image:{}".format(image_file))
  597. continue
  598. valid_image_file_list.append(image_file)
  599. img_list.append(img)
  600. try:
  601. rec_res, _ = text_recognizer(img_list)
  602. except Exception as E:
  603. logger.info(traceback.format_exc())
  604. logger.info(E)
  605. exit()
  606. for ino in range(len(img_list)):
  607. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  608. rec_res[ino]))
  609. if args.benchmark:
  610. text_recognizer.autolog.report()
  611. if __name__ == "__main__":
  612. main(utility.parse_args())