swinir_model.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import os
  2. import numpy as np
  3. import torch
  4. from PIL import Image
  5. from basicsr.utils.download_util import load_file_from_url
  6. from tqdm import tqdm
  7. from modules import modelloader, devices, script_callbacks, shared
  8. from modules.shared import opts, state
  9. from swinir_model_arch import SwinIR as net
  10. from swinir_model_arch_v2 import Swin2SR as net2
  11. from modules.upscaler import Upscaler, UpscalerData
  12. device_swinir = devices.get_device_for('swinir')
  13. class UpscalerSwinIR(Upscaler):
  14. def __init__(self, dirname):
  15. self.name = "SwinIR"
  16. self.model_url = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0" \
  17. "/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR" \
  18. "-L_x4_GAN.pth "
  19. self.model_name = "SwinIR 4x"
  20. self.user_path = dirname
  21. super().__init__()
  22. scalers = []
  23. model_files = self.find_models(ext_filter=[".pt", ".pth"])
  24. for model in model_files:
  25. if "http" in model:
  26. name = self.model_name
  27. else:
  28. name = modelloader.friendly_name(model)
  29. model_data = UpscalerData(name, model, self)
  30. scalers.append(model_data)
  31. self.scalers = scalers
  32. def do_upscale(self, img, model_file):
  33. model = self.load_model(model_file)
  34. if model is None:
  35. return img
  36. model = model.to(device_swinir, dtype=devices.dtype)
  37. img = upscale(img, model)
  38. try:
  39. torch.cuda.empty_cache()
  40. except Exception:
  41. pass
  42. return img
  43. def load_model(self, path, scale=4):
  44. if "http" in path:
  45. dl_name = "%s%s" % (self.model_name.replace(" ", "_"), ".pth")
  46. filename = load_file_from_url(url=path, model_dir=self.model_path, file_name=dl_name, progress=True)
  47. else:
  48. filename = path
  49. if filename is None or not os.path.exists(filename):
  50. return None
  51. if filename.endswith(".v2.pth"):
  52. model = net2(
  53. upscale=scale,
  54. in_chans=3,
  55. img_size=64,
  56. window_size=8,
  57. img_range=1.0,
  58. depths=[6, 6, 6, 6, 6, 6],
  59. embed_dim=180,
  60. num_heads=[6, 6, 6, 6, 6, 6],
  61. mlp_ratio=2,
  62. upsampler="nearest+conv",
  63. resi_connection="1conv",
  64. )
  65. params = None
  66. else:
  67. model = net(
  68. upscale=scale,
  69. in_chans=3,
  70. img_size=64,
  71. window_size=8,
  72. img_range=1.0,
  73. depths=[6, 6, 6, 6, 6, 6, 6, 6, 6],
  74. embed_dim=240,
  75. num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
  76. mlp_ratio=2,
  77. upsampler="nearest+conv",
  78. resi_connection="3conv",
  79. )
  80. params = "params_ema"
  81. pretrained_model = torch.load(filename)
  82. if params is not None:
  83. model.load_state_dict(pretrained_model[params], strict=True)
  84. else:
  85. model.load_state_dict(pretrained_model, strict=True)
  86. return model
  87. def upscale(
  88. img,
  89. model,
  90. tile=None,
  91. tile_overlap=None,
  92. window_size=8,
  93. scale=4,
  94. ):
  95. tile = tile or opts.SWIN_tile
  96. tile_overlap = tile_overlap or opts.SWIN_tile_overlap
  97. img = np.array(img)
  98. img = img[:, :, ::-1]
  99. img = np.moveaxis(img, 2, 0) / 255
  100. img = torch.from_numpy(img).float()
  101. img = img.unsqueeze(0).to(device_swinir, dtype=devices.dtype)
  102. with torch.no_grad(), devices.autocast():
  103. _, _, h_old, w_old = img.size()
  104. h_pad = (h_old // window_size + 1) * window_size - h_old
  105. w_pad = (w_old // window_size + 1) * window_size - w_old
  106. img = torch.cat([img, torch.flip(img, [2])], 2)[:, :, : h_old + h_pad, :]
  107. img = torch.cat([img, torch.flip(img, [3])], 3)[:, :, :, : w_old + w_pad]
  108. output = inference(img, model, tile, tile_overlap, window_size, scale)
  109. output = output[..., : h_old * scale, : w_old * scale]
  110. output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
  111. if output.ndim == 3:
  112. output = np.transpose(
  113. output[[2, 1, 0], :, :], (1, 2, 0)
  114. ) # CHW-RGB to HCW-BGR
  115. output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
  116. return Image.fromarray(output, "RGB")
  117. def inference(img, model, tile, tile_overlap, window_size, scale):
  118. # test the image tile by tile
  119. b, c, h, w = img.size()
  120. tile = min(tile, h, w)
  121. assert tile % window_size == 0, "tile size should be a multiple of window_size"
  122. sf = scale
  123. stride = tile - tile_overlap
  124. h_idx_list = list(range(0, h - tile, stride)) + [h - tile]
  125. w_idx_list = list(range(0, w - tile, stride)) + [w - tile]
  126. E = torch.zeros(b, c, h * sf, w * sf, dtype=devices.dtype, device=device_swinir).type_as(img)
  127. W = torch.zeros_like(E, dtype=devices.dtype, device=device_swinir)
  128. with tqdm(total=len(h_idx_list) * len(w_idx_list), desc="SwinIR tiles") as pbar:
  129. for h_idx in h_idx_list:
  130. if state.interrupted or state.skipped:
  131. break
  132. for w_idx in w_idx_list:
  133. if state.interrupted or state.skipped:
  134. break
  135. in_patch = img[..., h_idx: h_idx + tile, w_idx: w_idx + tile]
  136. out_patch = model(in_patch)
  137. out_patch_mask = torch.ones_like(out_patch)
  138. E[
  139. ..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
  140. ].add_(out_patch)
  141. W[
  142. ..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
  143. ].add_(out_patch_mask)
  144. pbar.update(1)
  145. output = E.div_(W)
  146. return output
  147. def on_ui_settings():
  148. import gradio as gr
  149. shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
  150. shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling")))
  151. script_callbacks.on_ui_settings(on_ui_settings)