Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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