inference_realesrgan.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. parser.add_argument(
  40. '-g', '--gpu-id', type=int, default=None, help='gpu device to use (default=None) can be 0,1,2 for multi-gpu')
  41. args = parser.parse_args()
  42. # determine models according to model names
  43. args.model_name = args.model_name.split('.')[0]
  44. if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model
  45. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
  46. netscale = 4
  47. elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks
  48. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
  49. netscale = 4
  50. elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model
  51. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
  52. netscale = 2
  53. elif args.model_name in ['realesr-animevideov3']: # x4 VGG-style model (XS size)
  54. model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
  55. netscale = 4
  56. # determine model paths
  57. model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth')
  58. if not os.path.isfile(model_path):
  59. model_path = os.path.join('realesrgan/weights', args.model_name + '.pth')
  60. if not os.path.isfile(model_path):
  61. raise ValueError(f'Model {args.model_name} does not exist.')
  62. # restorer
  63. upsampler = RealESRGANer(
  64. scale=netscale,
  65. model_path=model_path,
  66. model=model,
  67. tile=args.tile,
  68. tile_pad=args.tile_pad,
  69. pre_pad=args.pre_pad,
  70. half=not args.fp32,
  71. gpu_id=args.gpu_id)
  72. if args.face_enhance: # Use GFPGAN for face enhancement
  73. from gfpgan import GFPGANer
  74. face_enhancer = GFPGANer(
  75. model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth',
  76. upscale=args.outscale,
  77. arch='clean',
  78. channel_multiplier=2,
  79. bg_upsampler=upsampler)
  80. os.makedirs(args.output, exist_ok=True)
  81. if os.path.isfile(args.input):
  82. paths = [args.input]
  83. else:
  84. paths = sorted(glob.glob(os.path.join(args.input, '*')))
  85. for idx, path in enumerate(paths):
  86. imgname, extension = os.path.splitext(os.path.basename(path))
  87. print('Testing', idx, imgname)
  88. img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
  89. if len(img.shape) == 3 and img.shape[2] == 4:
  90. img_mode = 'RGBA'
  91. else:
  92. img_mode = None
  93. try:
  94. if args.face_enhance:
  95. _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
  96. else:
  97. output, _ = upsampler.enhance(img, outscale=args.outscale)
  98. except RuntimeError as error:
  99. print('Error', error)
  100. print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
  101. else:
  102. if args.ext == 'auto':
  103. extension = extension[1:]
  104. else:
  105. extension = args.ext
  106. if img_mode == 'RGBA': # RGBA images should be saved in png format
  107. extension = 'png'
  108. if args.suffix == '':
  109. save_path = os.path.join(args.output, f'{imgname}.{extension}')
  110. else:
  111. save_path = os.path.join(args.output, f'{imgname}_{args.suffix}.{extension}')
  112. cv2.imwrite(save_path, output)
  113. if __name__ == '__main__':
  114. main()