infer_det.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import numpy as np
  18. import os
  19. import sys
  20. __dir__ = os.path.dirname(os.path.abspath(__file__))
  21. sys.path.append(__dir__)
  22. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..')))
  23. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  24. import cv2
  25. import json
  26. import paddle
  27. from ppocr.data import create_operators, transform
  28. from ppocr.modeling.architectures import build_model
  29. from ppocr.postprocess import build_post_process
  30. from ppocr.utils.save_load import load_model
  31. from ppocr.utils.utility import get_image_file_list
  32. import tools.program as program
  33. def draw_det_res(dt_boxes, config, img, img_name, save_path):
  34. if len(dt_boxes) > 0:
  35. import cv2
  36. src_im = img
  37. for box in dt_boxes:
  38. box = np.array(box).astype(np.int32).reshape((-1, 1, 2))
  39. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  40. if not os.path.exists(save_path):
  41. os.makedirs(save_path)
  42. save_path = os.path.join(save_path, os.path.basename(img_name))
  43. cv2.imwrite(save_path, src_im)
  44. logger.info("The detected Image saved in {}".format(save_path))
  45. @paddle.no_grad()
  46. def main():
  47. global_config = config['Global']
  48. # build model
  49. model = build_model(config['Architecture'])
  50. load_model(config, model)
  51. # build post process
  52. post_process_class = build_post_process(config['PostProcess'])
  53. # create data ops
  54. transforms = []
  55. for op in config['Eval']['dataset']['transforms']:
  56. op_name = list(op)[0]
  57. if 'Label' in op_name:
  58. continue
  59. elif op_name == 'KeepKeys':
  60. op[op_name]['keep_keys'] = ['image', 'shape']
  61. transforms.append(op)
  62. ops = create_operators(transforms, global_config)
  63. save_res_path = config['Global']['save_res_path']
  64. if not os.path.exists(os.path.dirname(save_res_path)):
  65. os.makedirs(os.path.dirname(save_res_path))
  66. model.eval()
  67. with open(save_res_path, "wb") as fout:
  68. for file in get_image_file_list(config['Global']['infer_img']):
  69. logger.info("infer_img: {}".format(file))
  70. with open(file, 'rb') as f:
  71. img = f.read()
  72. data = {'image': img}
  73. batch = transform(data, ops)
  74. images = np.expand_dims(batch[0], axis=0)
  75. shape_list = np.expand_dims(batch[1], axis=0)
  76. images = paddle.to_tensor(images)
  77. preds = model(images)
  78. post_result = post_process_class(preds, shape_list)
  79. src_img = cv2.imread(file)
  80. dt_boxes_json = []
  81. # parser boxes if post_result is dict
  82. if isinstance(post_result, dict):
  83. det_box_json = {}
  84. for k in post_result.keys():
  85. boxes = post_result[k][0]['points']
  86. dt_boxes_list = []
  87. for box in boxes:
  88. tmp_json = {"transcription": ""}
  89. tmp_json['points'] = np.array(box).tolist()
  90. dt_boxes_list.append(tmp_json)
  91. det_box_json[k] = dt_boxes_list
  92. save_det_path = os.path.dirname(config['Global'][
  93. 'save_res_path']) + "/det_results_{}/".format(k)
  94. draw_det_res(boxes, config, src_img, file, save_det_path)
  95. else:
  96. boxes = post_result[0]['points']
  97. dt_boxes_json = []
  98. # write result
  99. for box in boxes:
  100. tmp_json = {"transcription": ""}
  101. tmp_json['points'] = np.array(box).tolist()
  102. dt_boxes_json.append(tmp_json)
  103. save_det_path = os.path.dirname(config['Global'][
  104. 'save_res_path']) + "/det_results/"
  105. draw_det_res(boxes, config, src_img, file, save_det_path)
  106. otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n"
  107. fout.write(otstr.encode())
  108. logger.info("success!")
  109. if __name__ == '__main__':
  110. config, device, logger, vdl_writer = program.preprocess()
  111. main()