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.

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