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

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