inference_realesrgan.py 5.2 KB

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