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

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