predict_layout.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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': {
  35. 'size': [800, 608]
  36. }
  37. }, {
  38. 'NormalizeImage': {
  39. 'std': [0.229, 0.224, 0.225],
  40. 'mean': [0.485, 0.456, 0.406],
  41. 'scale': '1./255.',
  42. 'order': 'hwc'
  43. }
  44. }, {
  45. 'ToCHWImage': None
  46. }, {
  47. 'KeepKeys': {
  48. 'keep_keys': ['image']
  49. }
  50. }]
  51. postprocess_params = {
  52. 'name': 'PicoDetPostProcess',
  53. "layout_dict_path": args.layout_dict_path,
  54. "score_threshold": args.layout_score_threshold,
  55. "nms_threshold": args.layout_nms_threshold,
  56. }
  57. self.preprocess_op = create_operators(pre_process_list)
  58. self.postprocess_op = build_post_process(postprocess_params)
  59. self.predictor, self.input_tensor, self.output_tensors, self.config = \
  60. utility.create_predictor(args, 'layout', logger)
  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. self.input_tensor.copy_from_cpu(img)
  73. self.predictor.run()
  74. np_score_list, np_boxes_list = [], []
  75. output_names = self.predictor.get_output_names()
  76. num_outs = int(len(output_names) / 2)
  77. for out_idx in range(num_outs):
  78. np_score_list.append(
  79. self.predictor.get_output_handle(output_names[out_idx])
  80. .copy_to_cpu())
  81. np_boxes_list.append(
  82. self.predictor.get_output_handle(output_names[
  83. out_idx + num_outs]).copy_to_cpu())
  84. preds = dict(boxes=np_score_list, boxes_num=np_boxes_list)
  85. post_preds = self.postprocess_op(ori_im, img, preds)
  86. elapse = time.time() - starttime
  87. return post_preds, elapse
  88. def main(args):
  89. image_file_list = get_image_file_list(args.image_dir)
  90. layout_predictor = LayoutPredictor(args)
  91. count = 0
  92. total_time = 0
  93. repeats = 50
  94. for image_file in image_file_list:
  95. img, flag, _ = check_and_read(image_file)
  96. if not flag:
  97. img = cv2.imread(image_file)
  98. if img is None:
  99. logger.info("error in loading image:{}".format(image_file))
  100. continue
  101. layout_res, elapse = layout_predictor(img)
  102. logger.info("result: {}".format(layout_res))
  103. if count > 0:
  104. total_time += elapse
  105. count += 1
  106. logger.info("Predict time of {}: {}".format(image_file, elapse))
  107. if __name__ == "__main__":
  108. main(parse_args())