inference_realesrgan.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import argparse
  2. import cv2
  3. import glob
  4. import os
  5. from basicsr.archs.rrdbnet_arch import RRDBNet
  6. from realesrgan import RealESRGANer
  7. from realesrgan.archs.srvgg_arch import SRVGGNetCompact
  8. def main():
  9. """Inference demo for Real-ESRGAN.
  10. """
  11. parser = argparse.ArgumentParser()
  12. parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder')
  13. parser.add_argument(
  14. '-n',
  15. '--model_name',
  16. type=str,
  17. default='RealESRGAN_x4plus',
  18. help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus | '
  19. 'realesr-animevideov3 | realesr-general-x4v3 | realesr-general-wdn-x4v3'))
  20. parser.add_argument('-o', '--output', type=str, default='results', help='Output folder')
  21. parser.add_argument('--model_path', type=str, default=None, help='Model path')
  22. parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of the image')
  23. parser.add_argument('--suffix', type=str, default='out', help='Suffix of the restored image')
  24. parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no tile during testing')
  25. parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')
  26. parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')
  27. parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')
  28. parser.add_argument(
  29. '--fp32', action='store_true', help='Use fp32 precision during inference. Default: fp16 (half precision).')
  30. parser.add_argument(
  31. '--alpha_upsampler',
  32. type=str,
  33. default='realesrgan',
  34. help='The upsampler for the alpha channels. Options: realesrgan | bicubic')
  35. parser.add_argument(
  36. '--ext',
  37. type=str,
  38. default='auto',
  39. help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')
  40. parser.add_argument(
  41. '-g', '--gpu-id', type=int, default=None, help='gpu device to use (default=None) can be 0,1,2 for multi-gpu')
  42. args = parser.parse_args()
  43. # determine models according to model names
  44. args.model_name = args.model_name.split('.')[0]
  45. if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model
  46. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
  47. netscale = 4
  48. elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks
  49. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
  50. netscale = 4
  51. elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model
  52. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
  53. netscale = 2
  54. elif args.model_name in ['realesr-animevideov3']: # x4 VGG-style model (XS size)
  55. model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
  56. netscale = 4
  57. elif args.model_name in ['realesr-general-x4v3', 'realesr-general-wdn-x4v3']: # x4 VGG-style model (S size)
  58. model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
  59. netscale = 4
  60. # determine model paths
  61. if args.model_path is not None:
  62. model_path = args.model_path
  63. else:
  64. model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth')
  65. if not os.path.isfile(model_path):
  66. model_path = os.path.join('realesrgan/weights', args.model_name + '.pth')
  67. if not os.path.isfile(model_path):
  68. raise ValueError(f'Model {args.model_name} does not exist.')
  69. # restorer
  70. upsampler = RealESRGANer(
  71. scale=netscale,
  72. model_path=model_path,
  73. model=model,
  74. tile=args.tile,
  75. tile_pad=args.tile_pad,
  76. pre_pad=args.pre_pad,
  77. half=not args.fp32,
  78. gpu_id=args.gpu_id)
  79. if args.face_enhance: # Use GFPGAN for face enhancement
  80. from gfpgan import GFPGANer
  81. face_enhancer = GFPGANer(
  82. model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth',
  83. upscale=args.outscale,
  84. arch='clean',
  85. channel_multiplier=2,
  86. bg_upsampler=upsampler)
  87. os.makedirs(args.output, exist_ok=True)
  88. if os.path.isfile(args.input):
  89. paths = [args.input]
  90. else:
  91. paths = sorted(glob.glob(os.path.join(args.input, '*')))
  92. for idx, path in enumerate(paths):
  93. imgname, extension = os.path.splitext(os.path.basename(path))
  94. print('Testing', idx, imgname)
  95. img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
  96. if len(img.shape) == 3 and img.shape[2] == 4:
  97. img_mode = 'RGBA'
  98. else:
  99. img_mode = None
  100. try:
  101. if args.face_enhance:
  102. _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
  103. else:
  104. output, _ = upsampler.enhance(img, outscale=args.outscale)
  105. except RuntimeError as error:
  106. print('Error', error)
  107. print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
  108. else:
  109. if args.ext == 'auto':
  110. extension = extension[1:]
  111. else:
  112. extension = args.ext
  113. if img_mode == 'RGBA': # RGBA images should be saved in png format
  114. extension = 'png'
  115. if args.suffix == '':
  116. save_path = os.path.join(args.output, f'{imgname}.{extension}')
  117. else:
  118. save_path = os.path.join(args.output, f'{imgname}_{args.suffix}.{extension}')
  119. cv2.imwrite(save_path, output)
  120. if __name__ == '__main__':
  121. main()