您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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