infer_det.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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.append(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 init_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):
  34. if len(dt_boxes) > 0:
  35. import cv2
  36. src_im = img
  37. for box in dt_boxes:
  38. box = box.astype(np.int32).reshape((-1, 1, 2))
  39. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  40. save_det_path = os.path.dirname(config['Global'][
  41. 'save_res_path']) + "/det_results/"
  42. if not os.path.exists(save_det_path):
  43. os.makedirs(save_det_path)
  44. save_path = os.path.join(save_det_path, os.path.basename(img_name))
  45. cv2.imwrite(save_path, src_im)
  46. logger.info("The detected Image saved in {}".format(save_path))
  47. def main():
  48. global_config = config['Global']
  49. # build model
  50. model = build_model(config['Architecture'])
  51. init_model(config, model, logger)
  52. # build post process
  53. post_process_class = build_post_process(config['PostProcess'])
  54. # create data ops
  55. transforms = []
  56. for op in config['Eval']['dataset']['transforms']:
  57. op_name = list(op)[0]
  58. if 'Label' in op_name:
  59. continue
  60. elif op_name == 'KeepKeys':
  61. op[op_name]['keep_keys'] = ['image', 'shape']
  62. transforms.append(op)
  63. ops = create_operators(transforms, global_config)
  64. save_res_path = config['Global']['save_res_path']
  65. if not os.path.exists(os.path.dirname(save_res_path)):
  66. os.makedirs(os.path.dirname(save_res_path))
  67. model.eval()
  68. with open(save_res_path, "wb") as fout:
  69. for file in get_image_file_list(config['Global']['infer_img']):
  70. logger.info("infer_img: {}".format(file))
  71. with open(file, 'rb') as f:
  72. img = f.read()
  73. data = {'image': img}
  74. batch = transform(data, ops)
  75. images = np.expand_dims(batch[0], axis=0)
  76. shape_list = np.expand_dims(batch[1], axis=0)
  77. images = paddle.to_tensor(images)
  78. preds = model(images)
  79. post_result = post_process_class(preds, shape_list)
  80. boxes = post_result[0]['points']
  81. # write result
  82. dt_boxes_json = []
  83. for box in boxes:
  84. tmp_json = {"transcription": ""}
  85. tmp_json['points'] = box.tolist()
  86. dt_boxes_json.append(tmp_json)
  87. otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n"
  88. fout.write(otstr.encode())
  89. src_img = cv2.imread(file)
  90. draw_det_res(boxes, config, src_img, file)
  91. logger.info("success!")
  92. if __name__ == '__main__':
  93. config, device, logger, vdl_writer = program.preprocess()
  94. main()