Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ocr.py 22KB

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