You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import copy
  17. import time
  18. import os
  19. from huggingface_hub import snapshot_download
  20. from api.utils.file_utils import get_project_base_directory
  21. from .operators import * # noqa: F403
  22. from . import operators
  23. import math
  24. import numpy as np
  25. import cv2
  26. import onnxruntime as ort
  27. from .postprocess import build_post_process
  28. def transform(data, ops=None):
  29. """ transform """
  30. if ops is None:
  31. ops = []
  32. for op in ops:
  33. data = op(data)
  34. if data is None:
  35. return None
  36. return data
  37. def create_operators(op_param_list, global_config=None):
  38. """
  39. create operators based on the config
  40. Args:
  41. params(list): a dict list, used to create some operators
  42. """
  43. assert isinstance(
  44. op_param_list, list), ('operator config should be a list')
  45. ops = []
  46. for operator in op_param_list:
  47. assert isinstance(operator,
  48. dict) and len(operator) == 1, "yaml format error"
  49. op_name = list(operator)[0]
  50. param = {} if operator[op_name] is None else operator[op_name]
  51. if global_config is not None:
  52. param.update(global_config)
  53. op = getattr(operators, op_name)(**param)
  54. ops.append(op)
  55. return ops
  56. def load_model(model_dir, nm):
  57. model_file_path = os.path.join(model_dir, nm + ".onnx")
  58. if not os.path.exists(model_file_path):
  59. raise ValueError("not find model file path {}".format(
  60. model_file_path))
  61. options = ort.SessionOptions()
  62. options.enable_cpu_mem_arena = False
  63. options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
  64. options.intra_op_num_threads = 2
  65. options.inter_op_num_threads = 2
  66. if False and ort.get_device() == "GPU":
  67. sess = ort.InferenceSession(
  68. model_file_path,
  69. options=options,
  70. providers=['CUDAExecutionProvider'])
  71. else:
  72. sess = ort.InferenceSession(
  73. model_file_path,
  74. options=options,
  75. providers=['CPUExecutionProvider'])
  76. return sess, sess.get_inputs()[0]
  77. class TextRecognizer(object):
  78. def __init__(self, model_dir):
  79. self.rec_image_shape = [int(v) for v in "3, 48, 320".split(",")]
  80. self.rec_batch_num = 16
  81. postprocess_params = {
  82. 'name': 'CTCLabelDecode',
  83. "character_dict_path": os.path.join(model_dir, "ocr.res"),
  84. "use_space_char": True
  85. }
  86. self.postprocess_op = build_post_process(postprocess_params)
  87. self.predictor, self.input_tensor = load_model(model_dir, 'rec')
  88. def resize_norm_img(self, img, max_wh_ratio):
  89. imgC, imgH, imgW = self.rec_image_shape
  90. assert imgC == img.shape[2]
  91. imgW = int((imgH * max_wh_ratio))
  92. w = self.input_tensor.shape[3:][0]
  93. if isinstance(w, str):
  94. pass
  95. elif w is not None and w > 0:
  96. imgW = w
  97. h, w = img.shape[:2]
  98. ratio = w / float(h)
  99. if math.ceil(imgH * ratio) > imgW:
  100. resized_w = imgW
  101. else:
  102. resized_w = int(math.ceil(imgH * ratio))
  103. resized_image = cv2.resize(img, (resized_w, imgH))
  104. resized_image = resized_image.astype('float32')
  105. resized_image = resized_image.transpose((2, 0, 1)) / 255
  106. resized_image -= 0.5
  107. resized_image /= 0.5
  108. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  109. padding_im[:, :, 0:resized_w] = resized_image
  110. return padding_im
  111. def resize_norm_img_vl(self, img, image_shape):
  112. imgC, imgH, imgW = image_shape
  113. img = img[:, :, ::-1] # bgr2rgb
  114. resized_image = cv2.resize(
  115. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  116. resized_image = resized_image.astype('float32')
  117. resized_image = resized_image.transpose((2, 0, 1)) / 255
  118. return resized_image
  119. def resize_norm_img_srn(self, img, image_shape):
  120. imgC, imgH, imgW = image_shape
  121. img_black = np.zeros((imgH, imgW))
  122. im_hei = img.shape[0]
  123. im_wid = img.shape[1]
  124. if im_wid <= im_hei * 1:
  125. img_new = cv2.resize(img, (imgH * 1, imgH))
  126. elif im_wid <= im_hei * 2:
  127. img_new = cv2.resize(img, (imgH * 2, imgH))
  128. elif im_wid <= im_hei * 3:
  129. img_new = cv2.resize(img, (imgH * 3, imgH))
  130. else:
  131. img_new = cv2.resize(img, (imgW, imgH))
  132. img_np = np.asarray(img_new)
  133. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  134. img_black[:, 0:img_np.shape[1]] = img_np
  135. img_black = img_black[:, :, np.newaxis]
  136. row, col, c = img_black.shape
  137. c = 1
  138. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  139. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  140. imgC, imgH, imgW = image_shape
  141. feature_dim = int((imgH / 8) * (imgW / 8))
  142. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  143. (feature_dim, 1)).astype('int64')
  144. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  145. (max_text_length, 1)).astype('int64')
  146. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  147. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  148. [-1, 1, max_text_length, max_text_length])
  149. gsrm_slf_attn_bias1 = np.tile(
  150. gsrm_slf_attn_bias1,
  151. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  152. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  153. [-1, 1, max_text_length, max_text_length])
  154. gsrm_slf_attn_bias2 = np.tile(
  155. gsrm_slf_attn_bias2,
  156. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  157. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  158. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  159. return [
  160. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  161. gsrm_slf_attn_bias2
  162. ]
  163. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  164. norm_img = self.resize_norm_img_srn(img, image_shape)
  165. norm_img = norm_img[np.newaxis, :]
  166. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  167. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  168. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  169. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  170. encoder_word_pos = encoder_word_pos.astype(np.int64)
  171. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  172. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  173. gsrm_slf_attn_bias2)
  174. def resize_norm_img_sar(self, img, image_shape,
  175. width_downsample_ratio=0.25):
  176. imgC, imgH, imgW_min, imgW_max = image_shape
  177. h = img.shape[0]
  178. w = img.shape[1]
  179. valid_ratio = 1.0
  180. # make sure new_width is an integral multiple of width_divisor.
  181. width_divisor = int(1 / width_downsample_ratio)
  182. # resize
  183. ratio = w / float(h)
  184. resize_w = math.ceil(imgH * ratio)
  185. if resize_w % width_divisor != 0:
  186. resize_w = round(resize_w / width_divisor) * width_divisor
  187. if imgW_min is not None:
  188. resize_w = max(imgW_min, resize_w)
  189. if imgW_max is not None:
  190. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  191. resize_w = min(imgW_max, resize_w)
  192. resized_image = cv2.resize(img, (resize_w, imgH))
  193. resized_image = resized_image.astype('float32')
  194. # norm
  195. if image_shape[0] == 1:
  196. resized_image = resized_image / 255
  197. resized_image = resized_image[np.newaxis, :]
  198. else:
  199. resized_image = resized_image.transpose((2, 0, 1)) / 255
  200. resized_image -= 0.5
  201. resized_image /= 0.5
  202. resize_shape = resized_image.shape
  203. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  204. padding_im[:, :, 0:resize_w] = resized_image
  205. pad_shape = padding_im.shape
  206. return padding_im, resize_shape, pad_shape, valid_ratio
  207. def resize_norm_img_spin(self, img):
  208. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  209. # return padding_im
  210. img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC)
  211. img = np.array(img, np.float32)
  212. img = np.expand_dims(img, -1)
  213. img = img.transpose((2, 0, 1))
  214. mean = [127.5]
  215. std = [127.5]
  216. mean = np.array(mean, dtype=np.float32)
  217. std = np.array(std, dtype=np.float32)
  218. mean = np.float32(mean.reshape(1, -1))
  219. stdinv = 1 / np.float32(std.reshape(1, -1))
  220. img -= mean
  221. img *= stdinv
  222. return img
  223. def resize_norm_img_svtr(self, img, image_shape):
  224. imgC, imgH, imgW = image_shape
  225. resized_image = cv2.resize(
  226. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  227. resized_image = resized_image.astype('float32')
  228. resized_image = resized_image.transpose((2, 0, 1)) / 255
  229. resized_image -= 0.5
  230. resized_image /= 0.5
  231. return resized_image
  232. def resize_norm_img_abinet(self, img, image_shape):
  233. imgC, imgH, imgW = image_shape
  234. resized_image = cv2.resize(
  235. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  236. resized_image = resized_image.astype('float32')
  237. resized_image = resized_image / 255.
  238. mean = np.array([0.485, 0.456, 0.406])
  239. std = np.array([0.229, 0.224, 0.225])
  240. resized_image = (
  241. resized_image - mean[None, None, ...]) / std[None, None, ...]
  242. resized_image = resized_image.transpose((2, 0, 1))
  243. resized_image = resized_image.astype('float32')
  244. return resized_image
  245. def norm_img_can(self, img, image_shape):
  246. img = cv2.cvtColor(
  247. img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image
  248. if self.rec_image_shape[0] == 1:
  249. h, w = img.shape
  250. _, imgH, imgW = self.rec_image_shape
  251. if h < imgH or w < imgW:
  252. padding_h = max(imgH - h, 0)
  253. padding_w = max(imgW - w, 0)
  254. img_padded = np.pad(img, ((0, padding_h), (0, padding_w)),
  255. 'constant',
  256. constant_values=(255))
  257. img = img_padded
  258. img = np.expand_dims(img, 0) / 255.0 # h,w,c -> c,h,w
  259. img = img.astype('float32')
  260. return img
  261. def __call__(self, img_list):
  262. img_num = len(img_list)
  263. # Calculate the aspect ratio of all text bars
  264. width_list = []
  265. for img in img_list:
  266. width_list.append(img.shape[1] / float(img.shape[0]))
  267. # Sorting can speed up the recognition process
  268. indices = np.argsort(np.array(width_list))
  269. rec_res = [['', 0.0]] * img_num
  270. batch_num = self.rec_batch_num
  271. st = time.time()
  272. for beg_img_no in range(0, img_num, batch_num):
  273. end_img_no = min(img_num, beg_img_no + batch_num)
  274. norm_img_batch = []
  275. imgC, imgH, imgW = self.rec_image_shape[:3]
  276. max_wh_ratio = imgW / imgH
  277. # max_wh_ratio = 0
  278. for ino in range(beg_img_no, end_img_no):
  279. h, w = img_list[indices[ino]].shape[0:2]
  280. wh_ratio = w * 1.0 / h
  281. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  282. for ino in range(beg_img_no, end_img_no):
  283. norm_img = self.resize_norm_img(img_list[indices[ino]],
  284. max_wh_ratio)
  285. norm_img = norm_img[np.newaxis, :]
  286. norm_img_batch.append(norm_img)
  287. norm_img_batch = np.concatenate(norm_img_batch)
  288. norm_img_batch = norm_img_batch.copy()
  289. input_dict = {}
  290. input_dict[self.input_tensor.name] = norm_img_batch
  291. for i in range(100000):
  292. try:
  293. outputs = self.predictor.run(None, input_dict)
  294. break
  295. except Exception as e:
  296. if i >= 3:
  297. raise e
  298. time.sleep(5)
  299. preds = outputs[0]
  300. rec_result = self.postprocess_op(preds)
  301. for rno in range(len(rec_result)):
  302. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  303. return rec_res, time.time() - st
  304. class TextDetector(object):
  305. def __init__(self, model_dir):
  306. pre_process_list = [{
  307. 'DetResizeForTest': {
  308. 'limit_side_len': 960,
  309. 'limit_type': "max",
  310. }
  311. }, {
  312. 'NormalizeImage': {
  313. 'std': [0.229, 0.224, 0.225],
  314. 'mean': [0.485, 0.456, 0.406],
  315. 'scale': '1./255.',
  316. 'order': 'hwc'
  317. }
  318. }, {
  319. 'ToCHWImage': None
  320. }, {
  321. 'KeepKeys': {
  322. 'keep_keys': ['image', 'shape']
  323. }
  324. }]
  325. postprocess_params = {"name": "DBPostProcess", "thresh": 0.3, "box_thresh": 0.5, "max_candidates": 1000,
  326. "unclip_ratio": 1.5, "use_dilation": False, "score_mode": "fast", "box_type": "quad"}
  327. self.postprocess_op = build_post_process(postprocess_params)
  328. self.predictor, self.input_tensor = load_model(model_dir, 'det')
  329. img_h, img_w = self.input_tensor.shape[2:]
  330. if isinstance(img_h, str) or isinstance(img_w, str):
  331. pass
  332. elif img_h is not None and img_w is not None and img_h > 0 and img_w > 0:
  333. pre_process_list[0] = {
  334. 'DetResizeForTest': {
  335. 'image_shape': [img_h, img_w]
  336. }
  337. }
  338. self.preprocess_op = create_operators(pre_process_list)
  339. def order_points_clockwise(self, pts):
  340. rect = np.zeros((4, 2), dtype="float32")
  341. s = pts.sum(axis=1)
  342. rect[0] = pts[np.argmin(s)]
  343. rect[2] = pts[np.argmax(s)]
  344. tmp = np.delete(pts, (np.argmin(s), np.argmax(s)), axis=0)
  345. diff = np.diff(np.array(tmp), axis=1)
  346. rect[1] = tmp[np.argmin(diff)]
  347. rect[3] = tmp[np.argmax(diff)]
  348. return rect
  349. def clip_det_res(self, points, img_height, img_width):
  350. for pno in range(points.shape[0]):
  351. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  352. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  353. return points
  354. def filter_tag_det_res(self, dt_boxes, image_shape):
  355. img_height, img_width = image_shape[0:2]
  356. dt_boxes_new = []
  357. for box in dt_boxes:
  358. if isinstance(box, list):
  359. box = np.array(box)
  360. box = self.order_points_clockwise(box)
  361. box = self.clip_det_res(box, img_height, img_width)
  362. rect_width = int(np.linalg.norm(box[0] - box[1]))
  363. rect_height = int(np.linalg.norm(box[0] - box[3]))
  364. if rect_width <= 3 or rect_height <= 3:
  365. continue
  366. dt_boxes_new.append(box)
  367. dt_boxes = np.array(dt_boxes_new)
  368. return dt_boxes
  369. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  370. img_height, img_width = image_shape[0:2]
  371. dt_boxes_new = []
  372. for box in dt_boxes:
  373. if isinstance(box, list):
  374. box = np.array(box)
  375. box = self.clip_det_res(box, img_height, img_width)
  376. dt_boxes_new.append(box)
  377. dt_boxes = np.array(dt_boxes_new)
  378. return dt_boxes
  379. def __call__(self, img):
  380. ori_im = img.copy()
  381. data = {'image': img}
  382. st = time.time()
  383. data = transform(data, self.preprocess_op)
  384. img, shape_list = data
  385. if img is None:
  386. return None, 0
  387. img = np.expand_dims(img, axis=0)
  388. shape_list = np.expand_dims(shape_list, axis=0)
  389. img = img.copy()
  390. input_dict = {}
  391. input_dict[self.input_tensor.name] = img
  392. for i in range(100000):
  393. try:
  394. outputs = self.predictor.run(None, input_dict)
  395. break
  396. except Exception as e:
  397. if i >= 3:
  398. raise e
  399. time.sleep(5)
  400. post_result = self.postprocess_op({"maps": outputs[0]}, shape_list)
  401. dt_boxes = post_result[0]['points']
  402. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  403. return dt_boxes, time.time() - st
  404. class OCR(object):
  405. def __init__(self, model_dir=None):
  406. """
  407. If you have trouble downloading HuggingFace models, -_^ this might help!!
  408. For Linux:
  409. export HF_ENDPOINT=https://hf-mirror.com
  410. For Windows:
  411. Good luck
  412. ^_-
  413. """
  414. if not model_dir:
  415. try:
  416. model_dir = os.path.join(
  417. get_project_base_directory(),
  418. "rag/res/deepdoc")
  419. self.text_detector = TextDetector(model_dir)
  420. self.text_recognizer = TextRecognizer(model_dir)
  421. except Exception:
  422. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc",
  423. local_dir=os.path.join(get_project_base_directory(), "rag/res/deepdoc"),
  424. local_dir_use_symlinks=False)
  425. self.text_detector = TextDetector(model_dir)
  426. self.text_recognizer = TextRecognizer(model_dir)
  427. self.drop_score = 0.5
  428. self.crop_image_res_index = 0
  429. def get_rotate_crop_image(self, img, points):
  430. '''
  431. img_height, img_width = img.shape[0:2]
  432. left = int(np.min(points[:, 0]))
  433. right = int(np.max(points[:, 0]))
  434. top = int(np.min(points[:, 1]))
  435. bottom = int(np.max(points[:, 1]))
  436. img_crop = img[top:bottom, left:right, :].copy()
  437. points[:, 0] = points[:, 0] - left
  438. points[:, 1] = points[:, 1] - top
  439. '''
  440. assert len(points) == 4, "shape of points must be 4*2"
  441. img_crop_width = int(
  442. max(
  443. np.linalg.norm(points[0] - points[1]),
  444. np.linalg.norm(points[2] - points[3])))
  445. img_crop_height = int(
  446. max(
  447. np.linalg.norm(points[0] - points[3]),
  448. np.linalg.norm(points[1] - points[2])))
  449. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  450. [img_crop_width, img_crop_height],
  451. [0, img_crop_height]])
  452. M = cv2.getPerspectiveTransform(points, pts_std)
  453. dst_img = cv2.warpPerspective(
  454. img,
  455. M, (img_crop_width, img_crop_height),
  456. borderMode=cv2.BORDER_REPLICATE,
  457. flags=cv2.INTER_CUBIC)
  458. dst_img_height, dst_img_width = dst_img.shape[0:2]
  459. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  460. dst_img = np.rot90(dst_img)
  461. return dst_img
  462. def sorted_boxes(self, dt_boxes):
  463. """
  464. Sort text boxes in order from top to bottom, left to right
  465. args:
  466. dt_boxes(array):detected text boxes with shape [4, 2]
  467. return:
  468. sorted boxes(array) with shape [4, 2]
  469. """
  470. num_boxes = dt_boxes.shape[0]
  471. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  472. _boxes = list(sorted_boxes)
  473. for i in range(num_boxes - 1):
  474. for j in range(i, -1, -1):
  475. if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
  476. (_boxes[j + 1][0][0] < _boxes[j][0][0]):
  477. tmp = _boxes[j]
  478. _boxes[j] = _boxes[j + 1]
  479. _boxes[j + 1] = tmp
  480. else:
  481. break
  482. return _boxes
  483. def detect(self, img):
  484. time_dict = {'det': 0, 'rec': 0, 'cls': 0, 'all': 0}
  485. if img is None:
  486. return None, None, time_dict
  487. start = time.time()
  488. dt_boxes, elapse = self.text_detector(img)
  489. time_dict['det'] = elapse
  490. if dt_boxes is None:
  491. end = time.time()
  492. time_dict['all'] = end - start
  493. return None, None, time_dict
  494. return zip(self.sorted_boxes(dt_boxes), [
  495. ("", 0) for _ in range(len(dt_boxes))])
  496. def recognize(self, ori_im, box):
  497. img_crop = self.get_rotate_crop_image(ori_im, box)
  498. rec_res, elapse = self.text_recognizer([img_crop])
  499. text, score = rec_res[0]
  500. if score < self.drop_score:
  501. return ""
  502. return text
  503. def __call__(self, img, cls=True):
  504. time_dict = {'det': 0, 'rec': 0, 'cls': 0, 'all': 0}
  505. if img is None:
  506. return None, None, time_dict
  507. start = time.time()
  508. ori_im = img.copy()
  509. dt_boxes, elapse = self.text_detector(img)
  510. time_dict['det'] = elapse
  511. if dt_boxes is None:
  512. end = time.time()
  513. time_dict['all'] = end - start
  514. return None, None, time_dict
  515. img_crop_list = []
  516. dt_boxes = self.sorted_boxes(dt_boxes)
  517. for bno in range(len(dt_boxes)):
  518. tmp_box = copy.deepcopy(dt_boxes[bno])
  519. img_crop = self.get_rotate_crop_image(ori_im, tmp_box)
  520. img_crop_list.append(img_crop)
  521. rec_res, elapse = self.text_recognizer(img_crop_list)
  522. time_dict['rec'] = elapse
  523. filter_boxes, filter_rec_res = [], []
  524. for box, rec_result in zip(dt_boxes, rec_res):
  525. text, score = rec_result
  526. if score >= self.drop_score:
  527. filter_boxes.append(box)
  528. filter_rec_res.append(rec_result)
  529. end = time.time()
  530. time_dict['all'] = end - start
  531. # for bno in range(len(img_crop_list)):
  532. # print(f"{bno}, {rec_res[bno]}")
  533. return list(zip([a.tolist() for a in filter_boxes], filter_rec_res))