predict_structure.py 7.3 KB

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