swinir_model.py 6.0 KB

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