predict_table.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. __dir__ = os.path.dirname(os.path.abspath(__file__))
  17. sys.path.append(__dir__)
  18. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..')))
  19. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..')))
  20. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  21. import cv2
  22. import copy
  23. import logging
  24. import numpy as np
  25. import time
  26. import tools.infer.predict_rec as predict_rec
  27. import tools.infer.predict_det as predict_det
  28. import tools.infer.utility as utility
  29. from tools.infer.predict_system import sorted_boxes
  30. from ppocr.utils.utility import get_image_file_list, check_and_read
  31. from ppocr.utils.logging import get_logger
  32. from ppstructure.table.matcher import TableMatch
  33. from ppstructure.table.table_master_match import TableMasterMatcher
  34. from ppstructure.utility import parse_args
  35. import ppstructure.table.predict_structure as predict_strture
  36. logger = get_logger()
  37. def expand(pix, det_box, shape):
  38. x0, y0, x1, y1 = det_box
  39. # print(shape)
  40. h, w, c = shape
  41. tmp_x0 = x0 - pix
  42. tmp_x1 = x1 + pix
  43. tmp_y0 = y0 - pix
  44. tmp_y1 = y1 + pix
  45. x0_ = tmp_x0 if tmp_x0 >= 0 else 0
  46. x1_ = tmp_x1 if tmp_x1 <= w else w
  47. y0_ = tmp_y0 if tmp_y0 >= 0 else 0
  48. y1_ = tmp_y1 if tmp_y1 <= h else h
  49. return x0_, y0_, x1_, y1_
  50. class TableSystem(object):
  51. def __init__(self, args, text_detector=None, text_recognizer=None):
  52. self.args = args
  53. if not args.show_log:
  54. logger.setLevel(logging.INFO)
  55. benchmark_tmp = False
  56. if args.benchmark:
  57. benchmark_tmp = args.benchmark
  58. args.benchmark = False
  59. self.text_detector = predict_det.TextDetector(copy.deepcopy(
  60. args)) if text_detector is None else text_detector
  61. self.text_recognizer = predict_rec.TextRecognizer(copy.deepcopy(
  62. args)) if text_recognizer is None else text_recognizer
  63. if benchmark_tmp:
  64. args.benchmark = True
  65. self.table_structurer = predict_strture.TableStructurer(args)
  66. if args.table_algorithm in ['TableMaster']:
  67. self.match = TableMasterMatcher()
  68. else:
  69. self.match = TableMatch(filter_ocr_result=True)
  70. self.predictor, self.input_tensor, self.output_tensors, self.config = utility.create_predictor(
  71. args, 'table', logger)
  72. def __call__(self, img, return_ocr_result_in_table=False):
  73. result = dict()
  74. time_dict = {'det': 0, 'rec': 0, 'table': 0, 'all': 0, 'match': 0}
  75. start = time.time()
  76. structure_res, elapse = self._structure(copy.deepcopy(img))
  77. result['cell_bbox'] = structure_res[1].tolist()
  78. time_dict['table'] = elapse
  79. dt_boxes, rec_res, det_elapse, rec_elapse = self._ocr(
  80. copy.deepcopy(img))
  81. time_dict['det'] = det_elapse
  82. time_dict['rec'] = rec_elapse
  83. if return_ocr_result_in_table:
  84. result['boxes'] = dt_boxes #[x.tolist() for x in dt_boxes]
  85. result['rec_res'] = rec_res
  86. tic = time.time()
  87. pred_html = self.match(structure_res, dt_boxes, rec_res)
  88. toc = time.time()
  89. time_dict['match'] = toc - tic
  90. result['html'] = pred_html
  91. end = time.time()
  92. time_dict['all'] = end - start
  93. return result, time_dict
  94. def _structure(self, img):
  95. structure_res, elapse = self.table_structurer(copy.deepcopy(img))
  96. return structure_res, elapse
  97. def _ocr(self, img):
  98. h, w = img.shape[:2]
  99. dt_boxes, det_elapse = self.text_detector(copy.deepcopy(img))
  100. dt_boxes = sorted_boxes(dt_boxes)
  101. r_boxes = []
  102. for box in dt_boxes:
  103. x_min = max(0, box[:, 0].min() - 1)
  104. x_max = min(w, box[:, 0].max() + 1)
  105. y_min = max(0, box[:, 1].min() - 1)
  106. y_max = min(h, box[:, 1].max() + 1)
  107. box = [x_min, y_min, x_max, y_max]
  108. r_boxes.append(box)
  109. dt_boxes = np.array(r_boxes)
  110. logger.debug("dt_boxes num : {}, elapse : {}".format(
  111. len(dt_boxes), det_elapse))
  112. if dt_boxes is None:
  113. return None, None
  114. img_crop_list = []
  115. for i in range(len(dt_boxes)):
  116. det_box = dt_boxes[i]
  117. x0, y0, x1, y1 = expand(2, det_box, img.shape)
  118. text_rect = img[int(y0):int(y1), int(x0):int(x1), :]
  119. img_crop_list.append(text_rect)
  120. rec_res, rec_elapse = self.text_recognizer(img_crop_list)
  121. logger.debug("rec_res num : {}, elapse : {}".format(
  122. len(rec_res), rec_elapse))
  123. return dt_boxes, rec_res, det_elapse, rec_elapse
  124. def to_excel(html_table, excel_path):
  125. from tablepyxl import tablepyxl
  126. tablepyxl.document_to_xl(html_table, excel_path)
  127. def main(args):
  128. image_file_list = get_image_file_list(args.image_dir)
  129. image_file_list = image_file_list[args.process_id::args.total_process_num]
  130. os.makedirs(args.output, exist_ok=True)
  131. table_sys = TableSystem(args)
  132. img_num = len(image_file_list)
  133. f_html = open(
  134. os.path.join(args.output, 'show.html'), mode='w', encoding='utf-8')
  135. f_html.write('<html>\n<body>\n')
  136. f_html.write('<table border="1">\n')
  137. f_html.write(
  138. "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
  139. )
  140. f_html.write("<tr>\n")
  141. f_html.write('<td>img name\n')
  142. f_html.write('<td>ori image</td>')
  143. f_html.write('<td>table html</td>')
  144. f_html.write('<td>cell box</td>')
  145. f_html.write("</tr>\n")
  146. for i, image_file in enumerate(image_file_list):
  147. logger.info("[{}/{}] {}".format(i, img_num, image_file))
  148. img, flag, _ = check_and_read(image_file)
  149. excel_path = os.path.join(
  150. args.output, os.path.basename(image_file).split('.')[0] + '.xlsx')
  151. if not flag:
  152. img = cv2.imread(image_file)
  153. if img is None:
  154. logger.error("error in loading image:{}".format(image_file))
  155. continue
  156. starttime = time.time()
  157. pred_res, _ = table_sys(img)
  158. pred_html = pred_res['html']
  159. logger.info(pred_html)
  160. to_excel(pred_html, excel_path)
  161. logger.info('excel saved to {}'.format(excel_path))
  162. elapse = time.time() - starttime
  163. logger.info("Predict time : {:.3f}s".format(elapse))
  164. if len(pred_res['cell_bbox']) > 0 and len(pred_res['cell_bbox'][
  165. 0]) == 4:
  166. img = predict_strture.draw_rectangle(image_file,
  167. pred_res['cell_bbox'])
  168. else:
  169. img = utility.draw_boxes(img, pred_res['cell_bbox'])
  170. img_save_path = os.path.join(args.output, os.path.basename(image_file))
  171. cv2.imwrite(img_save_path, img)
  172. f_html.write("<tr>\n")
  173. f_html.write(f'<td> {os.path.basename(image_file)} <br/>\n')
  174. f_html.write(f'<td><img src="{image_file}" width=640></td>\n')
  175. f_html.write('<td><table border="1">' + pred_html.replace(
  176. '<html><body><table>', '').replace('</table></body></html>', '') +
  177. '</table></td>\n')
  178. f_html.write(
  179. f'<td><img src="{os.path.basename(image_file)}" width=640></td>\n')
  180. f_html.write("</tr>\n")
  181. f_html.write("</table>\n")
  182. f_html.close()
  183. if args.benchmark:
  184. table_sys.table_structurer.autolog.report()
  185. if __name__ == "__main__":
  186. args = parse_args()
  187. if args.use_mp:
  188. import subprocess
  189. p_list = []
  190. total_process_num = args.total_process_num
  191. for process_id in range(total_process_num):
  192. cmd = [sys.executable, "-u"] + sys.argv + [
  193. "--process_id={}".format(process_id),
  194. "--use_mp={}".format(False)
  195. ]
  196. p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout)
  197. p_list.append(p)
  198. for p in p_list:
  199. p.wait()
  200. else:
  201. main(args)