predict_e2e.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. if os.path.exists(f"{args.e2e_model_dir}/inference.yml"):
  33. model_config = utility.load_config(f"{args.e2e_model_dir}/inference.yml")
  34. model_name = model_config.get("Global", {}).get("model_name", "")
  35. if model_name:
  36. raise ValueError(
  37. f"{model_name} is not supported. Please check if the model is supported by the PaddleOCR wheel."
  38. )
  39. self.args = args
  40. self.e2e_algorithm = args.e2e_algorithm
  41. self.use_onnx = args.use_onnx
  42. pre_process_list = [
  43. {"E2EResizeForTest": {}},
  44. {
  45. "NormalizeImage": {
  46. "std": [0.229, 0.224, 0.225],
  47. "mean": [0.485, 0.456, 0.406],
  48. "scale": "1./255.",
  49. "order": "hwc",
  50. }
  51. },
  52. {"ToCHWImage": None},
  53. {"KeepKeys": {"keep_keys": ["image", "shape"]}},
  54. ]
  55. postprocess_params = {}
  56. if self.e2e_algorithm == "PGNet":
  57. pre_process_list[0] = {
  58. "E2EResizeForTest": {
  59. "max_side_len": args.e2e_limit_side_len,
  60. "valid_set": "totaltext",
  61. }
  62. }
  63. postprocess_params["name"] = "PGPostProcess"
  64. postprocess_params["score_thresh"] = args.e2e_pgnet_score_thresh
  65. postprocess_params["character_dict_path"] = args.e2e_char_dict_path
  66. postprocess_params["valid_set"] = args.e2e_pgnet_valid_set
  67. postprocess_params["mode"] = args.e2e_pgnet_mode
  68. else:
  69. logger.info("unknown e2e_algorithm:{}".format(self.e2e_algorithm))
  70. sys.exit(0)
  71. self.preprocess_op = create_operators(pre_process_list)
  72. self.postprocess_op = build_post_process(postprocess_params)
  73. (
  74. self.predictor,
  75. self.input_tensor,
  76. self.output_tensors,
  77. _,
  78. ) = utility.create_predictor(
  79. args, "e2e", logger
  80. ) # paddle.jit.load(args.det_model_dir)
  81. # self.predictor.eval()
  82. def clip_det_res(self, points, img_height, img_width):
  83. for pno in range(points.shape[0]):
  84. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  85. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  86. return points
  87. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  88. img_height, img_width = image_shape[0:2]
  89. dt_boxes_new = []
  90. for box in dt_boxes:
  91. box = self.clip_det_res(box, img_height, img_width)
  92. dt_boxes_new.append(box)
  93. dt_boxes = np.array(dt_boxes_new)
  94. return dt_boxes
  95. def __call__(self, img):
  96. ori_im = img.copy()
  97. data = {"image": img}
  98. data = transform(data, self.preprocess_op)
  99. img, shape_list = data
  100. if img is None:
  101. return None, 0
  102. img = np.expand_dims(img, axis=0)
  103. shape_list = np.expand_dims(shape_list, axis=0)
  104. img = img.copy()
  105. starttime = time.time()
  106. if self.use_onnx:
  107. input_dict = {}
  108. input_dict[self.input_tensor.name] = img
  109. outputs = self.predictor.run(self.output_tensors, input_dict)
  110. preds = {}
  111. preds["f_border"] = outputs[0]
  112. preds["f_char"] = outputs[1]
  113. preds["f_direction"] = outputs[2]
  114. preds["f_score"] = outputs[3]
  115. else:
  116. self.input_tensor.copy_from_cpu(img)
  117. self.predictor.run()
  118. outputs = []
  119. for output_tensor in self.output_tensors:
  120. output = output_tensor.copy_to_cpu()
  121. outputs.append(output)
  122. preds = {}
  123. if self.e2e_algorithm == "PGNet":
  124. preds["f_border"] = outputs[0]
  125. preds["f_char"] = outputs[1]
  126. preds["f_direction"] = outputs[2]
  127. preds["f_score"] = outputs[3]
  128. else:
  129. raise NotImplementedError
  130. post_result = self.postprocess_op(preds, shape_list)
  131. points, strs = post_result["points"], post_result["texts"]
  132. dt_boxes = self.filter_tag_det_res_only_clip(points, ori_im.shape)
  133. elapse = time.time() - starttime
  134. return dt_boxes, strs, elapse
  135. if __name__ == "__main__":
  136. args = utility.parse_args()
  137. image_file_list = get_image_file_list(args.image_dir)
  138. text_detector = TextE2E(args)
  139. count = 0
  140. total_time = 0
  141. draw_img_save = "./inference_results"
  142. if not os.path.exists(draw_img_save):
  143. os.makedirs(draw_img_save)
  144. for image_file in image_file_list:
  145. img, flag, _ = check_and_read(image_file)
  146. if not flag:
  147. img = cv2.imread(image_file)
  148. if img is None:
  149. logger.info("error in loading image:{}".format(image_file))
  150. continue
  151. points, strs, elapse = text_detector(img)
  152. if count > 0:
  153. total_time += elapse
  154. count += 1
  155. logger.info("Predict time of {}: {}".format(image_file, elapse))
  156. src_im = utility.draw_e2e_res(points, strs, image_file)
  157. img_name_pure = os.path.split(image_file)[-1]
  158. img_path = os.path.join(draw_img_save, "e2e_res_{}".format(img_name_pure))
  159. cv2.imwrite(img_path, src_im)
  160. logger.info("The visualized image saved in {}".format(img_path))
  161. if count > 1:
  162. logger.info("Avg Time: {}".format(total_time / (count - 1)))