predict_structure.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  20. import cv2
  21. import numpy as np
  22. import time
  23. import json
  24. import tools.infer.utility as utility
  25. from ppocr.data import create_operators, transform
  26. from ppocr.postprocess import build_post_process
  27. from ppocr.utils.logging import get_logger
  28. from ppocr.utils.utility import get_image_file_list, check_and_read
  29. from ppocr.utils.visual import draw_rectangle
  30. from ppstructure.utility import parse_args
  31. logger = get_logger()
  32. def build_pre_process_list(args):
  33. resize_op = {
  34. "ResizeTableImage": {
  35. "max_len": args.table_max_len,
  36. }
  37. }
  38. pad_op = {"PaddingTableImage": {"size": [args.table_max_len, args.table_max_len]}}
  39. normalize_op = {
  40. "NormalizeImage": {
  41. "std": (
  42. [0.229, 0.224, 0.225]
  43. if args.table_algorithm not in ["TableMaster"]
  44. else [0.5, 0.5, 0.5]
  45. ),
  46. "mean": (
  47. [0.485, 0.456, 0.406]
  48. if args.table_algorithm not in ["TableMaster"]
  49. else [0.5, 0.5, 0.5]
  50. ),
  51. "scale": "1./255.",
  52. "order": "hwc",
  53. }
  54. }
  55. to_chw_op = {"ToCHWImage": None}
  56. keep_keys_op = {"KeepKeys": {"keep_keys": ["image", "shape"]}}
  57. if args.table_algorithm not in ["TableMaster"]:
  58. pre_process_list = [resize_op, normalize_op, pad_op, to_chw_op, keep_keys_op]
  59. else:
  60. pre_process_list = [resize_op, pad_op, normalize_op, to_chw_op, keep_keys_op]
  61. return pre_process_list
  62. class TableStructurer(object):
  63. def __init__(self, args):
  64. self.args = args
  65. self.use_onnx = args.use_onnx
  66. pre_process_list = build_pre_process_list(args)
  67. if args.table_algorithm not in ["TableMaster"]:
  68. postprocess_params = {
  69. "name": "TableLabelDecode",
  70. "character_dict_path": args.table_char_dict_path,
  71. "merge_no_span_structure": args.merge_no_span_structure,
  72. }
  73. else:
  74. postprocess_params = {
  75. "name": "TableMasterLabelDecode",
  76. "character_dict_path": args.table_char_dict_path,
  77. "box_shape": "pad",
  78. "merge_no_span_structure": args.merge_no_span_structure,
  79. }
  80. self.preprocess_op = create_operators(pre_process_list)
  81. self.postprocess_op = build_post_process(postprocess_params)
  82. (
  83. self.predictor,
  84. self.input_tensor,
  85. self.output_tensors,
  86. self.config,
  87. ) = utility.create_predictor(args, "table", logger)
  88. if args.benchmark:
  89. import auto_log
  90. pid = os.getpid()
  91. gpu_id = utility.get_infer_gpuid()
  92. self.autolog = auto_log.AutoLogger(
  93. model_name="table",
  94. model_precision=args.precision,
  95. batch_size=1,
  96. data_shape="dynamic",
  97. save_path=None, # args.save_log_path,
  98. inference_config=self.config,
  99. pids=pid,
  100. process_name=None,
  101. gpu_ids=gpu_id if args.use_gpu else None,
  102. time_keys=["preprocess_time", "inference_time", "postprocess_time"],
  103. warmup=0,
  104. logger=logger,
  105. )
  106. def __call__(self, img):
  107. starttime = time.time()
  108. if self.args.benchmark:
  109. self.autolog.times.start()
  110. ori_im = img.copy()
  111. data = {"image": img}
  112. data = transform(data, self.preprocess_op)
  113. img = data[0]
  114. if img is None:
  115. return None, 0
  116. img = np.expand_dims(img, axis=0)
  117. img = img.copy()
  118. if self.args.benchmark:
  119. self.autolog.times.stamp()
  120. if self.use_onnx:
  121. input_dict = {}
  122. input_dict[self.input_tensor.name] = img
  123. outputs = self.predictor.run(self.output_tensors, input_dict)
  124. else:
  125. self.input_tensor.copy_from_cpu(img)
  126. self.predictor.run()
  127. outputs = []
  128. for output_tensor in self.output_tensors:
  129. output = output_tensor.copy_to_cpu()
  130. outputs.append(output)
  131. if self.args.benchmark:
  132. self.autolog.times.stamp()
  133. preds = {}
  134. preds["structure_probs"] = outputs[1]
  135. preds["loc_preds"] = outputs[0]
  136. shape_list = np.expand_dims(data[-1], axis=0)
  137. post_result = self.postprocess_op(preds, [shape_list])
  138. structure_str_list = post_result["structure_batch_list"][0]
  139. bbox_list = post_result["bbox_batch_list"][0]
  140. structure_str_list = structure_str_list[0]
  141. structure_str_list = (
  142. ["<html>", "<body>", "<table>"]
  143. + structure_str_list
  144. + ["</table>", "</body>", "</html>"]
  145. )
  146. elapse = time.time() - starttime
  147. if self.args.benchmark:
  148. self.autolog.times.end(stamp=True)
  149. return (structure_str_list, bbox_list), elapse
  150. def main(args):
  151. image_file_list = get_image_file_list(args.image_dir)
  152. table_structurer = TableStructurer(args)
  153. count = 0
  154. total_time = 0
  155. os.makedirs(args.output, exist_ok=True)
  156. with open(
  157. os.path.join(args.output, "infer.txt"), mode="w", encoding="utf-8"
  158. ) as f_w:
  159. for image_file in image_file_list:
  160. img, flag, _ = check_and_read(image_file)
  161. if not flag:
  162. img = cv2.imread(image_file)
  163. if img is None:
  164. logger.info("error in loading image:{}".format(image_file))
  165. continue
  166. structure_res, elapse = table_structurer(img)
  167. structure_str_list, bbox_list = structure_res
  168. bbox_list_str = json.dumps(bbox_list.tolist())
  169. logger.info("result: {}, {}".format(structure_str_list, bbox_list_str))
  170. f_w.write("result: {}, {}\n".format(structure_str_list, bbox_list_str))
  171. if len(bbox_list) > 0 and len(bbox_list[0]) == 4:
  172. img = draw_rectangle(image_file, bbox_list)
  173. else:
  174. img = utility.draw_boxes(img, bbox_list)
  175. img_save_path = os.path.join(args.output, os.path.basename(image_file))
  176. cv2.imwrite(img_save_path, img)
  177. logger.info("save vis result to {}".format(img_save_path))
  178. if count > 0:
  179. total_time += elapse
  180. count += 1
  181. logger.info("Predict time of {}: {}".format(image_file, elapse))
  182. if args.benchmark:
  183. table_structurer.autolog.report()
  184. if __name__ == "__main__":
  185. main(parse_args())