predict_sr.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. from PIL import Image
  17. __dir__ = os.path.dirname(os.path.abspath(__file__))
  18. sys.path.insert(0, __dir__)
  19. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "../..")))
  20. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  21. import cv2
  22. import numpy as np
  23. import math
  24. import time
  25. import traceback
  26. import paddle
  27. import tools.infer.utility as utility
  28. from ppocr.postprocess import build_post_process
  29. from ppocr.utils.logging import get_logger
  30. from ppocr.utils.utility import get_image_file_list, check_and_read
  31. logger = get_logger()
  32. class TextSR(object):
  33. def __init__(self, args):
  34. if os.path.exists(f"{args.sr_model_dir}/inference.yml"):
  35. model_config = utility.load_config(f"{args.sr_model_dir}/inference.yml")
  36. model_name = model_config.get("Global", {}).get("model_name", "")
  37. if model_name:
  38. raise ValueError(
  39. f"{model_name} is not supported. Please check if the model is supported by the PaddleOCR wheel."
  40. )
  41. self.sr_image_shape = [int(v) for v in args.sr_image_shape.split(",")]
  42. self.sr_batch_num = args.sr_batch_num
  43. (
  44. self.predictor,
  45. self.input_tensor,
  46. self.output_tensors,
  47. self.config,
  48. ) = utility.create_predictor(args, "sr", logger)
  49. self.benchmark = args.benchmark
  50. if args.benchmark:
  51. import auto_log
  52. pid = os.getpid()
  53. gpu_id = utility.get_infer_gpuid()
  54. self.autolog = auto_log.AutoLogger(
  55. model_name="sr",
  56. model_precision=args.precision,
  57. batch_size=args.sr_batch_num,
  58. data_shape="dynamic",
  59. save_path=None, # args.save_log_path,
  60. inference_config=self.config,
  61. pids=pid,
  62. process_name=None,
  63. gpu_ids=gpu_id if args.use_gpu else None,
  64. time_keys=["preprocess_time", "inference_time", "postprocess_time"],
  65. warmup=0,
  66. logger=logger,
  67. )
  68. def resize_norm_img(self, img):
  69. imgC, imgH, imgW = self.sr_image_shape
  70. img = img.resize((imgW // 2, imgH // 2), Image.BICUBIC)
  71. img_numpy = np.array(img).astype("float32")
  72. img_numpy = img_numpy.transpose((2, 0, 1)) / 255
  73. return img_numpy
  74. def __call__(self, img_list):
  75. img_num = len(img_list)
  76. batch_num = self.sr_batch_num
  77. st = time.time()
  78. st = time.time()
  79. all_result = [] * img_num
  80. if self.benchmark:
  81. self.autolog.times.start()
  82. for beg_img_no in range(0, img_num, batch_num):
  83. end_img_no = min(img_num, beg_img_no + batch_num)
  84. norm_img_batch = []
  85. imgC, imgH, imgW = self.sr_image_shape
  86. for ino in range(beg_img_no, end_img_no):
  87. norm_img = self.resize_norm_img(img_list[ino])
  88. norm_img = norm_img[np.newaxis, :]
  89. norm_img_batch.append(norm_img)
  90. norm_img_batch = np.concatenate(norm_img_batch)
  91. norm_img_batch = norm_img_batch.copy()
  92. if self.benchmark:
  93. self.autolog.times.stamp()
  94. self.input_tensor.copy_from_cpu(norm_img_batch)
  95. self.predictor.run()
  96. outputs = []
  97. for output_tensor in self.output_tensors:
  98. output = output_tensor.copy_to_cpu()
  99. outputs.append(output)
  100. if len(outputs) != 1:
  101. preds = outputs
  102. else:
  103. preds = outputs[0]
  104. all_result.append(outputs)
  105. if self.benchmark:
  106. self.autolog.times.end(stamp=True)
  107. return all_result, time.time() - st
  108. def main(args):
  109. image_file_list = get_image_file_list(args.image_dir)
  110. text_recognizer = TextSR(args)
  111. valid_image_file_list = []
  112. img_list = []
  113. # warmup 2 times
  114. if args.warmup:
  115. img = np.random.uniform(0, 255, [16, 64, 3]).astype(np.uint8)
  116. for i in range(2):
  117. res = text_recognizer([img] * int(args.sr_batch_num))
  118. for image_file in image_file_list:
  119. img, flag, _ = check_and_read(image_file)
  120. if not flag:
  121. img = Image.open(image_file).convert("RGB")
  122. if img is None:
  123. logger.info("error in loading image:{}".format(image_file))
  124. continue
  125. valid_image_file_list.append(image_file)
  126. img_list.append(img)
  127. try:
  128. preds, _ = text_recognizer(img_list)
  129. for beg_no in range(len(preds)):
  130. sr_img = preds[beg_no][1]
  131. lr_img = preds[beg_no][0]
  132. for i in range(sr_img.shape[0]):
  133. fm_sr = (sr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8)
  134. fm_lr = (lr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8)
  135. img_name_pure = os.path.split(
  136. valid_image_file_list[beg_no * args.sr_batch_num + i]
  137. )[-1]
  138. cv2.imwrite(
  139. "infer_result/sr_{}".format(img_name_pure), fm_sr[:, :, ::-1]
  140. )
  141. logger.info(
  142. "The visualized image saved in infer_result/sr_{}".format(
  143. img_name_pure
  144. )
  145. )
  146. except Exception as E:
  147. logger.info(traceback.format_exc())
  148. logger.info(E)
  149. exit()
  150. if args.benchmark:
  151. text_recognizer.autolog.report()
  152. if __name__ == "__main__":
  153. main(utility.parse_args())