predict_layout.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 tools.infer.utility as utility
  24. from ppocr.data import create_operators, transform
  25. from ppocr.postprocess import build_post_process
  26. from ppocr.utils.logging import get_logger
  27. from ppocr.utils.utility import get_image_file_list, check_and_read
  28. from ppstructure.utility import parse_args
  29. from picodet_postprocess import PicoDetPostProcess
  30. logger = get_logger()
  31. class LayoutPredictor(object):
  32. def __init__(self, args):
  33. pre_process_list = [
  34. {"Resize": {"size": [800, 608]}},
  35. {
  36. "NormalizeImage": {
  37. "std": [0.229, 0.224, 0.225],
  38. "mean": [0.485, 0.456, 0.406],
  39. "scale": "1./255.",
  40. "order": "hwc",
  41. }
  42. },
  43. {"ToCHWImage": None},
  44. {"KeepKeys": {"keep_keys": ["image"]}},
  45. ]
  46. postprocess_params = {
  47. "name": "PicoDetPostProcess",
  48. "layout_dict_path": args.layout_dict_path,
  49. "score_threshold": args.layout_score_threshold,
  50. "nms_threshold": args.layout_nms_threshold,
  51. }
  52. self.preprocess_op = create_operators(pre_process_list)
  53. self.postprocess_op = build_post_process(postprocess_params)
  54. (
  55. self.predictor,
  56. self.input_tensor,
  57. self.output_tensors,
  58. self.config,
  59. ) = utility.create_predictor(args, "layout", logger)
  60. self.use_onnx = args.use_onnx
  61. def __call__(self, img):
  62. ori_im = img.copy()
  63. data = {"image": img}
  64. data = transform(data, self.preprocess_op)
  65. img = data[0]
  66. if img is None:
  67. return None, 0
  68. img = np.expand_dims(img, axis=0)
  69. img = img.copy()
  70. preds, elapse = 0, 1
  71. starttime = time.time()
  72. np_score_list, np_boxes_list = [], []
  73. if self.use_onnx:
  74. input_dict = {}
  75. input_dict[self.input_tensor.name] = img
  76. outputs = self.predictor.run(self.output_tensors, input_dict)
  77. num_outs = int(len(outputs) / 2)
  78. for out_idx in range(num_outs):
  79. np_score_list.append(outputs[out_idx])
  80. np_boxes_list.append(outputs[out_idx + num_outs])
  81. else:
  82. self.input_tensor.copy_from_cpu(img)
  83. self.predictor.run()
  84. output_names = self.predictor.get_output_names()
  85. num_outs = int(len(output_names) / 2)
  86. for out_idx in range(num_outs):
  87. np_score_list.append(
  88. self.predictor.get_output_handle(
  89. output_names[out_idx]
  90. ).copy_to_cpu()
  91. )
  92. np_boxes_list.append(
  93. self.predictor.get_output_handle(
  94. output_names[out_idx + num_outs]
  95. ).copy_to_cpu()
  96. )
  97. preds = dict(boxes=np_score_list, boxes_num=np_boxes_list)
  98. post_preds = self.postprocess_op(ori_im, img, preds)
  99. elapse = time.time() - starttime
  100. return post_preds, elapse
  101. def main(args):
  102. image_file_list = get_image_file_list(args.image_dir)
  103. layout_predictor = LayoutPredictor(args)
  104. count = 0
  105. total_time = 0
  106. repeats = 50
  107. for image_file in image_file_list:
  108. img, flag, _ = check_and_read(image_file)
  109. if not flag:
  110. img = cv2.imread(image_file)
  111. if img is None:
  112. logger.info("error in loading image:{}".format(image_file))
  113. continue
  114. layout_res, elapse = layout_predictor(img)
  115. logger.info("result: {}".format(layout_res))
  116. if count > 0:
  117. total_time += elapse
  118. count += 1
  119. logger.info("Predict time of {}: {}".format(image_file, elapse))
  120. if __name__ == "__main__":
  121. main(parse_args())