infer_det.py 4.7 KB

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