inference_realesrgan.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. def main():
  8. """Inference demo for Real-ESRGAN.
  9. """
  10. parser = argparse.ArgumentParser()
  11. parser.add_argument('--input', type=str, default='inputs', help='Input image or folder')
  12. parser.add_argument(
  13. '--model_path',
  14. type=str,
  15. default='experiments/pretrained_models/RealESRGAN_x4plus.pth',
  16. help='Path to the pre-trained model')
  17. parser.add_argument('--output', type=str, default='results', help='Output folder')
  18. parser.add_argument('--netscale', type=int, default=4, help='Upsample scale factor of the network')
  19. parser.add_argument('--outscale', type=float, default=4, help='The final upsampling scale of the image')
  20. parser.add_argument('--suffix', type=str, default='out', help='Suffix of the restored image')
  21. parser.add_argument('--tile', type=int, default=0, help='Tile size, 0 for no tile during testing')
  22. parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')
  23. parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')
  24. parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')
  25. parser.add_argument('--half', action='store_true', help='Use half precision during inference')
  26. parser.add_argument('--block', type=int, default=23, help='num_block in RRDB')
  27. parser.add_argument(
  28. '--alpha_upsampler',
  29. type=str,
  30. default='realesrgan',
  31. help='The upsampler for the alpha channels. Options: realesrgan | bicubic')
  32. parser.add_argument(
  33. '--ext',
  34. type=str,
  35. default='auto',
  36. help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')
  37. args = parser.parse_args()
  38. if 'RealESRGAN_x4plus_anime_6B.pth' in args.model_path:
  39. args.block = 6
  40. elif 'RealESRGAN_x2plus.pth' in args.model_path:
  41. args.netscale = 2
  42. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=args.block, num_grow_ch=32, scale=args.netscale)
  43. upsampler = RealESRGANer(
  44. scale=args.netscale,
  45. model_path=args.model_path,
  46. model=model,
  47. tile=args.tile,
  48. tile_pad=args.tile_pad,
  49. pre_pad=args.pre_pad,
  50. half=args.half)
  51. if args.face_enhance: # Use GFPGAN for face enhancement
  52. from gfpgan import GFPGANer
  53. face_enhancer = GFPGANer(
  54. model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth',
  55. upscale=args.outscale,
  56. arch='clean',
  57. channel_multiplier=2,
  58. bg_upsampler=upsampler)
  59. os.makedirs(args.output, exist_ok=True)
  60. if os.path.isfile(args.input):
  61. paths = [args.input]
  62. else:
  63. paths = sorted(glob.glob(os.path.join(args.input, '*')))
  64. for idx, path in enumerate(paths):
  65. imgname, extension = os.path.splitext(os.path.basename(path))
  66. print('Testing', idx, imgname)
  67. img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
  68. if len(img.shape) == 3 and img.shape[2] == 4:
  69. img_mode = 'RGBA'
  70. else:
  71. img_mode = None
  72. # give warnings for too large/small images
  73. h, w = img.shape[0:2]
  74. if max(h, w) > 1000 and args.netscale == 4:
  75. import warnings
  76. warnings.warn('The input image is large, try X2 model for better performance.')
  77. if max(h, w) < 500 and args.netscale == 2:
  78. import warnings
  79. warnings.warn('The input image is small, try X4 model for better performance.')
  80. try:
  81. if args.face_enhance:
  82. _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
  83. else:
  84. output, _ = upsampler.enhance(img, outscale=args.outscale)
  85. except Exception as error:
  86. print('Error', error)
  87. print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
  88. else:
  89. if args.ext == 'auto':
  90. extension = extension[1:]
  91. else:
  92. extension = args.ext
  93. if img_mode == 'RGBA': # RGBA images should be saved in png format
  94. extension = 'png'
  95. save_path = os.path.join(args.output, f'{imgname}_{args.suffix}.{extension}')
  96. cv2.imwrite(save_path, output)
  97. if __name__ == '__main__':
  98. main()