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

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