predict_e2e.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 sys
  24. import tools.infer.utility as utility
  25. from ppocr.utils.logging import get_logger
  26. from ppocr.utils.utility import get_image_file_list, check_and_read
  27. from ppocr.data import create_operators, transform
  28. from ppocr.postprocess import build_post_process
  29. logger = get_logger()
  30. class TextE2E(object):
  31. def __init__(self, args):
  32. self.args = args
  33. self.e2e_algorithm = args.e2e_algorithm
  34. self.use_onnx = args.use_onnx
  35. pre_process_list = [{
  36. 'E2EResizeForTest': {}
  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', 'shape']
  49. }
  50. }]
  51. postprocess_params = {}
  52. if self.e2e_algorithm == "PGNet":
  53. pre_process_list[0] = {
  54. 'E2EResizeForTest': {
  55. 'max_side_len': args.e2e_limit_side_len,
  56. 'valid_set': 'totaltext'
  57. }
  58. }
  59. postprocess_params['name'] = 'PGPostProcess'
  60. postprocess_params["score_thresh"] = args.e2e_pgnet_score_thresh
  61. postprocess_params["character_dict_path"] = args.e2e_char_dict_path
  62. postprocess_params["valid_set"] = args.e2e_pgnet_valid_set
  63. postprocess_params["mode"] = args.e2e_pgnet_mode
  64. else:
  65. logger.info("unknown e2e_algorithm:{}".format(self.e2e_algorithm))
  66. sys.exit(0)
  67. self.preprocess_op = create_operators(pre_process_list)
  68. self.postprocess_op = build_post_process(postprocess_params)
  69. self.predictor, self.input_tensor, self.output_tensors, _ = utility.create_predictor(
  70. args, 'e2e', logger) # paddle.jit.load(args.det_model_dir)
  71. # self.predictor.eval()
  72. def clip_det_res(self, points, img_height, img_width):
  73. for pno in range(points.shape[0]):
  74. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  75. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  76. return points
  77. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  78. img_height, img_width = image_shape[0:2]
  79. dt_boxes_new = []
  80. for box in dt_boxes:
  81. box = self.clip_det_res(box, img_height, img_width)
  82. dt_boxes_new.append(box)
  83. dt_boxes = np.array(dt_boxes_new)
  84. return dt_boxes
  85. def __call__(self, img):
  86. ori_im = img.copy()
  87. data = {'image': img}
  88. data = transform(data, self.preprocess_op)
  89. img, shape_list = data
  90. if img is None:
  91. return None, 0
  92. img = np.expand_dims(img, axis=0)
  93. shape_list = np.expand_dims(shape_list, axis=0)
  94. img = img.copy()
  95. starttime = time.time()
  96. if self.use_onnx:
  97. input_dict = {}
  98. input_dict[self.input_tensor.name] = img
  99. outputs = self.predictor.run(self.output_tensors, input_dict)
  100. preds = {}
  101. preds['f_border'] = outputs[0]
  102. preds['f_char'] = outputs[1]
  103. preds['f_direction'] = outputs[2]
  104. preds['f_score'] = outputs[3]
  105. else:
  106. self.input_tensor.copy_from_cpu(img)
  107. self.predictor.run()
  108. outputs = []
  109. for output_tensor in self.output_tensors:
  110. output = output_tensor.copy_to_cpu()
  111. outputs.append(output)
  112. preds = {}
  113. if self.e2e_algorithm == 'PGNet':
  114. preds['f_border'] = outputs[0]
  115. preds['f_char'] = outputs[1]
  116. preds['f_direction'] = outputs[2]
  117. preds['f_score'] = outputs[3]
  118. else:
  119. raise NotImplementedError
  120. post_result = self.postprocess_op(preds, shape_list)
  121. points, strs = post_result['points'], post_result['texts']
  122. dt_boxes = self.filter_tag_det_res_only_clip(points, ori_im.shape)
  123. elapse = time.time() - starttime
  124. return dt_boxes, strs, elapse
  125. if __name__ == "__main__":
  126. args = utility.parse_args()
  127. image_file_list = get_image_file_list(args.image_dir)
  128. text_detector = TextE2E(args)
  129. count = 0
  130. total_time = 0
  131. draw_img_save = "./inference_results"
  132. if not os.path.exists(draw_img_save):
  133. os.makedirs(draw_img_save)
  134. for image_file in image_file_list:
  135. img, flag, _ = check_and_read(image_file)
  136. if not flag:
  137. img = cv2.imread(image_file)
  138. if img is None:
  139. logger.info("error in loading image:{}".format(image_file))
  140. continue
  141. points, strs, elapse = text_detector(img)
  142. if count > 0:
  143. total_time += elapse
  144. count += 1
  145. logger.info("Predict time of {}: {}".format(image_file, elapse))
  146. src_im = utility.draw_e2e_res(points, strs, image_file)
  147. img_name_pure = os.path.split(image_file)[-1]
  148. img_path = os.path.join(draw_img_save,
  149. "e2e_res_{}".format(img_name_pure))
  150. cv2.imwrite(img_path, src_im)
  151. logger.info("The visualized image saved in {}".format(img_path))
  152. if count > 1:
  153. logger.info("Avg Time: {}".format(total_time / (count - 1)))