inference_realesrgan.py 7.6 KB

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