infer_sr.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. import json
  21. from PIL import Image
  22. import cv2
  23. __dir__ = os.path.dirname(os.path.abspath(__file__))
  24. sys.path.insert(0, __dir__)
  25. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..')))
  26. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  27. import paddle
  28. from ppocr.data import create_operators, transform
  29. from ppocr.modeling.architectures import build_model
  30. from ppocr.postprocess import build_post_process
  31. from ppocr.utils.save_load import load_model
  32. from ppocr.utils.utility import get_image_file_list
  33. import tools.program as program
  34. def main():
  35. global_config = config['Global']
  36. # build post process
  37. post_process_class = build_post_process(config['PostProcess'],
  38. global_config)
  39. # sr transform
  40. config['Architecture']["Transform"]['infer_mode'] = True
  41. model = build_model(config['Architecture'])
  42. load_model(config, model)
  43. # create data ops
  44. transforms = []
  45. for op in config['Eval']['dataset']['transforms']:
  46. op_name = list(op)[0]
  47. if 'Label' in op_name:
  48. continue
  49. elif op_name in ['SRResize']:
  50. op[op_name]['infer_mode'] = True
  51. elif op_name == 'KeepKeys':
  52. op[op_name]['keep_keys'] = ['img_lr']
  53. transforms.append(op)
  54. global_config['infer_mode'] = True
  55. ops = create_operators(transforms, global_config)
  56. save_visual_path = config['Global'].get('save_visual', "infer_result/")
  57. if not os.path.exists(os.path.dirname(save_visual_path)):
  58. os.makedirs(os.path.dirname(save_visual_path))
  59. model.eval()
  60. for file in get_image_file_list(config['Global']['infer_img']):
  61. logger.info("infer_img: {}".format(file))
  62. img = Image.open(file).convert("RGB")
  63. data = {'image_lr': img}
  64. batch = transform(data, ops)
  65. images = np.expand_dims(batch[0], axis=0)
  66. images = paddle.to_tensor(images)
  67. preds = model(images)
  68. sr_img = preds["sr_img"][0]
  69. lr_img = preds["lr_img"][0]
  70. fm_sr = (sr_img.numpy() * 255).transpose(1, 2, 0).astype(np.uint8)
  71. fm_lr = (lr_img.numpy() * 255).transpose(1, 2, 0).astype(np.uint8)
  72. img_name_pure = os.path.split(file)[-1]
  73. cv2.imwrite("{}/sr_{}".format(save_visual_path, img_name_pure),
  74. fm_sr[:, :, ::-1])
  75. logger.info("The visualized image saved in infer_result/sr_{}".format(
  76. img_name_pure))
  77. logger.info("success!")
  78. if __name__ == '__main__':
  79. config, device, logger, vdl_writer = program.preprocess()
  80. main()