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.

ocr.py 22KB

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