predict_rec.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 isinstance(w, str):
  169. pass
  170. elif w is not None and w > 0:
  171. imgW = w
  172. h, w = img.shape[:2]
  173. ratio = w / float(h)
  174. if math.ceil(imgH * ratio) > imgW:
  175. resized_w = imgW
  176. else:
  177. resized_w = int(math.ceil(imgH * ratio))
  178. if self.rec_algorithm == 'RARE':
  179. if resized_w > self.rec_image_shape[2]:
  180. resized_w = self.rec_image_shape[2]
  181. imgW = self.rec_image_shape[2]
  182. resized_image = cv2.resize(img, (resized_w, imgH))
  183. resized_image = resized_image.astype('float32')
  184. resized_image = resized_image.transpose((2, 0, 1)) / 255
  185. resized_image -= 0.5
  186. resized_image /= 0.5
  187. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  188. padding_im[:, :, 0:resized_w] = resized_image
  189. return padding_im
  190. def resize_norm_img_vl(self, img, image_shape):
  191. imgC, imgH, imgW = image_shape
  192. img = img[:, :, ::-1] # bgr2rgb
  193. resized_image = cv2.resize(
  194. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  195. resized_image = resized_image.astype('float32')
  196. resized_image = resized_image.transpose((2, 0, 1)) / 255
  197. return resized_image
  198. def resize_norm_img_srn(self, img, image_shape):
  199. imgC, imgH, imgW = image_shape
  200. img_black = np.zeros((imgH, imgW))
  201. im_hei = img.shape[0]
  202. im_wid = img.shape[1]
  203. if im_wid <= im_hei * 1:
  204. img_new = cv2.resize(img, (imgH * 1, imgH))
  205. elif im_wid <= im_hei * 2:
  206. img_new = cv2.resize(img, (imgH * 2, imgH))
  207. elif im_wid <= im_hei * 3:
  208. img_new = cv2.resize(img, (imgH * 3, imgH))
  209. else:
  210. img_new = cv2.resize(img, (imgW, imgH))
  211. img_np = np.asarray(img_new)
  212. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  213. img_black[:, 0:img_np.shape[1]] = img_np
  214. img_black = img_black[:, :, np.newaxis]
  215. row, col, c = img_black.shape
  216. c = 1
  217. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  218. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  219. imgC, imgH, imgW = image_shape
  220. feature_dim = int((imgH / 8) * (imgW / 8))
  221. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  222. (feature_dim, 1)).astype('int64')
  223. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  224. (max_text_length, 1)).astype('int64')
  225. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  226. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  227. [-1, 1, max_text_length, max_text_length])
  228. gsrm_slf_attn_bias1 = np.tile(
  229. gsrm_slf_attn_bias1,
  230. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  231. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  232. [-1, 1, max_text_length, max_text_length])
  233. gsrm_slf_attn_bias2 = np.tile(
  234. gsrm_slf_attn_bias2,
  235. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  236. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  237. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  238. return [
  239. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  240. gsrm_slf_attn_bias2
  241. ]
  242. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  243. norm_img = self.resize_norm_img_srn(img, image_shape)
  244. norm_img = norm_img[np.newaxis, :]
  245. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  246. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  247. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  248. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  249. encoder_word_pos = encoder_word_pos.astype(np.int64)
  250. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  251. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  252. gsrm_slf_attn_bias2)
  253. def resize_norm_img_sar(self, img, image_shape,
  254. width_downsample_ratio=0.25):
  255. imgC, imgH, imgW_min, imgW_max = image_shape
  256. h = img.shape[0]
  257. w = img.shape[1]
  258. valid_ratio = 1.0
  259. # make sure new_width is an integral multiple of width_divisor.
  260. width_divisor = int(1 / width_downsample_ratio)
  261. # resize
  262. ratio = w / float(h)
  263. resize_w = math.ceil(imgH * ratio)
  264. if resize_w % width_divisor != 0:
  265. resize_w = round(resize_w / width_divisor) * width_divisor
  266. if imgW_min is not None:
  267. resize_w = max(imgW_min, resize_w)
  268. if imgW_max is not None:
  269. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  270. resize_w = min(imgW_max, resize_w)
  271. resized_image = cv2.resize(img, (resize_w, imgH))
  272. resized_image = resized_image.astype('float32')
  273. # norm
  274. if image_shape[0] == 1:
  275. resized_image = resized_image / 255
  276. resized_image = resized_image[np.newaxis, :]
  277. else:
  278. resized_image = resized_image.transpose((2, 0, 1)) / 255
  279. resized_image -= 0.5
  280. resized_image /= 0.5
  281. resize_shape = resized_image.shape
  282. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  283. padding_im[:, :, 0:resize_w] = resized_image
  284. pad_shape = padding_im.shape
  285. return padding_im, resize_shape, pad_shape, valid_ratio
  286. def resize_norm_img_spin(self, img):
  287. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  288. # return padding_im
  289. img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC)
  290. img = np.array(img, np.float32)
  291. img = np.expand_dims(img, -1)
  292. img = img.transpose((2, 0, 1))
  293. mean = [127.5]
  294. std = [127.5]
  295. mean = np.array(mean, dtype=np.float32)
  296. std = np.array(std, dtype=np.float32)
  297. mean = np.float32(mean.reshape(1, -1))
  298. stdinv = 1 / np.float32(std.reshape(1, -1))
  299. img -= mean
  300. img *= stdinv
  301. return img
  302. def resize_norm_img_svtr(self, img, image_shape):
  303. imgC, imgH, imgW = image_shape
  304. resized_image = cv2.resize(
  305. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  306. resized_image = resized_image.astype('float32')
  307. resized_image = resized_image.transpose((2, 0, 1)) / 255
  308. resized_image -= 0.5
  309. resized_image /= 0.5
  310. return resized_image
  311. def resize_norm_img_abinet(self, img, image_shape):
  312. imgC, imgH, imgW = image_shape
  313. resized_image = cv2.resize(
  314. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  315. resized_image = resized_image.astype('float32')
  316. resized_image = resized_image / 255.
  317. mean = np.array([0.485, 0.456, 0.406])
  318. std = np.array([0.229, 0.224, 0.225])
  319. resized_image = (
  320. resized_image - mean[None, None, ...]) / std[None, None, ...]
  321. resized_image = resized_image.transpose((2, 0, 1))
  322. resized_image = resized_image.astype('float32')
  323. return resized_image
  324. def norm_img_can(self, img, image_shape):
  325. img = cv2.cvtColor(
  326. img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image
  327. if self.inverse:
  328. img = 255 - img
  329. if self.rec_image_shape[0] == 1:
  330. h, w = img.shape
  331. _, imgH, imgW = self.rec_image_shape
  332. if h < imgH or w < imgW:
  333. padding_h = max(imgH - h, 0)
  334. padding_w = max(imgW - w, 0)
  335. img_padded = np.pad(img, ((0, padding_h), (0, padding_w)),
  336. 'constant',
  337. constant_values=(255))
  338. img = img_padded
  339. img = np.expand_dims(img, 0) / 255.0 # h,w,c -> c,h,w
  340. img = img.astype('float32')
  341. return img
  342. def __call__(self, img_list):
  343. img_num = len(img_list)
  344. # Calculate the aspect ratio of all text bars
  345. width_list = []
  346. for img in img_list:
  347. width_list.append(img.shape[1] / float(img.shape[0]))
  348. # Sorting can speed up the recognition process
  349. indices = np.argsort(np.array(width_list))
  350. rec_res = [['', 0.0]] * img_num
  351. batch_num = self.rec_batch_num
  352. st = time.time()
  353. if self.benchmark:
  354. self.autolog.times.start()
  355. for beg_img_no in range(0, img_num, batch_num):
  356. end_img_no = min(img_num, beg_img_no + batch_num)
  357. norm_img_batch = []
  358. if self.rec_algorithm == "SRN":
  359. encoder_word_pos_list = []
  360. gsrm_word_pos_list = []
  361. gsrm_slf_attn_bias1_list = []
  362. gsrm_slf_attn_bias2_list = []
  363. if self.rec_algorithm == "SAR":
  364. valid_ratios = []
  365. imgC, imgH, imgW = self.rec_image_shape[:3]
  366. max_wh_ratio = imgW / imgH
  367. # max_wh_ratio = 0
  368. for ino in range(beg_img_no, end_img_no):
  369. h, w = img_list[indices[ino]].shape[0:2]
  370. wh_ratio = w * 1.0 / h
  371. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  372. for ino in range(beg_img_no, end_img_no):
  373. if self.rec_algorithm == "SAR":
  374. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  375. img_list[indices[ino]], self.rec_image_shape)
  376. norm_img = norm_img[np.newaxis, :]
  377. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  378. valid_ratios.append(valid_ratio)
  379. norm_img_batch.append(norm_img)
  380. elif self.rec_algorithm == "SRN":
  381. norm_img = self.process_image_srn(
  382. img_list[indices[ino]], self.rec_image_shape, 8, 25)
  383. encoder_word_pos_list.append(norm_img[1])
  384. gsrm_word_pos_list.append(norm_img[2])
  385. gsrm_slf_attn_bias1_list.append(norm_img[3])
  386. gsrm_slf_attn_bias2_list.append(norm_img[4])
  387. norm_img_batch.append(norm_img[0])
  388. elif self.rec_algorithm == "SVTR":
  389. norm_img = self.resize_norm_img_svtr(img_list[indices[ino]],
  390. self.rec_image_shape)
  391. norm_img = norm_img[np.newaxis, :]
  392. norm_img_batch.append(norm_img)
  393. elif self.rec_algorithm in ["VisionLAN", "PREN"]:
  394. norm_img = self.resize_norm_img_vl(img_list[indices[ino]],
  395. self.rec_image_shape)
  396. norm_img = norm_img[np.newaxis, :]
  397. norm_img_batch.append(norm_img)
  398. elif self.rec_algorithm == 'SPIN':
  399. norm_img = self.resize_norm_img_spin(img_list[indices[ino]])
  400. norm_img = norm_img[np.newaxis, :]
  401. norm_img_batch.append(norm_img)
  402. elif self.rec_algorithm == "ABINet":
  403. norm_img = self.resize_norm_img_abinet(
  404. img_list[indices[ino]], self.rec_image_shape)
  405. norm_img = norm_img[np.newaxis, :]
  406. norm_img_batch.append(norm_img)
  407. elif self.rec_algorithm == "RobustScanner":
  408. norm_img, _, _, valid_ratio = self.resize_norm_img_sar(
  409. img_list[indices[ino]],
  410. self.rec_image_shape,
  411. width_downsample_ratio=0.25)
  412. norm_img = norm_img[np.newaxis, :]
  413. valid_ratio = np.expand_dims(valid_ratio, axis=0)
  414. valid_ratios = []
  415. valid_ratios.append(valid_ratio)
  416. norm_img_batch.append(norm_img)
  417. word_positions_list = []
  418. word_positions = np.array(range(0, 40)).astype('int64')
  419. word_positions = np.expand_dims(word_positions, axis=0)
  420. word_positions_list.append(word_positions)
  421. elif self.rec_algorithm == "CAN":
  422. norm_img = self.norm_img_can(img_list[indices[ino]],
  423. max_wh_ratio)
  424. norm_img = norm_img[np.newaxis, :]
  425. norm_img_batch.append(norm_img)
  426. norm_image_mask = np.ones(norm_img.shape, dtype='float32')
  427. word_label = np.ones([1, 36], dtype='int64')
  428. norm_img_mask_batch = []
  429. word_label_list = []
  430. norm_img_mask_batch.append(norm_image_mask)
  431. word_label_list.append(word_label)
  432. else:
  433. norm_img = self.resize_norm_img(img_list[indices[ino]],
  434. max_wh_ratio)
  435. norm_img = norm_img[np.newaxis, :]
  436. norm_img_batch.append(norm_img)
  437. norm_img_batch = np.concatenate(norm_img_batch)
  438. norm_img_batch = norm_img_batch.copy()
  439. if self.benchmark:
  440. self.autolog.times.stamp()
  441. if self.rec_algorithm == "SRN":
  442. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  443. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  444. gsrm_slf_attn_bias1_list = np.concatenate(
  445. gsrm_slf_attn_bias1_list)
  446. gsrm_slf_attn_bias2_list = np.concatenate(
  447. gsrm_slf_attn_bias2_list)
  448. inputs = [
  449. norm_img_batch,
  450. encoder_word_pos_list,
  451. gsrm_word_pos_list,
  452. gsrm_slf_attn_bias1_list,
  453. gsrm_slf_attn_bias2_list,
  454. ]
  455. if self.use_onnx:
  456. input_dict = {}
  457. input_dict[self.input_tensor.name] = norm_img_batch
  458. outputs = self.predictor.run(self.output_tensors,
  459. input_dict)
  460. preds = {"predict": outputs[2]}
  461. else:
  462. input_names = self.predictor.get_input_names()
  463. for i in range(len(input_names)):
  464. input_tensor = self.predictor.get_input_handle(
  465. input_names[i])
  466. input_tensor.copy_from_cpu(inputs[i])
  467. self.predictor.run()
  468. outputs = []
  469. for output_tensor in self.output_tensors:
  470. output = output_tensor.copy_to_cpu()
  471. outputs.append(output)
  472. if self.benchmark:
  473. self.autolog.times.stamp()
  474. preds = {"predict": outputs[2]}
  475. elif self.rec_algorithm == "SAR":
  476. valid_ratios = np.concatenate(valid_ratios)
  477. inputs = [
  478. norm_img_batch,
  479. np.array(
  480. [valid_ratios], dtype=np.float32),
  481. ]
  482. if self.use_onnx:
  483. input_dict = {}
  484. input_dict[self.input_tensor.name] = norm_img_batch
  485. outputs = self.predictor.run(self.output_tensors,
  486. input_dict)
  487. preds = outputs[0]
  488. else:
  489. input_names = self.predictor.get_input_names()
  490. for i in range(len(input_names)):
  491. input_tensor = self.predictor.get_input_handle(
  492. input_names[i])
  493. input_tensor.copy_from_cpu(inputs[i])
  494. self.predictor.run()
  495. outputs = []
  496. for output_tensor in self.output_tensors:
  497. output = output_tensor.copy_to_cpu()
  498. outputs.append(output)
  499. if self.benchmark:
  500. self.autolog.times.stamp()
  501. preds = outputs[0]
  502. elif self.rec_algorithm == "RobustScanner":
  503. valid_ratios = np.concatenate(valid_ratios)
  504. word_positions_list = np.concatenate(word_positions_list)
  505. inputs = [norm_img_batch, valid_ratios, word_positions_list]
  506. if self.use_onnx:
  507. input_dict = {}
  508. input_dict[self.input_tensor.name] = norm_img_batch
  509. outputs = self.predictor.run(self.output_tensors,
  510. input_dict)
  511. preds = outputs[0]
  512. else:
  513. input_names = self.predictor.get_input_names()
  514. for i in range(len(input_names)):
  515. input_tensor = self.predictor.get_input_handle(
  516. input_names[i])
  517. input_tensor.copy_from_cpu(inputs[i])
  518. self.predictor.run()
  519. outputs = []
  520. for output_tensor in self.output_tensors:
  521. output = output_tensor.copy_to_cpu()
  522. outputs.append(output)
  523. if self.benchmark:
  524. self.autolog.times.stamp()
  525. preds = outputs[0]
  526. elif self.rec_algorithm == "CAN":
  527. norm_img_mask_batch = np.concatenate(norm_img_mask_batch)
  528. word_label_list = np.concatenate(word_label_list)
  529. inputs = [norm_img_batch, norm_img_mask_batch, word_label_list]
  530. if self.use_onnx:
  531. input_dict = {}
  532. input_dict[self.input_tensor.name] = norm_img_batch
  533. outputs = self.predictor.run(self.output_tensors,
  534. input_dict)
  535. preds = outputs
  536. else:
  537. input_names = self.predictor.get_input_names()
  538. input_tensor = []
  539. for i in range(len(input_names)):
  540. input_tensor_i = self.predictor.get_input_handle(
  541. input_names[i])
  542. input_tensor_i.copy_from_cpu(inputs[i])
  543. input_tensor.append(input_tensor_i)
  544. self.input_tensor = input_tensor
  545. self.predictor.run()
  546. outputs = []
  547. for output_tensor in self.output_tensors:
  548. output = output_tensor.copy_to_cpu()
  549. outputs.append(output)
  550. if self.benchmark:
  551. self.autolog.times.stamp()
  552. preds = outputs
  553. else:
  554. if self.use_onnx:
  555. input_dict = {}
  556. input_dict[self.input_tensor.name] = norm_img_batch
  557. outputs = self.predictor.run(self.output_tensors,
  558. input_dict)
  559. preds = outputs[0]
  560. else:
  561. self.input_tensor.copy_from_cpu(norm_img_batch)
  562. self.predictor.run()
  563. outputs = []
  564. for output_tensor in self.output_tensors:
  565. output = output_tensor.copy_to_cpu()
  566. outputs.append(output)
  567. if self.benchmark:
  568. self.autolog.times.stamp()
  569. if len(outputs) != 1:
  570. preds = outputs
  571. else:
  572. preds = outputs[0]
  573. rec_result = self.postprocess_op(preds)
  574. for rno in range(len(rec_result)):
  575. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  576. if self.benchmark:
  577. self.autolog.times.end(stamp=True)
  578. return rec_res, time.time() - st
  579. def main(args):
  580. image_file_list = get_image_file_list(args.image_dir)
  581. text_recognizer = TextRecognizer(args)
  582. valid_image_file_list = []
  583. img_list = []
  584. logger.info(
  585. "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', "
  586. "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320"
  587. )
  588. # warmup 2 times
  589. if args.warmup:
  590. img = np.random.uniform(0, 255, [48, 320, 3]).astype(np.uint8)
  591. for i in range(2):
  592. res = text_recognizer([img] * int(args.rec_batch_num))
  593. for image_file in image_file_list:
  594. img, flag, _ = check_and_read(image_file)
  595. if not flag:
  596. img = cv2.imread(image_file)
  597. if img is None:
  598. logger.info("error in loading image:{}".format(image_file))
  599. continue
  600. valid_image_file_list.append(image_file)
  601. img_list.append(img)
  602. try:
  603. rec_res, _ = text_recognizer(img_list)
  604. except Exception as E:
  605. logger.info(traceback.format_exc())
  606. logger.info(E)
  607. exit()
  608. for ino in range(len(img_list)):
  609. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  610. rec_res[ino]))
  611. if args.benchmark:
  612. text_recognizer.autolog.report()
  613. if __name__ == "__main__":
  614. main(utility.parse_args())