infer_det.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. def draw_det_res_and_label(dt_boxes, classes, config, img, img_name, save_path):
  46. label_list = config["Global"]["label_list"]
  47. labels = []
  48. if label_list is not None:
  49. if isinstance(label_list, str):
  50. with open(label_list, "r+", encoding="utf-8") as f:
  51. for line in f.readlines():
  52. labels.append(line.replace("\n", ""))
  53. else:
  54. labels = label_list
  55. if len(dt_boxes) > 0:
  56. import cv2
  57. index = 0
  58. src_im = img
  59. for box in dt_boxes:
  60. box = box.astype(np.int32).reshape((-1, 1, 2))
  61. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  62. font = cv2.FONT_HERSHEY_SIMPLEX
  63. src_im = cv2.putText(src_im, labels[classes[index]], (box[0][0][0], box[0][0][1]), font, 0.5, (255, 0, 0), 1)
  64. index += 1
  65. if not os.path.exists(save_path):
  66. os.makedirs(save_path)
  67. save_path = os.path.join(save_path, os.path.basename(img_name))
  68. cv2.imwrite(save_path, src_im)
  69. logger.info("The detected Image saved in {}".format(save_path))
  70. @paddle.no_grad()
  71. def main():
  72. global_config = config['Global']
  73. if "num_classes" in global_config:
  74. config['Architecture']["Head"]['num_classes'] = global_config["num_classes"]
  75. # build model
  76. model = build_model(config['Architecture'])
  77. load_model(config, model)
  78. # build post process
  79. post_process_class = build_post_process(config['PostProcess'])
  80. # create data ops
  81. transforms = []
  82. for op in config['Eval']['dataset']['transforms']:
  83. op_name = list(op)[0]
  84. if 'Label' in op_name:
  85. continue
  86. elif op_name == 'KeepKeys':
  87. op[op_name]['keep_keys'] = ['image', 'shape']
  88. transforms.append(op)
  89. ops = create_operators(transforms, global_config)
  90. save_res_path = config['Global']['save_res_path']
  91. if not os.path.exists(os.path.dirname(save_res_path)):
  92. os.makedirs(os.path.dirname(save_res_path))
  93. model.eval()
  94. with open(save_res_path, "wb") as fout:
  95. for file in get_image_file_list(config['Global']['infer_img']):
  96. logger.info("infer_img: {}".format(file))
  97. with open(file, 'rb') as f:
  98. img = f.read()
  99. data = {'image': img}
  100. batch = transform(data, ops)
  101. images = np.expand_dims(batch[0], axis=0)
  102. shape_list = np.expand_dims(batch[1], axis=0)
  103. images = paddle.to_tensor(images)
  104. preds = model(images)
  105. post_result = post_process_class(preds, shape_list)
  106. src_img = cv2.imread(file)
  107. dt_boxes_json = []
  108. # parser boxes if post_result is dict
  109. if isinstance(post_result, dict):
  110. det_box_json = {}
  111. for k in post_result.keys():
  112. boxes = post_result[k][0]['points']
  113. dt_boxes_list = []
  114. for box in boxes:
  115. tmp_json = {"transcription": ""}
  116. tmp_json['points'] = np.array(box).tolist()
  117. dt_boxes_list.append(tmp_json)
  118. det_box_json[k] = dt_boxes_list
  119. save_det_path = os.path.dirname(config['Global'][
  120. 'save_res_path']) + "/det_results_{}/".format(k)
  121. draw_det_res(boxes, config, src_img, file, save_det_path)
  122. else:
  123. boxes = post_result[0]['points']
  124. dt_boxes_json = []
  125. # write result
  126. for box in boxes:
  127. tmp_json = {"transcription": ""}
  128. tmp_json['points'] = np.array(box).tolist()
  129. dt_boxes_json.append(tmp_json)
  130. save_det_path = os.path.dirname(config['Global'][
  131. 'save_res_path']) + "/det_results/"
  132. if "classes" in post_result[0]:
  133. draw_det_res_and_label(boxes, post_result[0]["classes"], config, src_img, file, save_det_path)
  134. else:
  135. draw_det_res(boxes, config, src_img, file, save_det_path)
  136. otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n"
  137. fout.write(otstr.encode())
  138. logger.info("success!")
  139. if __name__ == '__main__':
  140. config, device, logger, vdl_writer = program.preprocess()
  141. main()