predict_sr.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. self.sr_image_shape = [int(v) for v in args.sr_image_shape.split(",")]
  35. self.sr_batch_num = args.sr_batch_num
  36. self.predictor, self.input_tensor, self.output_tensors, self.config = \
  37. utility.create_predictor(args, 'sr', logger)
  38. self.benchmark = args.benchmark
  39. if args.benchmark:
  40. import auto_log
  41. pid = os.getpid()
  42. gpu_id = utility.get_infer_gpuid()
  43. self.autolog = auto_log.AutoLogger(
  44. model_name="sr",
  45. model_precision=args.precision,
  46. batch_size=args.sr_batch_num,
  47. data_shape="dynamic",
  48. save_path=None, #args.save_log_path,
  49. inference_config=self.config,
  50. pids=pid,
  51. process_name=None,
  52. gpu_ids=gpu_id if args.use_gpu else None,
  53. time_keys=[
  54. 'preprocess_time', 'inference_time', 'postprocess_time'
  55. ],
  56. warmup=0,
  57. logger=logger)
  58. def resize_norm_img(self, img):
  59. imgC, imgH, imgW = self.sr_image_shape
  60. img = img.resize((imgW // 2, imgH // 2), Image.BICUBIC)
  61. img_numpy = np.array(img).astype("float32")
  62. img_numpy = img_numpy.transpose((2, 0, 1)) / 255
  63. return img_numpy
  64. def __call__(self, img_list):
  65. img_num = len(img_list)
  66. batch_num = self.sr_batch_num
  67. st = time.time()
  68. st = time.time()
  69. all_result = [] * img_num
  70. if self.benchmark:
  71. self.autolog.times.start()
  72. for beg_img_no in range(0, img_num, batch_num):
  73. end_img_no = min(img_num, beg_img_no + batch_num)
  74. norm_img_batch = []
  75. imgC, imgH, imgW = self.sr_image_shape
  76. for ino in range(beg_img_no, end_img_no):
  77. norm_img = self.resize_norm_img(img_list[ino])
  78. norm_img = norm_img[np.newaxis, :]
  79. norm_img_batch.append(norm_img)
  80. norm_img_batch = np.concatenate(norm_img_batch)
  81. norm_img_batch = norm_img_batch.copy()
  82. if self.benchmark:
  83. self.autolog.times.stamp()
  84. self.input_tensor.copy_from_cpu(norm_img_batch)
  85. self.predictor.run()
  86. outputs = []
  87. for output_tensor in self.output_tensors:
  88. output = output_tensor.copy_to_cpu()
  89. outputs.append(output)
  90. if len(outputs) != 1:
  91. preds = outputs
  92. else:
  93. preds = outputs[0]
  94. all_result.append(outputs)
  95. if self.benchmark:
  96. self.autolog.times.end(stamp=True)
  97. return all_result, time.time() - st
  98. def main(args):
  99. image_file_list = get_image_file_list(args.image_dir)
  100. text_recognizer = TextSR(args)
  101. valid_image_file_list = []
  102. img_list = []
  103. # warmup 2 times
  104. if args.warmup:
  105. img = np.random.uniform(0, 255, [16, 64, 3]).astype(np.uint8)
  106. for i in range(2):
  107. res = text_recognizer([img] * int(args.sr_batch_num))
  108. for image_file in image_file_list:
  109. img, flag, _ = check_and_read(image_file)
  110. if not flag:
  111. img = Image.open(image_file).convert("RGB")
  112. if img is None:
  113. logger.info("error in loading image:{}".format(image_file))
  114. continue
  115. valid_image_file_list.append(image_file)
  116. img_list.append(img)
  117. try:
  118. preds, _ = text_recognizer(img_list)
  119. for beg_no in range(len(preds)):
  120. sr_img = preds[beg_no][1]
  121. lr_img = preds[beg_no][0]
  122. for i in (range(sr_img.shape[0])):
  123. fm_sr = (sr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8)
  124. fm_lr = (lr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8)
  125. img_name_pure = os.path.split(valid_image_file_list[
  126. beg_no * args.sr_batch_num + i])[-1]
  127. cv2.imwrite("infer_result/sr_{}".format(img_name_pure),
  128. fm_sr[:, :, ::-1])
  129. logger.info("The visualized image saved in infer_result/sr_{}".
  130. format(img_name_pure))
  131. except Exception as E:
  132. logger.info(traceback.format_exc())
  133. logger.info(E)
  134. exit()
  135. if args.benchmark:
  136. text_recognizer.autolog.report()
  137. if __name__ == "__main__":
  138. main(utility.parse_args())