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 23KB

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