predict_table.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 = (
  60. predict_det.TextDetector(copy.deepcopy(args))
  61. if text_detector is None
  62. else text_detector
  63. )
  64. self.text_recognizer = (
  65. predict_rec.TextRecognizer(copy.deepcopy(args))
  66. if text_recognizer is None
  67. else text_recognizer
  68. )
  69. if benchmark_tmp:
  70. args.benchmark = True
  71. self.table_structurer = predict_strture.TableStructurer(args)
  72. if args.table_algorithm in ["TableMaster"]:
  73. self.match = TableMasterMatcher()
  74. else:
  75. self.match = TableMatch(filter_ocr_result=True)
  76. (
  77. self.predictor,
  78. self.input_tensor,
  79. self.output_tensors,
  80. self.config,
  81. ) = utility.create_predictor(args, "table", logger)
  82. def __call__(self, img, return_ocr_result_in_table=False):
  83. result = dict()
  84. time_dict = {"det": 0, "rec": 0, "table": 0, "all": 0, "match": 0}
  85. start = time.time()
  86. structure_res, elapse = self._structure(copy.deepcopy(img))
  87. result["cell_bbox"] = structure_res[1].tolist()
  88. time_dict["table"] = elapse
  89. dt_boxes, rec_res, det_elapse, rec_elapse = self._ocr(copy.deepcopy(img))
  90. time_dict["det"] = det_elapse
  91. time_dict["rec"] = rec_elapse
  92. if return_ocr_result_in_table:
  93. result["boxes"] = [x.tolist() for x in dt_boxes]
  94. result["rec_res"] = rec_res
  95. tic = time.time()
  96. pred_html = self.match(structure_res, dt_boxes, rec_res)
  97. toc = time.time()
  98. time_dict["match"] = toc - tic
  99. result["html"] = pred_html
  100. end = time.time()
  101. time_dict["all"] = end - start
  102. return result, time_dict
  103. def _structure(self, img):
  104. structure_res, elapse = self.table_structurer(copy.deepcopy(img))
  105. return structure_res, elapse
  106. def _ocr(self, img):
  107. h, w = img.shape[:2]
  108. dt_boxes, det_elapse = self.text_detector(copy.deepcopy(img))
  109. dt_boxes = sorted_boxes(dt_boxes)
  110. r_boxes = []
  111. for box in dt_boxes:
  112. x_min = max(0, box[:, 0].min() - 1)
  113. x_max = min(w, box[:, 0].max() + 1)
  114. y_min = max(0, box[:, 1].min() - 1)
  115. y_max = min(h, box[:, 1].max() + 1)
  116. box = [x_min, y_min, x_max, y_max]
  117. r_boxes.append(box)
  118. dt_boxes = np.array(r_boxes)
  119. logger.debug("dt_boxes num : {}, elapse : {}".format(len(dt_boxes), det_elapse))
  120. if dt_boxes is None:
  121. return None, None
  122. img_crop_list = []
  123. for i in range(len(dt_boxes)):
  124. det_box = dt_boxes[i]
  125. x0, y0, x1, y1 = expand(2, det_box, img.shape)
  126. text_rect = img[int(y0) : int(y1), int(x0) : int(x1), :]
  127. img_crop_list.append(text_rect)
  128. rec_res, rec_elapse = self.text_recognizer(img_crop_list)
  129. logger.debug("rec_res num : {}, elapse : {}".format(len(rec_res), rec_elapse))
  130. return dt_boxes, rec_res, det_elapse, rec_elapse
  131. def to_excel(html_table, excel_path):
  132. from tablepyxl import tablepyxl
  133. tablepyxl.document_to_xl(html_table, excel_path)
  134. def main(args):
  135. image_file_list = get_image_file_list(args.image_dir)
  136. image_file_list = image_file_list[args.process_id :: args.total_process_num]
  137. os.makedirs(args.output, exist_ok=True)
  138. table_sys = TableSystem(args)
  139. img_num = len(image_file_list)
  140. f_html = open(os.path.join(args.output, "show.html"), mode="w", encoding="utf-8")
  141. f_html.write("<html>\n<body>\n")
  142. f_html.write('<table border="1">\n')
  143. f_html.write(
  144. '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
  145. )
  146. f_html.write("<tr>\n")
  147. f_html.write("<td>img name\n")
  148. f_html.write("<td>ori image</td>")
  149. f_html.write("<td>table html</td>")
  150. f_html.write("<td>cell box</td>")
  151. f_html.write("</tr>\n")
  152. for i, image_file in enumerate(image_file_list):
  153. logger.info("[{}/{}] {}".format(i, img_num, image_file))
  154. img, flag, _ = check_and_read(image_file)
  155. excel_path = os.path.join(
  156. args.output, os.path.basename(image_file).split(".")[0] + ".xlsx"
  157. )
  158. if not flag:
  159. img = cv2.imread(image_file)
  160. if img is None:
  161. logger.error("error in loading image:{}".format(image_file))
  162. continue
  163. starttime = time.time()
  164. pred_res, _ = table_sys(img)
  165. pred_html = pred_res["html"]
  166. logger.info(pred_html)
  167. to_excel(pred_html, excel_path)
  168. logger.info("excel saved to {}".format(excel_path))
  169. elapse = time.time() - starttime
  170. logger.info("Predict time : {:.3f}s".format(elapse))
  171. if len(pred_res["cell_bbox"]) > 0 and len(pred_res["cell_bbox"][0]) == 4:
  172. img = predict_strture.draw_rectangle(image_file, pred_res["cell_bbox"])
  173. else:
  174. img = utility.draw_boxes(img, pred_res["cell_bbox"])
  175. img_save_path = os.path.join(args.output, os.path.basename(image_file))
  176. cv2.imwrite(img_save_path, img)
  177. f_html.write("<tr>\n")
  178. f_html.write(f"<td> {os.path.basename(image_file)} <br/>\n")
  179. f_html.write(f'<td><img src="{image_file}" width=640></td>\n')
  180. f_html.write(
  181. '<td><table border="1">'
  182. + pred_html.replace("<html><body><table>", "").replace(
  183. "</table></body></html>", ""
  184. )
  185. + "</table></td>\n"
  186. )
  187. f_html.write(f'<td><img src="{os.path.basename(image_file)}" width=640></td>\n')
  188. f_html.write("</tr>\n")
  189. f_html.write("</table>\n")
  190. f_html.close()
  191. if args.benchmark:
  192. table_sys.table_structurer.autolog.report()
  193. if __name__ == "__main__":
  194. args = parse_args()
  195. if args.use_mp:
  196. import subprocess
  197. p_list = []
  198. total_process_num = args.total_process_num
  199. for process_id in range(total_process_num):
  200. cmd = (
  201. [sys.executable, "-u"]
  202. + sys.argv
  203. + ["--process_id={}".format(process_id), "--use_mp={}".format(False)]
  204. )
  205. p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout)
  206. p_list.append(p)
  207. for p in p_list:
  208. p.wait()
  209. else:
  210. main(args)