jjourney1125 commited on
Commit
19bb687
1 Parent(s): 603bf25

Init commit

Browse files
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import torch
6
+
7
+ model_path = 'experiments/pretrained_models/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth'
8
+
9
+ if os.path.exists(model_path):
10
+ print(f'loading model from {model_path}')
11
+ else:
12
+ os.makedirs(os.path.dirname(model_path), exist_ok=True)
13
+ url = 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/{}'.format(os.path.basename(model_path))
14
+ r = requests.get(url, allow_redirects=True)
15
+ print(f'downloading model {model_path}')
16
+ open(model_path, 'wb').write(r.content)
17
+
18
+ os.makedirs("test", exist_ok=True)
19
+
20
+ def inference(img):
21
+
22
+ cv2.imwrite("test/1.png", cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
23
+ # basewidth = 256
24
+ # wpercent = (basewidth/float(img.size[0]))
25
+ # hsize = int((float(img.size[1])*float(wpercent)))
26
+ # img = img.resize((basewidth,hsize), Image.ANTIALIAS)
27
+ #img.save("test/1.jpg", "JPEG")
28
+ os.system('python main_test_swin2sr.py --task real_sr --model_path experiments/pretrained_models/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth --folder_lq test --scale 4')
29
+ return 'results/swin2sr_real_sr_x4/1_Swin2SR.png'
30
+
31
+ title = "Swin2SR"
32
+ description = "Gradio demo for Swin2SR."
33
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2209.11345' target='_blank'>Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration></a> | <a href='https://github.com/mv-lab/swin2sr' target='_blank'>Github Repo</a></p>"
34
+
35
+ examples=[['butterflyx4.png']]
36
+ gr.Interface(
37
+ inference,
38
+ "image",
39
+ "image",
40
+ title=title,
41
+ description=description,
42
+ article=article,
43
+ examples=examples,
44
+ ).launch(enable_queue=True,
45
+ share=True)
butterflyx4.png ADDED
main_test_swin2sr.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import cv2
3
+ import glob
4
+ import numpy as np
5
+ from collections import OrderedDict
6
+ import os
7
+ import torch
8
+ import requests
9
+
10
+ from models.network_swin2sr import Swin2SR as net
11
+ from utils import util_calculate_psnr_ssim as util
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument('--task', type=str, default='color_dn', help='classical_sr, lightweight_sr, real_sr, '
17
+ 'gray_dn, color_dn, jpeg_car, color_jpeg_car')
18
+ parser.add_argument('--scale', type=int, default=1, help='scale factor: 1, 2, 3, 4, 8') # 1 for dn and jpeg car
19
+ parser.add_argument('--noise', type=int, default=15, help='noise level: 15, 25, 50')
20
+ parser.add_argument('--jpeg', type=int, default=40, help='scale factor: 10, 20, 30, 40')
21
+ parser.add_argument('--training_patch_size', type=int, default=128, help='patch size used in training Swin2SR. '
22
+ 'Just used to differentiate two different settings in Table 2 of the paper. '
23
+ 'Images are NOT tested patch by patch.')
24
+ parser.add_argument('--large_model', action='store_true', help='use large model, only provided for real image sr')
25
+ parser.add_argument('--model_path', type=str,
26
+ default='model_zoo/swin2sr/Swin2SR_ClassicalSR_X2_64.pth')
27
+ parser.add_argument('--folder_lq', type=str, default=None, help='input low-quality test image folder')
28
+ parser.add_argument('--folder_gt', type=str, default=None, help='input ground-truth test image folder')
29
+ parser.add_argument('--tile', type=int, default=None, help='Tile size, None for no tile during testing (testing as a whole)')
30
+ parser.add_argument('--tile_overlap', type=int, default=32, help='Overlapping of different tiles')
31
+ parser.add_argument('--save_img_only', default=False, action='store_true', help='save image and do not evaluate')
32
+ args = parser.parse_args()
33
+
34
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
35
+ # set up model
36
+ if os.path.exists(args.model_path):
37
+ print(f'loading model from {args.model_path}')
38
+ else:
39
+ os.makedirs(os.path.dirname(args.model_path), exist_ok=True)
40
+ url = 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/{}'.format(os.path.basename(args.model_path))
41
+ r = requests.get(url, allow_redirects=True)
42
+ print(f'downloading model {args.model_path}')
43
+ open(args.model_path, 'wb').write(r.content)
44
+
45
+ model = define_model(args)
46
+ model.eval()
47
+ model = model.to(device)
48
+
49
+ # setup folder and path
50
+ folder, save_dir, border, window_size = setup(args)
51
+ os.makedirs(save_dir, exist_ok=True)
52
+ test_results = OrderedDict()
53
+ test_results['psnr'] = []
54
+ test_results['ssim'] = []
55
+ test_results['psnr_y'] = []
56
+ test_results['ssim_y'] = []
57
+ test_results['psnrb'] = []
58
+ test_results['psnrb_y'] = []
59
+ psnr, ssim, psnr_y, ssim_y, psnrb, psnrb_y = 0, 0, 0, 0, 0, 0
60
+
61
+ for idx, path in enumerate(sorted(glob.glob(os.path.join(folder, '*')))):
62
+ # read image
63
+ imgname, img_lq, img_gt = get_image_pair(args, path) # image to HWC-BGR, float32
64
+ img_lq = np.transpose(img_lq if img_lq.shape[2] == 1 else img_lq[:, :, [2, 1, 0]], (2, 0, 1)) # HCW-BGR to CHW-RGB
65
+ img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(device) # CHW-RGB to NCHW-RGB
66
+
67
+ # inference
68
+ with torch.no_grad():
69
+ # pad input image to be a multiple of window_size
70
+ _, _, h_old, w_old = img_lq.size()
71
+ h_pad = (h_old // window_size + 1) * window_size - h_old
72
+ w_pad = (w_old // window_size + 1) * window_size - w_old
73
+ img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]
74
+ img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]
75
+ output = test(img_lq, model, args, window_size)
76
+
77
+ if args.task == 'compressed_sr':
78
+ output = output[0][..., :h_old * args.scale, :w_old * args.scale]
79
+ else:
80
+ output = output[..., :h_old * args.scale, :w_old * args.scale]
81
+
82
+ # save image
83
+ output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
84
+ if output.ndim == 3:
85
+ output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR
86
+ output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
87
+ cv2.imwrite(f'{save_dir}/{imgname}_Swin2SR.png', output)
88
+
89
+
90
+ # evaluate psnr/ssim/psnr_b
91
+ if img_gt is not None:
92
+ img_gt = (img_gt * 255.0).round().astype(np.uint8) # float32 to uint8
93
+ img_gt = img_gt[:h_old * args.scale, :w_old * args.scale, ...] # crop gt
94
+ img_gt = np.squeeze(img_gt)
95
+
96
+ psnr = util.calculate_psnr(output, img_gt, crop_border=border)
97
+ ssim = util.calculate_ssim(output, img_gt, crop_border=border)
98
+ test_results['psnr'].append(psnr)
99
+ test_results['ssim'].append(ssim)
100
+ if img_gt.ndim == 3: # RGB image
101
+ psnr_y = util.calculate_psnr(output, img_gt, crop_border=border, test_y_channel=True)
102
+ ssim_y = util.calculate_ssim(output, img_gt, crop_border=border, test_y_channel=True)
103
+ test_results['psnr_y'].append(psnr_y)
104
+ test_results['ssim_y'].append(ssim_y)
105
+ if args.task in ['jpeg_car', 'color_jpeg_car']:
106
+ psnrb = util.calculate_psnrb(output, img_gt, crop_border=border, test_y_channel=False)
107
+ test_results['psnrb'].append(psnrb)
108
+ if args.task in ['color_jpeg_car']:
109
+ psnrb_y = util.calculate_psnrb(output, img_gt, crop_border=border, test_y_channel=True)
110
+ test_results['psnrb_y'].append(psnrb_y)
111
+ print('Testing {:d} {:20s} - PSNR: {:.2f} dB; SSIM: {:.4f}; PSNRB: {:.2f} dB;'
112
+ 'PSNR_Y: {:.2f} dB; SSIM_Y: {:.4f}; PSNRB_Y: {:.2f} dB.'.
113
+ format(idx, imgname, psnr, ssim, psnrb, psnr_y, ssim_y, psnrb_y))
114
+ else:
115
+ print('Testing {:d} {:20s}'.format(idx, imgname))
116
+
117
+ # summarize psnr/ssim
118
+ if img_gt is not None:
119
+ ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
120
+ ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
121
+ print('\n{} \n-- Average PSNR/SSIM(RGB): {:.2f} dB; {:.4f}'.format(save_dir, ave_psnr, ave_ssim))
122
+ if img_gt.ndim == 3:
123
+ ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
124
+ ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
125
+ print('-- Average PSNR_Y/SSIM_Y: {:.2f} dB; {:.4f}'.format(ave_psnr_y, ave_ssim_y))
126
+ if args.task in ['jpeg_car', 'color_jpeg_car']:
127
+ ave_psnrb = sum(test_results['psnrb']) / len(test_results['psnrb'])
128
+ print('-- Average PSNRB: {:.2f} dB'.format(ave_psnrb))
129
+ if args.task in ['color_jpeg_car']:
130
+ ave_psnrb_y = sum(test_results['psnrb_y']) / len(test_results['psnrb_y'])
131
+ print('-- Average PSNRB_Y: {:.2f} dB'.format(ave_psnrb_y))
132
+
133
+
134
+ def define_model(args):
135
+ # 001 classical image sr
136
+ if args.task == 'classical_sr':
137
+ model = net(upscale=args.scale, in_chans=3, img_size=args.training_patch_size, window_size=8,
138
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
139
+ mlp_ratio=2, upsampler='pixelshuffle', resi_connection='1conv')
140
+ param_key_g = 'params'
141
+
142
+ # 002 lightweight image sr
143
+ # use 'pixelshuffledirect' to save parameters
144
+ elif args.task in ['lightweight_sr']:
145
+ model = net(upscale=args.scale, in_chans=3, img_size=64, window_size=8,
146
+ img_range=1., depths=[6, 6, 6, 6], embed_dim=60, num_heads=[6, 6, 6, 6],
147
+ mlp_ratio=2, upsampler='pixelshuffledirect', resi_connection='1conv')
148
+ param_key_g = 'params'
149
+
150
+ elif args.task == 'compressed_sr':
151
+ model = net(upscale=args.scale, in_chans=3, img_size=args.training_patch_size, window_size=8,
152
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
153
+ mlp_ratio=2, upsampler='pixelshuffle_aux', resi_connection='1conv')
154
+ param_key_g = 'params'
155
+
156
+ # 003 real-world image sr
157
+ elif args.task == 'real_sr':
158
+ if not args.large_model:
159
+ # use 'nearest+conv' to avoid block artifacts
160
+ model = net(upscale=args.scale, in_chans=3, img_size=64, window_size=8,
161
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
162
+ mlp_ratio=2, upsampler='nearest+conv', resi_connection='1conv')
163
+ else:
164
+ # larger model size; use '3conv' to save parameters and memory; use ema for GAN training
165
+ model = net(upscale=args.scale, in_chans=3, img_size=64, window_size=8,
166
+ img_range=1., depths=[6, 6, 6, 6, 6, 6, 6, 6, 6], embed_dim=240,
167
+ num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
168
+ mlp_ratio=2, upsampler='nearest+conv', resi_connection='3conv')
169
+ param_key_g = 'params_ema'
170
+
171
+ # 006 grayscale JPEG compression artifact reduction
172
+ # use window_size=7 because JPEG encoding uses 8x8; use img_range=255 because it's sligtly better than 1
173
+ elif args.task == 'jpeg_car':
174
+ model = net(upscale=1, in_chans=1, img_size=126, window_size=7,
175
+ img_range=255., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
176
+ mlp_ratio=2, upsampler='', resi_connection='1conv')
177
+ param_key_g = 'params'
178
+
179
+ # 006 color JPEG compression artifact reduction
180
+ # use window_size=7 because JPEG encoding uses 8x8; use img_range=255 because it's sligtly better than 1
181
+ elif args.task == 'color_jpeg_car':
182
+ model = net(upscale=1, in_chans=3, img_size=126, window_size=7,
183
+ img_range=255., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
184
+ mlp_ratio=2, upsampler='', resi_connection='1conv')
185
+ param_key_g = 'params'
186
+
187
+ pretrained_model = torch.load(args.model_path)
188
+ model.load_state_dict(pretrained_model[param_key_g] if param_key_g in pretrained_model.keys() else pretrained_model, strict=True)
189
+
190
+ return model
191
+
192
+
193
+ def setup(args):
194
+ # 001 classical image sr/ 002 lightweight image sr
195
+ if args.task in ['classical_sr', 'lightweight_sr', 'compressed_sr']:
196
+ save_dir = f'results/swin2sr_{args.task}_x{args.scale}'
197
+ if args.save_img_only:
198
+ folder = args.folder_lq
199
+ else:
200
+ folder = args.folder_gt
201
+ border = args.scale
202
+ window_size = 8
203
+
204
+ # 003 real-world image sr
205
+ elif args.task in ['real_sr']:
206
+ save_dir = f'results/swin2sr_{args.task}_x{args.scale}'
207
+ if args.large_model:
208
+ save_dir += '_large'
209
+ folder = args.folder_lq
210
+ border = 0
211
+ window_size = 8
212
+
213
+ # 006 JPEG compression artifact reduction
214
+ elif args.task in ['jpeg_car', 'color_jpeg_car']:
215
+ save_dir = f'results/swin2sr_{args.task}_jpeg{args.jpeg}'
216
+ folder = args.folder_gt
217
+ border = 0
218
+ window_size = 7
219
+
220
+ return folder, save_dir, border, window_size
221
+
222
+
223
+ def get_image_pair(args, path):
224
+ (imgname, imgext) = os.path.splitext(os.path.basename(path))
225
+
226
+ # 001 classical image sr/ 002 lightweight image sr (load lq-gt image pairs)
227
+ if args.task in ['classical_sr', 'lightweight_sr']:
228
+ if args.save_img_only:
229
+ img_gt = None
230
+ img_lq = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
231
+ else:
232
+ img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
233
+ img_lq = cv2.imread(f'{args.folder_lq}/{imgname}x{args.scale}{imgext}', cv2.IMREAD_COLOR).astype(
234
+ np.float32) / 255.
235
+
236
+ elif args.task in ['compressed_sr']:
237
+ if args.save_img_only:
238
+ img_gt = None
239
+ img_lq = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
240
+ else:
241
+ img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
242
+ img_lq = cv2.imread(f'{args.folder_lq}/{imgname}.jpg', cv2.IMREAD_COLOR).astype(
243
+ np.float32) / 255.
244
+
245
+ # 003 real-world image sr (load lq image only)
246
+ elif args.task in ['real_sr', 'lightweight_sr_infer']:
247
+ img_gt = None
248
+ img_lq = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
249
+
250
+ # 006 grayscale JPEG compression artifact reduction (load gt image and generate lq image on-the-fly)
251
+ elif args.task in ['jpeg_car']:
252
+ img_gt = cv2.imread(path, cv2.IMREAD_UNCHANGED)
253
+ if img_gt.ndim != 2:
254
+ img_gt = util.bgr2ycbcr(img_gt, y_only=True)
255
+ result, encimg = cv2.imencode('.jpg', img_gt, [int(cv2.IMWRITE_JPEG_QUALITY), args.jpeg])
256
+ img_lq = cv2.imdecode(encimg, 0)
257
+ img_gt = np.expand_dims(img_gt, axis=2).astype(np.float32) / 255.
258
+ img_lq = np.expand_dims(img_lq, axis=2).astype(np.float32) / 255.
259
+
260
+ # 006 JPEG compression artifact reduction (load gt image and generate lq image on-the-fly)
261
+ elif args.task in ['color_jpeg_car']:
262
+ img_gt = cv2.imread(path)
263
+ result, encimg = cv2.imencode('.jpg', img_gt, [int(cv2.IMWRITE_JPEG_QUALITY), args.jpeg])
264
+ img_lq = cv2.imdecode(encimg, 1)
265
+ img_gt = img_gt.astype(np.float32)/ 255.
266
+ img_lq = img_lq.astype(np.float32)/ 255.
267
+
268
+ return imgname, img_lq, img_gt
269
+
270
+
271
+ def test(img_lq, model, args, window_size):
272
+ if args.tile is None:
273
+ # test the image as a whole
274
+ output = model(img_lq)
275
+ else:
276
+ # test the image tile by tile
277
+ b, c, h, w = img_lq.size()
278
+ tile = min(args.tile, h, w)
279
+ assert tile % window_size == 0, "tile size should be a multiple of window_size"
280
+ tile_overlap = args.tile_overlap
281
+ sf = args.scale
282
+
283
+ stride = tile - tile_overlap
284
+ h_idx_list = list(range(0, h-tile, stride)) + [h-tile]
285
+ w_idx_list = list(range(0, w-tile, stride)) + [w-tile]
286
+ E = torch.zeros(b, c, h*sf, w*sf).type_as(img_lq)
287
+ W = torch.zeros_like(E)
288
+
289
+ for h_idx in h_idx_list:
290
+ for w_idx in w_idx_list:
291
+ in_patch = img_lq[..., h_idx:h_idx+tile, w_idx:w_idx+tile]
292
+ out_patch = model(in_patch)
293
+ out_patch_mask = torch.ones_like(out_patch)
294
+
295
+ E[..., h_idx*sf:(h_idx+tile)*sf, w_idx*sf:(w_idx+tile)*sf].add_(out_patch)
296
+ W[..., h_idx*sf:(h_idx+tile)*sf, w_idx*sf:(w_idx+tile)*sf].add_(out_patch_mask)
297
+ output = E.div_(W)
298
+
299
+ return output
300
+
301
+ if __name__ == '__main__':
302
+ main()
models/network_swin2sr.py ADDED
@@ -0,0 +1,1010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------------
2
+ # Swin2SR: Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration, https://arxiv.org/abs/
3
+ # Written by Conde and Choi et al.
4
+ # -----------------------------------------------------------------------------------
5
+
6
+ import math
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint as checkpoint
12
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
13
+
14
+
15
+ class Mlp(nn.Module):
16
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
17
+ super().__init__()
18
+ out_features = out_features or in_features
19
+ hidden_features = hidden_features or in_features
20
+ self.fc1 = nn.Linear(in_features, hidden_features)
21
+ self.act = act_layer()
22
+ self.fc2 = nn.Linear(hidden_features, out_features)
23
+ self.drop = nn.Dropout(drop)
24
+
25
+ def forward(self, x):
26
+ x = self.fc1(x)
27
+ x = self.act(x)
28
+ x = self.drop(x)
29
+ x = self.fc2(x)
30
+ x = self.drop(x)
31
+ return x
32
+
33
+
34
+ def window_partition(x, window_size):
35
+ """
36
+ Args:
37
+ x: (B, H, W, C)
38
+ window_size (int): window size
39
+ Returns:
40
+ windows: (num_windows*B, window_size, window_size, C)
41
+ """
42
+ B, H, W, C = x.shape
43
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
44
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
45
+ return windows
46
+
47
+
48
+ def window_reverse(windows, window_size, H, W):
49
+ """
50
+ Args:
51
+ windows: (num_windows*B, window_size, window_size, C)
52
+ window_size (int): Window size
53
+ H (int): Height of image
54
+ W (int): Width of image
55
+ Returns:
56
+ x: (B, H, W, C)
57
+ """
58
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
59
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
60
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
61
+ return x
62
+
63
+ class WindowAttention(nn.Module):
64
+ r""" Window based multi-head self attention (W-MSA) module with relative position bias.
65
+ It supports both of shifted and non-shifted window.
66
+ Args:
67
+ dim (int): Number of input channels.
68
+ window_size (tuple[int]): The height and width of the window.
69
+ num_heads (int): Number of attention heads.
70
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
71
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
72
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
73
+ pretrained_window_size (tuple[int]): The height and width of the window in pre-training.
74
+ """
75
+
76
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.,
77
+ pretrained_window_size=[0, 0]):
78
+
79
+ super().__init__()
80
+ self.dim = dim
81
+ self.window_size = window_size # Wh, Ww
82
+ self.pretrained_window_size = pretrained_window_size
83
+ self.num_heads = num_heads
84
+
85
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True)
86
+
87
+ # mlp to generate continuous relative position bias
88
+ self.cpb_mlp = nn.Sequential(nn.Linear(2, 512, bias=True),
89
+ nn.ReLU(inplace=True),
90
+ nn.Linear(512, num_heads, bias=False))
91
+
92
+ # get relative_coords_table
93
+ relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32)
94
+ relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32)
95
+ relative_coords_table = torch.stack(
96
+ torch.meshgrid([relative_coords_h,
97
+ relative_coords_w])).permute(1, 2, 0).contiguous().unsqueeze(0) # 1, 2*Wh-1, 2*Ww-1, 2
98
+ if pretrained_window_size[0] > 0:
99
+ relative_coords_table[:, :, :, 0] /= (pretrained_window_size[0] - 1)
100
+ relative_coords_table[:, :, :, 1] /= (pretrained_window_size[1] - 1)
101
+ else:
102
+ relative_coords_table[:, :, :, 0] /= (self.window_size[0] - 1)
103
+ relative_coords_table[:, :, :, 1] /= (self.window_size[1] - 1)
104
+ relative_coords_table *= 8 # normalize to -8, 8
105
+ relative_coords_table = torch.sign(relative_coords_table) * torch.log2(
106
+ torch.abs(relative_coords_table) + 1.0) / np.log2(8)
107
+
108
+ self.register_buffer("relative_coords_table", relative_coords_table)
109
+
110
+ # get pair-wise relative position index for each token inside the window
111
+ coords_h = torch.arange(self.window_size[0])
112
+ coords_w = torch.arange(self.window_size[1])
113
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
114
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
115
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
116
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
117
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
118
+ relative_coords[:, :, 1] += self.window_size[1] - 1
119
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
120
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
121
+ self.register_buffer("relative_position_index", relative_position_index)
122
+
123
+ self.qkv = nn.Linear(dim, dim * 3, bias=False)
124
+ if qkv_bias:
125
+ self.q_bias = nn.Parameter(torch.zeros(dim))
126
+ self.v_bias = nn.Parameter(torch.zeros(dim))
127
+ else:
128
+ self.q_bias = None
129
+ self.v_bias = None
130
+ self.attn_drop = nn.Dropout(attn_drop)
131
+ self.proj = nn.Linear(dim, dim)
132
+ self.proj_drop = nn.Dropout(proj_drop)
133
+ self.softmax = nn.Softmax(dim=-1)
134
+
135
+ def forward(self, x, mask=None):
136
+ """
137
+ Args:
138
+ x: input features with shape of (num_windows*B, N, C)
139
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
140
+ """
141
+ B_, N, C = x.shape
142
+ qkv_bias = None
143
+ if self.q_bias is not None:
144
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
145
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
146
+ qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
147
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
148
+
149
+ # cosine attention
150
+ attn = (F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1))
151
+ logit_scale = torch.clamp(self.logit_scale, max=torch.log(torch.tensor(1. / 0.01)).to(self.logit_scale.device)).exp()
152
+ attn = attn * logit_scale
153
+
154
+ relative_position_bias_table = self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads)
155
+ relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
156
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
157
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
158
+ relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
159
+ attn = attn + relative_position_bias.unsqueeze(0)
160
+
161
+ if mask is not None:
162
+ nW = mask.shape[0]
163
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
164
+ attn = attn.view(-1, self.num_heads, N, N)
165
+ attn = self.softmax(attn)
166
+ else:
167
+ attn = self.softmax(attn)
168
+
169
+ attn = self.attn_drop(attn)
170
+
171
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
172
+ x = self.proj(x)
173
+ x = self.proj_drop(x)
174
+ return x
175
+
176
+ def extra_repr(self) -> str:
177
+ return f'dim={self.dim}, window_size={self.window_size}, ' \
178
+ f'pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}'
179
+
180
+ def flops(self, N):
181
+ # calculate flops for 1 window with token length of N
182
+ flops = 0
183
+ # qkv = self.qkv(x)
184
+ flops += N * self.dim * 3 * self.dim
185
+ # attn = (q @ k.transpose(-2, -1))
186
+ flops += self.num_heads * N * (self.dim // self.num_heads) * N
187
+ # x = (attn @ v)
188
+ flops += self.num_heads * N * N * (self.dim // self.num_heads)
189
+ # x = self.proj(x)
190
+ flops += N * self.dim * self.dim
191
+ return flops
192
+
193
+ class SwinTransformerBlock(nn.Module):
194
+ r""" Swin Transformer Block.
195
+ Args:
196
+ dim (int): Number of input channels.
197
+ input_resolution (tuple[int]): Input resulotion.
198
+ num_heads (int): Number of attention heads.
199
+ window_size (int): Window size.
200
+ shift_size (int): Shift size for SW-MSA.
201
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
202
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
203
+ drop (float, optional): Dropout rate. Default: 0.0
204
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
205
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
206
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
207
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
208
+ pretrained_window_size (int): Window size in pre-training.
209
+ """
210
+
211
+ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
212
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0.,
213
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm, pretrained_window_size=0):
214
+ super().__init__()
215
+ self.dim = dim
216
+ self.input_resolution = input_resolution
217
+ self.num_heads = num_heads
218
+ self.window_size = window_size
219
+ self.shift_size = shift_size
220
+ self.mlp_ratio = mlp_ratio
221
+ if min(self.input_resolution) <= self.window_size:
222
+ # if window size is larger than input resolution, we don't partition windows
223
+ self.shift_size = 0
224
+ self.window_size = min(self.input_resolution)
225
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
226
+
227
+ self.norm1 = norm_layer(dim)
228
+ self.attn = WindowAttention(
229
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
230
+ qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
231
+ pretrained_window_size=to_2tuple(pretrained_window_size))
232
+
233
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
234
+ self.norm2 = norm_layer(dim)
235
+ mlp_hidden_dim = int(dim * mlp_ratio)
236
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
237
+
238
+ if self.shift_size > 0:
239
+ attn_mask = self.calculate_mask(self.input_resolution)
240
+ else:
241
+ attn_mask = None
242
+
243
+ self.register_buffer("attn_mask", attn_mask)
244
+
245
+ def calculate_mask(self, x_size):
246
+ # calculate attention mask for SW-MSA
247
+ H, W = x_size
248
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
249
+ h_slices = (slice(0, -self.window_size),
250
+ slice(-self.window_size, -self.shift_size),
251
+ slice(-self.shift_size, None))
252
+ w_slices = (slice(0, -self.window_size),
253
+ slice(-self.window_size, -self.shift_size),
254
+ slice(-self.shift_size, None))
255
+ cnt = 0
256
+ for h in h_slices:
257
+ for w in w_slices:
258
+ img_mask[:, h, w, :] = cnt
259
+ cnt += 1
260
+
261
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
262
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
263
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
264
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
265
+
266
+ return attn_mask
267
+
268
+ def forward(self, x, x_size):
269
+ H, W = x_size
270
+ B, L, C = x.shape
271
+ #assert L == H * W, "input feature has wrong size"
272
+
273
+ shortcut = x
274
+ x = x.view(B, H, W, C)
275
+
276
+ # cyclic shift
277
+ if self.shift_size > 0:
278
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
279
+ else:
280
+ shifted_x = x
281
+
282
+ # partition windows
283
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
284
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
285
+
286
+ # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
287
+ if self.input_resolution == x_size:
288
+ attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
289
+ else:
290
+ attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
291
+
292
+ # merge windows
293
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
294
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
295
+
296
+ # reverse cyclic shift
297
+ if self.shift_size > 0:
298
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
299
+ else:
300
+ x = shifted_x
301
+ x = x.view(B, H * W, C)
302
+ x = shortcut + self.drop_path(self.norm1(x))
303
+
304
+ # FFN
305
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
306
+
307
+ return x
308
+
309
+ def extra_repr(self) -> str:
310
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
311
+ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
312
+
313
+ def flops(self):
314
+ flops = 0
315
+ H, W = self.input_resolution
316
+ # norm1
317
+ flops += self.dim * H * W
318
+ # W-MSA/SW-MSA
319
+ nW = H * W / self.window_size / self.window_size
320
+ flops += nW * self.attn.flops(self.window_size * self.window_size)
321
+ # mlp
322
+ flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
323
+ # norm2
324
+ flops += self.dim * H * W
325
+ return flops
326
+
327
+ class PatchMerging(nn.Module):
328
+ r""" Patch Merging Layer.
329
+ Args:
330
+ input_resolution (tuple[int]): Resolution of input feature.
331
+ dim (int): Number of input channels.
332
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
333
+ """
334
+
335
+ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
336
+ super().__init__()
337
+ self.input_resolution = input_resolution
338
+ self.dim = dim
339
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
340
+ self.norm = norm_layer(2 * dim)
341
+
342
+ def forward(self, x):
343
+ """
344
+ x: B, H*W, C
345
+ """
346
+ H, W = self.input_resolution
347
+ B, L, C = x.shape
348
+ assert L == H * W, "input feature has wrong size"
349
+ assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
350
+
351
+ x = x.view(B, H, W, C)
352
+
353
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
354
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
355
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
356
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
357
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
358
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
359
+
360
+ x = self.reduction(x)
361
+ x = self.norm(x)
362
+
363
+ return x
364
+
365
+ def extra_repr(self) -> str:
366
+ return f"input_resolution={self.input_resolution}, dim={self.dim}"
367
+
368
+ def flops(self):
369
+ H, W = self.input_resolution
370
+ flops = (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
371
+ flops += H * W * self.dim // 2
372
+ return flops
373
+
374
+ class BasicLayer(nn.Module):
375
+ """ A basic Swin Transformer layer for one stage.
376
+ Args:
377
+ dim (int): Number of input channels.
378
+ input_resolution (tuple[int]): Input resolution.
379
+ depth (int): Number of blocks.
380
+ num_heads (int): Number of attention heads.
381
+ window_size (int): Local window size.
382
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
383
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
384
+ drop (float, optional): Dropout rate. Default: 0.0
385
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
386
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
387
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
388
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
389
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
390
+ pretrained_window_size (int): Local window size in pre-training.
391
+ """
392
+
393
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
394
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
395
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
396
+ pretrained_window_size=0):
397
+
398
+ super().__init__()
399
+ self.dim = dim
400
+ self.input_resolution = input_resolution
401
+ self.depth = depth
402
+ self.use_checkpoint = use_checkpoint
403
+
404
+ # build blocks
405
+ self.blocks = nn.ModuleList([
406
+ SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
407
+ num_heads=num_heads, window_size=window_size,
408
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
409
+ mlp_ratio=mlp_ratio,
410
+ qkv_bias=qkv_bias,
411
+ drop=drop, attn_drop=attn_drop,
412
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
413
+ norm_layer=norm_layer,
414
+ pretrained_window_size=pretrained_window_size)
415
+ for i in range(depth)])
416
+
417
+ # patch merging layer
418
+ if downsample is not None:
419
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
420
+ else:
421
+ self.downsample = None
422
+
423
+ def forward(self, x, x_size):
424
+ for blk in self.blocks:
425
+ if self.use_checkpoint:
426
+ x = checkpoint.checkpoint(blk, x, x_size)
427
+ else:
428
+ x = blk(x, x_size)
429
+ if self.downsample is not None:
430
+ x = self.downsample(x)
431
+ return x
432
+
433
+ def extra_repr(self) -> str:
434
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
435
+
436
+ def flops(self):
437
+ flops = 0
438
+ for blk in self.blocks:
439
+ flops += blk.flops()
440
+ if self.downsample is not None:
441
+ flops += self.downsample.flops()
442
+ return flops
443
+
444
+ def _init_respostnorm(self):
445
+ for blk in self.blocks:
446
+ nn.init.constant_(blk.norm1.bias, 0)
447
+ nn.init.constant_(blk.norm1.weight, 0)
448
+ nn.init.constant_(blk.norm2.bias, 0)
449
+ nn.init.constant_(blk.norm2.weight, 0)
450
+
451
+ class PatchEmbed(nn.Module):
452
+ r""" Image to Patch Embedding
453
+ Args:
454
+ img_size (int): Image size. Default: 224.
455
+ patch_size (int): Patch token size. Default: 4.
456
+ in_chans (int): Number of input image channels. Default: 3.
457
+ embed_dim (int): Number of linear projection output channels. Default: 96.
458
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
459
+ """
460
+
461
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
462
+ super().__init__()
463
+ img_size = to_2tuple(img_size)
464
+ patch_size = to_2tuple(patch_size)
465
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
466
+ self.img_size = img_size
467
+ self.patch_size = patch_size
468
+ self.patches_resolution = patches_resolution
469
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
470
+
471
+ self.in_chans = in_chans
472
+ self.embed_dim = embed_dim
473
+
474
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
475
+ if norm_layer is not None:
476
+ self.norm = norm_layer(embed_dim)
477
+ else:
478
+ self.norm = None
479
+
480
+ def forward(self, x):
481
+ B, C, H, W = x.shape
482
+ # FIXME look at relaxing size constraints
483
+ # assert H == self.img_size[0] and W == self.img_size[1],
484
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
485
+ x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C
486
+ if self.norm is not None:
487
+ x = self.norm(x)
488
+ return x
489
+
490
+ def flops(self):
491
+ Ho, Wo = self.patches_resolution
492
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
493
+ if self.norm is not None:
494
+ flops += Ho * Wo * self.embed_dim
495
+ return flops
496
+
497
+ class RSTB(nn.Module):
498
+ """Residual Swin Transformer Block (RSTB).
499
+ Args:
500
+ dim (int): Number of input channels.
501
+ input_resolution (tuple[int]): Input resolution.
502
+ depth (int): Number of blocks.
503
+ num_heads (int): Number of attention heads.
504
+ window_size (int): Local window size.
505
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
506
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
507
+ drop (float, optional): Dropout rate. Default: 0.0
508
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
509
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
510
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
511
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
512
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
513
+ img_size: Input image size.
514
+ patch_size: Patch size.
515
+ resi_connection: The convolutional block before residual connection.
516
+ """
517
+
518
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
519
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
520
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
521
+ img_size=224, patch_size=4, resi_connection='1conv'):
522
+ super(RSTB, self).__init__()
523
+
524
+ self.dim = dim
525
+ self.input_resolution = input_resolution
526
+
527
+ self.residual_group = BasicLayer(dim=dim,
528
+ input_resolution=input_resolution,
529
+ depth=depth,
530
+ num_heads=num_heads,
531
+ window_size=window_size,
532
+ mlp_ratio=mlp_ratio,
533
+ qkv_bias=qkv_bias,
534
+ drop=drop, attn_drop=attn_drop,
535
+ drop_path=drop_path,
536
+ norm_layer=norm_layer,
537
+ downsample=downsample,
538
+ use_checkpoint=use_checkpoint)
539
+
540
+ if resi_connection == '1conv':
541
+ self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
542
+ elif resi_connection == '3conv':
543
+ # to save parameters and memory
544
+ self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
545
+ nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
546
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
547
+ nn.Conv2d(dim // 4, dim, 3, 1, 1))
548
+
549
+ self.patch_embed = PatchEmbed(
550
+ img_size=img_size, patch_size=patch_size, in_chans=dim, embed_dim=dim,
551
+ norm_layer=None)
552
+
553
+ self.patch_unembed = PatchUnEmbed(
554
+ img_size=img_size, patch_size=patch_size, in_chans=dim, embed_dim=dim,
555
+ norm_layer=None)
556
+
557
+ def forward(self, x, x_size):
558
+ return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
559
+
560
+ def flops(self):
561
+ flops = 0
562
+ flops += self.residual_group.flops()
563
+ H, W = self.input_resolution
564
+ flops += H * W * self.dim * self.dim * 9
565
+ flops += self.patch_embed.flops()
566
+ flops += self.patch_unembed.flops()
567
+
568
+ return flops
569
+
570
+ class PatchUnEmbed(nn.Module):
571
+ r""" Image to Patch Unembedding
572
+ Args:
573
+ img_size (int): Image size. Default: 224.
574
+ patch_size (int): Patch token size. Default: 4.
575
+ in_chans (int): Number of input image channels. Default: 3.
576
+ embed_dim (int): Number of linear projection output channels. Default: 96.
577
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
578
+ """
579
+
580
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
581
+ super().__init__()
582
+ img_size = to_2tuple(img_size)
583
+ patch_size = to_2tuple(patch_size)
584
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
585
+ self.img_size = img_size
586
+ self.patch_size = patch_size
587
+ self.patches_resolution = patches_resolution
588
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
589
+
590
+ self.in_chans = in_chans
591
+ self.embed_dim = embed_dim
592
+
593
+ def forward(self, x, x_size):
594
+ B, HW, C = x.shape
595
+ x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
596
+ return x
597
+
598
+ def flops(self):
599
+ flops = 0
600
+ return flops
601
+
602
+
603
+ class Upsample(nn.Sequential):
604
+ """Upsample module.
605
+ Args:
606
+ scale (int): Scale factor. Supported scales: 2^n and 3.
607
+ num_feat (int): Channel number of intermediate features.
608
+ """
609
+
610
+ def __init__(self, scale, num_feat):
611
+ m = []
612
+ if (scale & (scale - 1)) == 0: # scale = 2^n
613
+ for _ in range(int(math.log(scale, 2))):
614
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
615
+ m.append(nn.PixelShuffle(2))
616
+ elif scale == 3:
617
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
618
+ m.append(nn.PixelShuffle(3))
619
+ else:
620
+ raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
621
+ super(Upsample, self).__init__(*m)
622
+
623
+ class Upsample_hf(nn.Sequential):
624
+ """Upsample module.
625
+ Args:
626
+ scale (int): Scale factor. Supported scales: 2^n and 3.
627
+ num_feat (int): Channel number of intermediate features.
628
+ """
629
+
630
+ def __init__(self, scale, num_feat):
631
+ m = []
632
+ if (scale & (scale - 1)) == 0: # scale = 2^n
633
+ for _ in range(int(math.log(scale, 2))):
634
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
635
+ m.append(nn.PixelShuffle(2))
636
+ elif scale == 3:
637
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
638
+ m.append(nn.PixelShuffle(3))
639
+ else:
640
+ raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
641
+ super(Upsample_hf, self).__init__(*m)
642
+
643
+
644
+ class UpsampleOneStep(nn.Sequential):
645
+ """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
646
+ Used in lightweight SR to save parameters.
647
+ Args:
648
+ scale (int): Scale factor. Supported scales: 2^n and 3.
649
+ num_feat (int): Channel number of intermediate features.
650
+ """
651
+
652
+ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
653
+ self.num_feat = num_feat
654
+ self.input_resolution = input_resolution
655
+ m = []
656
+ m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
657
+ m.append(nn.PixelShuffle(scale))
658
+ super(UpsampleOneStep, self).__init__(*m)
659
+
660
+ def flops(self):
661
+ H, W = self.input_resolution
662
+ flops = H * W * self.num_feat * 3 * 9
663
+ return flops
664
+
665
+
666
+
667
+ class Swin2SR(nn.Module):
668
+ r""" Swin2SR
669
+ A PyTorch impl of : `Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration`.
670
+ Args:
671
+ img_size (int | tuple(int)): Input image size. Default 64
672
+ patch_size (int | tuple(int)): Patch size. Default: 1
673
+ in_chans (int): Number of input image channels. Default: 3
674
+ embed_dim (int): Patch embedding dimension. Default: 96
675
+ depths (tuple(int)): Depth of each Swin Transformer layer.
676
+ num_heads (tuple(int)): Number of attention heads in different layers.
677
+ window_size (int): Window size. Default: 7
678
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
679
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
680
+ drop_rate (float): Dropout rate. Default: 0
681
+ attn_drop_rate (float): Attention dropout rate. Default: 0
682
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
683
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
684
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
685
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
686
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
687
+ upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
688
+ img_range: Image range. 1. or 255.
689
+ upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
690
+ resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
691
+ """
692
+
693
+ def __init__(self, img_size=64, patch_size=1, in_chans=3,
694
+ embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
695
+ window_size=7, mlp_ratio=4., qkv_bias=True,
696
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
697
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
698
+ use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
699
+ **kwargs):
700
+ super(Swin2SR, self).__init__()
701
+ num_in_ch = in_chans
702
+ num_out_ch = in_chans
703
+ num_feat = 64
704
+ self.img_range = img_range
705
+ if in_chans == 3:
706
+ rgb_mean = (0.4488, 0.4371, 0.4040)
707
+ self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
708
+ else:
709
+ self.mean = torch.zeros(1, 1, 1, 1)
710
+ self.upscale = upscale
711
+ self.upsampler = upsampler
712
+ self.window_size = window_size
713
+
714
+ #####################################################################################################
715
+ ################################### 1, shallow feature extraction ###################################
716
+ self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
717
+
718
+ #####################################################################################################
719
+ ################################### 2, deep feature extraction ######################################
720
+ self.num_layers = len(depths)
721
+ self.embed_dim = embed_dim
722
+ self.ape = ape
723
+ self.patch_norm = patch_norm
724
+ self.num_features = embed_dim
725
+ self.mlp_ratio = mlp_ratio
726
+
727
+ # split image into non-overlapping patches
728
+ self.patch_embed = PatchEmbed(
729
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
730
+ norm_layer=norm_layer if self.patch_norm else None)
731
+ num_patches = self.patch_embed.num_patches
732
+ patches_resolution = self.patch_embed.patches_resolution
733
+ self.patches_resolution = patches_resolution
734
+
735
+ # merge non-overlapping patches into image
736
+ self.patch_unembed = PatchUnEmbed(
737
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
738
+ norm_layer=norm_layer if self.patch_norm else None)
739
+
740
+ # absolute position embedding
741
+ if self.ape:
742
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
743
+ trunc_normal_(self.absolute_pos_embed, std=.02)
744
+
745
+ self.pos_drop = nn.Dropout(p=drop_rate)
746
+
747
+ # stochastic depth
748
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
749
+
750
+ # build Residual Swin Transformer blocks (RSTB)
751
+ self.layers = nn.ModuleList()
752
+ for i_layer in range(self.num_layers):
753
+ layer = RSTB(dim=embed_dim,
754
+ input_resolution=(patches_resolution[0],
755
+ patches_resolution[1]),
756
+ depth=depths[i_layer],
757
+ num_heads=num_heads[i_layer],
758
+ window_size=window_size,
759
+ mlp_ratio=self.mlp_ratio,
760
+ qkv_bias=qkv_bias,
761
+ drop=drop_rate, attn_drop=attn_drop_rate,
762
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
763
+ norm_layer=norm_layer,
764
+ downsample=None,
765
+ use_checkpoint=use_checkpoint,
766
+ img_size=img_size,
767
+ patch_size=patch_size,
768
+ resi_connection=resi_connection
769
+
770
+ )
771
+ self.layers.append(layer)
772
+
773
+ if self.upsampler == 'pixelshuffle_hf':
774
+ self.layers_hf = nn.ModuleList()
775
+ for i_layer in range(self.num_layers):
776
+ layer = RSTB(dim=embed_dim,
777
+ input_resolution=(patches_resolution[0],
778
+ patches_resolution[1]),
779
+ depth=depths[i_layer],
780
+ num_heads=num_heads[i_layer],
781
+ window_size=window_size,
782
+ mlp_ratio=self.mlp_ratio,
783
+ qkv_bias=qkv_bias,
784
+ drop=drop_rate, attn_drop=attn_drop_rate,
785
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
786
+ norm_layer=norm_layer,
787
+ downsample=None,
788
+ use_checkpoint=use_checkpoint,
789
+ img_size=img_size,
790
+ patch_size=patch_size,
791
+ resi_connection=resi_connection
792
+
793
+ )
794
+ self.layers_hf.append(layer)
795
+
796
+ self.norm = norm_layer(self.num_features)
797
+
798
+ # build the last conv layer in deep feature extraction
799
+ if resi_connection == '1conv':
800
+ self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
801
+ elif resi_connection == '3conv':
802
+ # to save parameters and memory
803
+ self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
804
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
805
+ nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
806
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
807
+ nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
808
+
809
+ #####################################################################################################
810
+ ################################ 3, high quality image reconstruction ################################
811
+ if self.upsampler == 'pixelshuffle':
812
+ # for classical SR
813
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
814
+ nn.LeakyReLU(inplace=True))
815
+ self.upsample = Upsample(upscale, num_feat)
816
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
817
+ elif self.upsampler == 'pixelshuffle_aux':
818
+ self.conv_bicubic = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)
819
+ self.conv_before_upsample = nn.Sequential(
820
+ nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
821
+ nn.LeakyReLU(inplace=True))
822
+ self.conv_aux = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
823
+ self.conv_after_aux = nn.Sequential(
824
+ nn.Conv2d(3, num_feat, 3, 1, 1),
825
+ nn.LeakyReLU(inplace=True))
826
+ self.upsample = Upsample(upscale, num_feat)
827
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
828
+
829
+ elif self.upsampler == 'pixelshuffle_hf':
830
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
831
+ nn.LeakyReLU(inplace=True))
832
+ self.upsample = Upsample(upscale, num_feat)
833
+ self.upsample_hf = Upsample_hf(upscale, num_feat)
834
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
835
+ self.conv_first_hf = nn.Sequential(nn.Conv2d(num_feat, embed_dim, 3, 1, 1),
836
+ nn.LeakyReLU(inplace=True))
837
+ self.conv_after_body_hf = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
838
+ self.conv_before_upsample_hf = nn.Sequential(
839
+ nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
840
+ nn.LeakyReLU(inplace=True))
841
+ self.conv_last_hf = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
842
+
843
+ elif self.upsampler == 'pixelshuffledirect':
844
+ # for lightweight SR (to save parameters)
845
+ self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
846
+ (patches_resolution[0], patches_resolution[1]))
847
+ elif self.upsampler == 'nearest+conv':
848
+ # for real-world SR (less artifacts)
849
+ assert self.upscale == 4, 'only support x4 now.'
850
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
851
+ nn.LeakyReLU(inplace=True))
852
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
853
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
854
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
855
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
856
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
857
+ else:
858
+ # for image denoising and JPEG compression artifact reduction
859
+ self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
860
+
861
+ self.apply(self._init_weights)
862
+
863
+ def _init_weights(self, m):
864
+ if isinstance(m, nn.Linear):
865
+ trunc_normal_(m.weight, std=.02)
866
+ if isinstance(m, nn.Linear) and m.bias is not None:
867
+ nn.init.constant_(m.bias, 0)
868
+ elif isinstance(m, nn.LayerNorm):
869
+ nn.init.constant_(m.bias, 0)
870
+ nn.init.constant_(m.weight, 1.0)
871
+
872
+ @torch.jit.ignore
873
+ def no_weight_decay(self):
874
+ return {'absolute_pos_embed'}
875
+
876
+ @torch.jit.ignore
877
+ def no_weight_decay_keywords(self):
878
+ return {'relative_position_bias_table'}
879
+
880
+ def check_image_size(self, x):
881
+ _, _, h, w = x.size()
882
+ mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
883
+ mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
884
+ x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
885
+ return x
886
+
887
+ def forward_features(self, x):
888
+ x_size = (x.shape[2], x.shape[3])
889
+ x = self.patch_embed(x)
890
+ if self.ape:
891
+ x = x + self.absolute_pos_embed
892
+ x = self.pos_drop(x)
893
+
894
+ for layer in self.layers:
895
+ x = layer(x, x_size)
896
+
897
+ x = self.norm(x) # B L C
898
+ x = self.patch_unembed(x, x_size)
899
+
900
+ return x
901
+
902
+ def forward_features_hf(self, x):
903
+ x_size = (x.shape[2], x.shape[3])
904
+ x = self.patch_embed(x)
905
+ if self.ape:
906
+ x = x + self.absolute_pos_embed
907
+ x = self.pos_drop(x)
908
+
909
+ for layer in self.layers_hf:
910
+ x = layer(x, x_size)
911
+
912
+ x = self.norm(x) # B L C
913
+ x = self.patch_unembed(x, x_size)
914
+
915
+ return x
916
+
917
+ def forward(self, x):
918
+ H, W = x.shape[2:]
919
+ x = self.check_image_size(x)
920
+
921
+ self.mean = self.mean.type_as(x)
922
+ x = (x - self.mean) * self.img_range
923
+
924
+ if self.upsampler == 'pixelshuffle':
925
+ # for classical SR
926
+ x = self.conv_first(x)
927
+ x = self.conv_after_body(self.forward_features(x)) + x
928
+ x = self.conv_before_upsample(x)
929
+ x = self.conv_last(self.upsample(x))
930
+ elif self.upsampler == 'pixelshuffle_aux':
931
+ bicubic = F.interpolate(x, size=(H * self.upscale, W * self.upscale), mode='bicubic', align_corners=False)
932
+ bicubic = self.conv_bicubic(bicubic)
933
+ x = self.conv_first(x)
934
+ x = self.conv_after_body(self.forward_features(x)) + x
935
+ x = self.conv_before_upsample(x)
936
+ aux = self.conv_aux(x) # b, 3, LR_H, LR_W
937
+ x = self.conv_after_aux(aux)
938
+ x = self.upsample(x)[:, :, :H * self.upscale, :W * self.upscale] + bicubic[:, :, :H * self.upscale, :W * self.upscale]
939
+ x = self.conv_last(x)
940
+ aux = aux / self.img_range + self.mean
941
+ elif self.upsampler == 'pixelshuffle_hf':
942
+ # for classical SR with HF
943
+ x = self.conv_first(x)
944
+ x = self.conv_after_body(self.forward_features(x)) + x
945
+ x_before = self.conv_before_upsample(x)
946
+ x_out = self.conv_last(self.upsample(x_before))
947
+
948
+ x_hf = self.conv_first_hf(x_before)
949
+ x_hf = self.conv_after_body_hf(self.forward_features_hf(x_hf)) + x_hf
950
+ x_hf = self.conv_before_upsample_hf(x_hf)
951
+ x_hf = self.conv_last_hf(self.upsample_hf(x_hf))
952
+ x = x_out + x_hf
953
+ x_hf = x_hf / self.img_range + self.mean
954
+
955
+ elif self.upsampler == 'pixelshuffledirect':
956
+ # for lightweight SR
957
+ x = self.conv_first(x)
958
+ x = self.conv_after_body(self.forward_features(x)) + x
959
+ x = self.upsample(x)
960
+ elif self.upsampler == 'nearest+conv':
961
+ # for real-world SR
962
+ x = self.conv_first(x)
963
+ x = self.conv_after_body(self.forward_features(x)) + x
964
+ x = self.conv_before_upsample(x)
965
+ x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
966
+ x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
967
+ x = self.conv_last(self.lrelu(self.conv_hr(x)))
968
+ else:
969
+ # for image denoising and JPEG compression artifact reduction
970
+ x_first = self.conv_first(x)
971
+ res = self.conv_after_body(self.forward_features(x_first)) + x_first
972
+ x = x + self.conv_last(res)
973
+
974
+ x = x / self.img_range + self.mean
975
+ if self.upsampler == "pixelshuffle_aux":
976
+ return x[:, :, :H*self.upscale, :W*self.upscale], aux
977
+
978
+ elif self.upsampler == "pixelshuffle_hf":
979
+ x_out = x_out / self.img_range + self.mean
980
+ return x_out[:, :, :H*self.upscale, :W*self.upscale], x[:, :, :H*self.upscale, :W*self.upscale], x_hf[:, :, :H*self.upscale, :W*self.upscale]
981
+
982
+ else:
983
+ return x[:, :, :H*self.upscale, :W*self.upscale]
984
+
985
+ def flops(self):
986
+ flops = 0
987
+ H, W = self.patches_resolution
988
+ flops += H * W * 3 * self.embed_dim * 9
989
+ flops += self.patch_embed.flops()
990
+ for i, layer in enumerate(self.layers):
991
+ flops += layer.flops()
992
+ flops += H * W * 3 * self.embed_dim * self.embed_dim
993
+ flops += self.upsample.flops()
994
+ return flops
995
+
996
+
997
+ if __name__ == '__main__':
998
+ upscale = 4
999
+ window_size = 8
1000
+ height = (1024 // upscale // window_size + 1) * window_size
1001
+ width = (720 // upscale // window_size + 1) * window_size
1002
+ model = Swin2SR(upscale=2, img_size=(height, width),
1003
+ window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
1004
+ embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect')
1005
+ print(model)
1006
+ print(height, width, model.flops() / 1e9)
1007
+
1008
+ x = torch.randn((1, 3, height, width))
1009
+ x = model(x)
1010
+ print(x.shape)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ timm
2
+ numpy
3
+ torch
4
+ opencv-python-headless
5
+ Pillow
utils/util_calculate_psnr_ssim.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------------
2
+ # https://github.com/JingyunLiang/SwinIR/blob/main/utils/util_calculate_psnr_ssim.py
3
+ # -----------------------------------------------------------------------------------
4
+
5
+ import cv2
6
+ import torch
7
+ import numpy as np
8
+
9
+ def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
10
+ """Calculate PSNR (Peak Signal-to-Noise Ratio).
11
+ Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
12
+ Args:
13
+ img1 (ndarray): Images with range [0, 255].
14
+ img2 (ndarray): Images with range [0, 255].
15
+ crop_border (int): Cropped pixels in each edge of an image. These
16
+ pixels are not involved in the PSNR calculation.
17
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
18
+ Default: 'HWC'.
19
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
20
+ Returns:
21
+ float: psnr result.
22
+ """
23
+
24
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
25
+ if input_order not in ['HWC', 'CHW']:
26
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
27
+ img1 = reorder_image(img1, input_order=input_order)
28
+ img2 = reorder_image(img2, input_order=input_order)
29
+ img1 = img1.astype(np.float64)
30
+ img2 = img2.astype(np.float64)
31
+
32
+ if crop_border != 0:
33
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
34
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
35
+
36
+ if test_y_channel:
37
+ img1 = to_y_channel(img1)
38
+ img2 = to_y_channel(img2)
39
+
40
+ mse = np.mean((img1 - img2) ** 2)
41
+ if mse == 0:
42
+ return float('inf')
43
+ return 20. * np.log10(255. / np.sqrt(mse))
44
+
45
+
46
+ def _ssim(img1, img2):
47
+ """Calculate SSIM (structural similarity) for one channel images.
48
+ It is called by func:`calculate_ssim`.
49
+ Args:
50
+ img1 (ndarray): Images with range [0, 255] with order 'HWC'.
51
+ img2 (ndarray): Images with range [0, 255] with order 'HWC'.
52
+ Returns:
53
+ float: ssim result.
54
+ """
55
+
56
+ C1 = (0.01 * 255) ** 2
57
+ C2 = (0.03 * 255) ** 2
58
+
59
+ img1 = img1.astype(np.float64)
60
+ img2 = img2.astype(np.float64)
61
+ kernel = cv2.getGaussianKernel(11, 1.5)
62
+ window = np.outer(kernel, kernel.transpose())
63
+
64
+ mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
65
+ mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
66
+ mu1_sq = mu1 ** 2
67
+ mu2_sq = mu2 ** 2
68
+ mu1_mu2 = mu1 * mu2
69
+ sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
70
+ sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
71
+ sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
72
+
73
+ ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
74
+ return ssim_map.mean()
75
+
76
+
77
+ def calculate_ssim(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
78
+ """Calculate SSIM (structural similarity).
79
+ Ref:
80
+ Image quality assessment: From error visibility to structural similarity
81
+ The results are the same as that of the official released MATLAB code in
82
+ https://ece.uwaterloo.ca/~z70wang/research/ssim/.
83
+ For three-channel images, SSIM is calculated for each channel and then
84
+ averaged.
85
+ Args:
86
+ img1 (ndarray): Images with range [0, 255].
87
+ img2 (ndarray): Images with range [0, 255].
88
+ crop_border (int): Cropped pixels in each edge of an image. These
89
+ pixels are not involved in the SSIM calculation.
90
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
91
+ Default: 'HWC'.
92
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
93
+ Returns:
94
+ float: ssim result.
95
+ """
96
+
97
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
98
+ if input_order not in ['HWC', 'CHW']:
99
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
100
+ img1 = reorder_image(img1, input_order=input_order)
101
+ img2 = reorder_image(img2, input_order=input_order)
102
+ img1 = img1.astype(np.float64)
103
+ img2 = img2.astype(np.float64)
104
+
105
+ if crop_border != 0:
106
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
107
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
108
+
109
+ if test_y_channel:
110
+ img1 = to_y_channel(img1)
111
+ img2 = to_y_channel(img2)
112
+
113
+ ssims = []
114
+ for i in range(img1.shape[2]):
115
+ ssims.append(_ssim(img1[..., i], img2[..., i]))
116
+ return np.array(ssims).mean()
117
+
118
+
119
+ def _blocking_effect_factor(im):
120
+ block_size = 8
121
+
122
+ block_horizontal_positions = torch.arange(7, im.shape[3] - 1, 8)
123
+ block_vertical_positions = torch.arange(7, im.shape[2] - 1, 8)
124
+
125
+ horizontal_block_difference = (
126
+ (im[:, :, :, block_horizontal_positions] - im[:, :, :, block_horizontal_positions + 1]) ** 2).sum(
127
+ 3).sum(2).sum(1)
128
+ vertical_block_difference = (
129
+ (im[:, :, block_vertical_positions, :] - im[:, :, block_vertical_positions + 1, :]) ** 2).sum(3).sum(
130
+ 2).sum(1)
131
+
132
+ nonblock_horizontal_positions = np.setdiff1d(torch.arange(0, im.shape[3] - 1), block_horizontal_positions)
133
+ nonblock_vertical_positions = np.setdiff1d(torch.arange(0, im.shape[2] - 1), block_vertical_positions)
134
+
135
+ horizontal_nonblock_difference = (
136
+ (im[:, :, :, nonblock_horizontal_positions] - im[:, :, :, nonblock_horizontal_positions + 1]) ** 2).sum(
137
+ 3).sum(2).sum(1)
138
+ vertical_nonblock_difference = (
139
+ (im[:, :, nonblock_vertical_positions, :] - im[:, :, nonblock_vertical_positions + 1, :]) ** 2).sum(
140
+ 3).sum(2).sum(1)
141
+
142
+ n_boundary_horiz = im.shape[2] * (im.shape[3] // block_size - 1)
143
+ n_boundary_vert = im.shape[3] * (im.shape[2] // block_size - 1)
144
+ boundary_difference = (horizontal_block_difference + vertical_block_difference) / (
145
+ n_boundary_horiz + n_boundary_vert)
146
+
147
+ n_nonboundary_horiz = im.shape[2] * (im.shape[3] - 1) - n_boundary_horiz
148
+ n_nonboundary_vert = im.shape[3] * (im.shape[2] - 1) - n_boundary_vert
149
+ nonboundary_difference = (horizontal_nonblock_difference + vertical_nonblock_difference) / (
150
+ n_nonboundary_horiz + n_nonboundary_vert)
151
+
152
+ scaler = np.log2(block_size) / np.log2(min([im.shape[2], im.shape[3]]))
153
+ bef = scaler * (boundary_difference - nonboundary_difference)
154
+
155
+ bef[boundary_difference <= nonboundary_difference] = 0
156
+ return bef
157
+
158
+
159
+ def calculate_psnrb(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
160
+ """Calculate PSNR-B (Peak Signal-to-Noise Ratio).
161
+ Ref: Quality assessment of deblocked images, for JPEG image deblocking evaluation
162
+ # https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
163
+ Args:
164
+ img1 (ndarray): Images with range [0, 255].
165
+ img2 (ndarray): Images with range [0, 255].
166
+ crop_border (int): Cropped pixels in each edge of an image. These
167
+ pixels are not involved in the PSNR calculation.
168
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
169
+ Default: 'HWC'.
170
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
171
+ Returns:
172
+ float: psnr result.
173
+ """
174
+
175
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
176
+ if input_order not in ['HWC', 'CHW']:
177
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
178
+ img1 = reorder_image(img1, input_order=input_order)
179
+ img2 = reorder_image(img2, input_order=input_order)
180
+ img1 = img1.astype(np.float64)
181
+ img2 = img2.astype(np.float64)
182
+
183
+ if crop_border != 0:
184
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
185
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
186
+
187
+ if test_y_channel:
188
+ img1 = to_y_channel(img1)
189
+ img2 = to_y_channel(img2)
190
+
191
+ # follow https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
192
+ img1 = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0) / 255.
193
+ img2 = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0) / 255.
194
+
195
+ total = 0
196
+ for c in range(img1.shape[1]):
197
+ mse = torch.nn.functional.mse_loss(img1[:, c:c + 1, :, :], img2[:, c:c + 1, :, :], reduction='none')
198
+ bef = _blocking_effect_factor(img1[:, c:c + 1, :, :])
199
+
200
+ mse = mse.view(mse.shape[0], -1).mean(1)
201
+ total += 10 * torch.log10(1 / (mse + bef))
202
+
203
+ return float(total) / img1.shape[1]
204
+
205
+
206
+ def reorder_image(img, input_order='HWC'):
207
+ """Reorder images to 'HWC' order.
208
+ If the input_order is (h, w), return (h, w, 1);
209
+ If the input_order is (c, h, w), return (h, w, c);
210
+ If the input_order is (h, w, c), return as it is.
211
+ Args:
212
+ img (ndarray): Input image.
213
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
214
+ If the input image shape is (h, w), input_order will not have
215
+ effects. Default: 'HWC'.
216
+ Returns:
217
+ ndarray: reordered image.
218
+ """
219
+
220
+ if input_order not in ['HWC', 'CHW']:
221
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'")
222
+ if len(img.shape) == 2:
223
+ img = img[..., None]
224
+ if input_order == 'CHW':
225
+ img = img.transpose(1, 2, 0)
226
+ return img
227
+
228
+
229
+ def to_y_channel(img):
230
+ """Change to Y channel of YCbCr.
231
+ Args:
232
+ img (ndarray): Images with range [0, 255].
233
+ Returns:
234
+ (ndarray): Images with range [0, 255] (float type) without round.
235
+ """
236
+ img = img.astype(np.float32) / 255.
237
+ if img.ndim == 3 and img.shape[2] == 3:
238
+ img = bgr2ycbcr(img, y_only=True)
239
+ img = img[..., None]
240
+ return img * 255.
241
+
242
+
243
+ def _convert_input_type_range(img):
244
+ """Convert the type and range of the input image.
245
+ It converts the input image to np.float32 type and range of [0, 1].
246
+ It is mainly used for pre-processing the input image in colorspace
247
+ convertion functions such as rgb2ycbcr and ycbcr2rgb.
248
+ Args:
249
+ img (ndarray): The input image. It accepts:
250
+ 1. np.uint8 type with range [0, 255];
251
+ 2. np.float32 type with range [0, 1].
252
+ Returns:
253
+ (ndarray): The converted image with type of np.float32 and range of
254
+ [0, 1].
255
+ """
256
+ img_type = img.dtype
257
+ img = img.astype(np.float32)
258
+ if img_type == np.float32:
259
+ pass
260
+ elif img_type == np.uint8:
261
+ img /= 255.
262
+ else:
263
+ raise TypeError('The img type should be np.float32 or np.uint8, ' f'but got {img_type}')
264
+ return img
265
+
266
+
267
+ def _convert_output_type_range(img, dst_type):
268
+ """Convert the type and range of the image according to dst_type.
269
+ It converts the image to desired type and range. If `dst_type` is np.uint8,
270
+ images will be converted to np.uint8 type with range [0, 255]. If
271
+ `dst_type` is np.float32, it converts the image to np.float32 type with
272
+ range [0, 1].
273
+ It is mainly used for post-processing images in colorspace convertion
274
+ functions such as rgb2ycbcr and ycbcr2rgb.
275
+ Args:
276
+ img (ndarray): The image to be converted with np.float32 type and
277
+ range [0, 255].
278
+ dst_type (np.uint8 | np.float32): If dst_type is np.uint8, it
279
+ converts the image to np.uint8 type with range [0, 255]. If
280
+ dst_type is np.float32, it converts the image to np.float32 type
281
+ with range [0, 1].
282
+ Returns:
283
+ (ndarray): The converted image with desired type and range.
284
+ """
285
+ if dst_type not in (np.uint8, np.float32):
286
+ raise TypeError('The dst_type should be np.float32 or np.uint8, ' f'but got {dst_type}')
287
+ if dst_type == np.uint8:
288
+ img = img.round()
289
+ else:
290
+ img /= 255.
291
+ return img.astype(dst_type)
292
+
293
+
294
+ def bgr2ycbcr(img, y_only=False):
295
+ """Convert a BGR image to YCbCr image.
296
+ The bgr version of rgb2ycbcr.
297
+ It implements the ITU-R BT.601 conversion for standard-definition
298
+ television. See more details in
299
+ https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
300
+ It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`.
301
+ In OpenCV, it implements a JPEG conversion. See more details in
302
+ https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.
303
+ Args:
304
+ img (ndarray): The input image. It accepts:
305
+ 1. np.uint8 type with range [0, 255];
306
+ 2. np.float32 type with range [0, 1].
307
+ y_only (bool): Whether to only return Y channel. Default: False.
308
+ Returns:
309
+ ndarray: The converted YCbCr image. The output image has the same type
310
+ and range as input image.
311
+ """
312
+ img_type = img.dtype
313
+ img = _convert_input_type_range(img)
314
+ if y_only:
315
+ out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0
316
+ else:
317
+ out_img = np.matmul(
318
+ img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) + [16, 128, 128]
319
+ out_img = _convert_output_type_range(out_img, img_type)
320
+ return out_img