sczhou commited on
Commit
41b64ac
·
1 Parent(s): 6f94023

add realesrgan.

Browse files
README.md CHANGED
@@ -14,15 +14,19 @@ S-Lab, Nanyang Technological University
14
 
15
  <img src="assets/network.jpg" width="800px"/>
16
 
 
 
 
 
17
  ### Updates
18
 
19
- - **2022.07.29**: New face detector with supporting `['YOLOv5', 'RetinaFace']`. :hugs:
 
20
  - **2022.07.17**: The Colab demo of CodeFormer is available now. <a href="https://colab.research.google.com/drive/1m52PNveE4PBhYrecj34cnpEeiHcC5LTb?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a>
21
  - **2022.07.16**: Test code for face restoration is released. :blush:
22
  - **2022.06.21**: This repo is created.
23
 
24
 
25
-
26
  #### Face Restoration
27
 
28
  <img src="assets/restoration_result1.png" width="400px"/> <img src="assets/restoration_result2.png" width="400px"/>
@@ -83,6 +87,8 @@ You can put the testing images in the `inputs/TestWhole` folder. If you would li
83
  python inference_codeformer.py --w 0.5 --has_aligned --test_path [input folder]
84
 
85
  # For the whole images
 
 
86
  python inference_codeformer.py --w 0.7 --test_path [input folder]
87
  ```
88
 
 
14
 
15
  <img src="assets/network.jpg" width="800px"/>
16
 
17
+ &emsp;
18
+ [![GitHub Stars](https://img.shields.io/github/stars/sczhou/CodeFormer?style=social)](https://github.com/sczhou/CodeFormer)
19
+ Please help to star this repo if CodeFormer is helpful to your pothos or projects. Thanks! :hugs:
20
+
21
  ### Updates
22
 
23
+ - **2022.08.07**: Integrate Real-ESRGAN to support background image enhancement.
24
+ - **2022.07.29**: New face detector with supporting `['YOLOv5', 'RetinaFace']`.
25
  - **2022.07.17**: The Colab demo of CodeFormer is available now. <a href="https://colab.research.google.com/drive/1m52PNveE4PBhYrecj34cnpEeiHcC5LTb?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a>
26
  - **2022.07.16**: Test code for face restoration is released. :blush:
27
  - **2022.06.21**: This repo is created.
28
 
29
 
 
30
  #### Face Restoration
31
 
32
  <img src="assets/restoration_result1.png" width="400px"/> <img src="assets/restoration_result2.png" width="400px"/>
 
87
  python inference_codeformer.py --w 0.5 --has_aligned --test_path [input folder]
88
 
89
  # For the whole images
90
+ # If you want to enhance the background regions with Real-ESRGAN,
91
+ # you can add '--bg_upsampler realesrgan' in the following command
92
  python inference_codeformer.py --w 0.7 --test_path [input folder]
93
  ```
94
 
basicsr/archs/arch_util.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ import math
3
+ import torch
4
+ import torchvision
5
+ import warnings
6
+ from distutils.version import LooseVersion
7
+ from itertools import repeat
8
+ from torch import nn as nn
9
+ from torch.nn import functional as F
10
+ from torch.nn import init as init
11
+ from torch.nn.modules.batchnorm import _BatchNorm
12
+
13
+ from basicsr.ops.dcn import ModulatedDeformConvPack, modulated_deform_conv
14
+ from basicsr.utils import get_root_logger
15
+
16
+
17
+ @torch.no_grad()
18
+ def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
19
+ """Initialize network weights.
20
+
21
+ Args:
22
+ module_list (list[nn.Module] | nn.Module): Modules to be initialized.
23
+ scale (float): Scale initialized weights, especially for residual
24
+ blocks. Default: 1.
25
+ bias_fill (float): The value to fill bias. Default: 0
26
+ kwargs (dict): Other arguments for initialization function.
27
+ """
28
+ if not isinstance(module_list, list):
29
+ module_list = [module_list]
30
+ for module in module_list:
31
+ for m in module.modules():
32
+ if isinstance(m, nn.Conv2d):
33
+ init.kaiming_normal_(m.weight, **kwargs)
34
+ m.weight.data *= scale
35
+ if m.bias is not None:
36
+ m.bias.data.fill_(bias_fill)
37
+ elif isinstance(m, nn.Linear):
38
+ init.kaiming_normal_(m.weight, **kwargs)
39
+ m.weight.data *= scale
40
+ if m.bias is not None:
41
+ m.bias.data.fill_(bias_fill)
42
+ elif isinstance(m, _BatchNorm):
43
+ init.constant_(m.weight, 1)
44
+ if m.bias is not None:
45
+ m.bias.data.fill_(bias_fill)
46
+
47
+
48
+ def make_layer(basic_block, num_basic_block, **kwarg):
49
+ """Make layers by stacking the same blocks.
50
+
51
+ Args:
52
+ basic_block (nn.module): nn.module class for basic block.
53
+ num_basic_block (int): number of blocks.
54
+
55
+ Returns:
56
+ nn.Sequential: Stacked blocks in nn.Sequential.
57
+ """
58
+ layers = []
59
+ for _ in range(num_basic_block):
60
+ layers.append(basic_block(**kwarg))
61
+ return nn.Sequential(*layers)
62
+
63
+
64
+ class ResidualBlockNoBN(nn.Module):
65
+ """Residual block without BN.
66
+
67
+ It has a style of:
68
+ ---Conv-ReLU-Conv-+-
69
+ |________________|
70
+
71
+ Args:
72
+ num_feat (int): Channel number of intermediate features.
73
+ Default: 64.
74
+ res_scale (float): Residual scale. Default: 1.
75
+ pytorch_init (bool): If set to True, use pytorch default init,
76
+ otherwise, use default_init_weights. Default: False.
77
+ """
78
+
79
+ def __init__(self, num_feat=64, res_scale=1, pytorch_init=False):
80
+ super(ResidualBlockNoBN, self).__init__()
81
+ self.res_scale = res_scale
82
+ self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
83
+ self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
84
+ self.relu = nn.ReLU(inplace=True)
85
+
86
+ if not pytorch_init:
87
+ default_init_weights([self.conv1, self.conv2], 0.1)
88
+
89
+ def forward(self, x):
90
+ identity = x
91
+ out = self.conv2(self.relu(self.conv1(x)))
92
+ return identity + out * self.res_scale
93
+
94
+
95
+ class Upsample(nn.Sequential):
96
+ """Upsample module.
97
+
98
+ Args:
99
+ scale (int): Scale factor. Supported scales: 2^n and 3.
100
+ num_feat (int): Channel number of intermediate features.
101
+ """
102
+
103
+ def __init__(self, scale, num_feat):
104
+ m = []
105
+ if (scale & (scale - 1)) == 0: # scale = 2^n
106
+ for _ in range(int(math.log(scale, 2))):
107
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
108
+ m.append(nn.PixelShuffle(2))
109
+ elif scale == 3:
110
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
111
+ m.append(nn.PixelShuffle(3))
112
+ else:
113
+ raise ValueError(f'scale {scale} is not supported. Supported scales: 2^n and 3.')
114
+ super(Upsample, self).__init__(*m)
115
+
116
+
117
+ def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True):
118
+ """Warp an image or feature map with optical flow.
119
+
120
+ Args:
121
+ x (Tensor): Tensor with size (n, c, h, w).
122
+ flow (Tensor): Tensor with size (n, h, w, 2), normal value.
123
+ interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'.
124
+ padding_mode (str): 'zeros' or 'border' or 'reflection'.
125
+ Default: 'zeros'.
126
+ align_corners (bool): Before pytorch 1.3, the default value is
127
+ align_corners=True. After pytorch 1.3, the default value is
128
+ align_corners=False. Here, we use the True as default.
129
+
130
+ Returns:
131
+ Tensor: Warped image or feature map.
132
+ """
133
+ assert x.size()[-2:] == flow.size()[1:3]
134
+ _, _, h, w = x.size()
135
+ # create mesh grid
136
+ grid_y, grid_x = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))
137
+ grid = torch.stack((grid_x, grid_y), 2).float() # W(x), H(y), 2
138
+ grid.requires_grad = False
139
+
140
+ vgrid = grid + flow
141
+ # scale grid to [-1,1]
142
+ vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(w - 1, 1) - 1.0
143
+ vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(h - 1, 1) - 1.0
144
+ vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
145
+ output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)
146
+
147
+ # TODO, what if align_corners=False
148
+ return output
149
+
150
+
151
+ def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):
152
+ """Resize a flow according to ratio or shape.
153
+
154
+ Args:
155
+ flow (Tensor): Precomputed flow. shape [N, 2, H, W].
156
+ size_type (str): 'ratio' or 'shape'.
157
+ sizes (list[int | float]): the ratio for resizing or the final output
158
+ shape.
159
+ 1) The order of ratio should be [ratio_h, ratio_w]. For
160
+ downsampling, the ratio should be smaller than 1.0 (i.e., ratio
161
+ < 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,
162
+ ratio > 1.0).
163
+ 2) The order of output_size should be [out_h, out_w].
164
+ interp_mode (str): The mode of interpolation for resizing.
165
+ Default: 'bilinear'.
166
+ align_corners (bool): Whether align corners. Default: False.
167
+
168
+ Returns:
169
+ Tensor: Resized flow.
170
+ """
171
+ _, _, flow_h, flow_w = flow.size()
172
+ if size_type == 'ratio':
173
+ output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])
174
+ elif size_type == 'shape':
175
+ output_h, output_w = sizes[0], sizes[1]
176
+ else:
177
+ raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')
178
+
179
+ input_flow = flow.clone()
180
+ ratio_h = output_h / flow_h
181
+ ratio_w = output_w / flow_w
182
+ input_flow[:, 0, :, :] *= ratio_w
183
+ input_flow[:, 1, :, :] *= ratio_h
184
+ resized_flow = F.interpolate(
185
+ input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)
186
+ return resized_flow
187
+
188
+
189
+ # TODO: may write a cpp file
190
+ def pixel_unshuffle(x, scale):
191
+ """ Pixel unshuffle.
192
+
193
+ Args:
194
+ x (Tensor): Input feature with shape (b, c, hh, hw).
195
+ scale (int): Downsample ratio.
196
+
197
+ Returns:
198
+ Tensor: the pixel unshuffled feature.
199
+ """
200
+ b, c, hh, hw = x.size()
201
+ out_channel = c * (scale**2)
202
+ assert hh % scale == 0 and hw % scale == 0
203
+ h = hh // scale
204
+ w = hw // scale
205
+ x_view = x.view(b, c, h, scale, w, scale)
206
+ return x_view.permute(0, 1, 3, 5, 2, 4).reshape(b, out_channel, h, w)
207
+
208
+
209
+ class DCNv2Pack(ModulatedDeformConvPack):
210
+ """Modulated deformable conv for deformable alignment.
211
+
212
+ Different from the official DCNv2Pack, which generates offsets and masks
213
+ from the preceding features, this DCNv2Pack takes another different
214
+ features to generate offsets and masks.
215
+
216
+ Ref:
217
+ Delving Deep into Deformable Alignment in Video Super-Resolution.
218
+ """
219
+
220
+ def forward(self, x, feat):
221
+ out = self.conv_offset(feat)
222
+ o1, o2, mask = torch.chunk(out, 3, dim=1)
223
+ offset = torch.cat((o1, o2), dim=1)
224
+ mask = torch.sigmoid(mask)
225
+
226
+ offset_absmean = torch.mean(torch.abs(offset))
227
+ if offset_absmean > 50:
228
+ logger = get_root_logger()
229
+ logger.warning(f'Offset abs mean is {offset_absmean}, larger than 50.')
230
+
231
+ if LooseVersion(torchvision.__version__) >= LooseVersion('0.9.0'):
232
+ return torchvision.ops.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding,
233
+ self.dilation, mask)
234
+ else:
235
+ return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding,
236
+ self.dilation, self.groups, self.deformable_groups)
237
+
238
+
239
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
240
+ # From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py
241
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
242
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
243
+ def norm_cdf(x):
244
+ # Computes standard normal cumulative distribution function
245
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
246
+
247
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
248
+ warnings.warn(
249
+ 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. '
250
+ 'The distribution of values may be incorrect.',
251
+ stacklevel=2)
252
+
253
+ with torch.no_grad():
254
+ # Values are generated by using a truncated uniform distribution and
255
+ # then using the inverse CDF for the normal distribution.
256
+ # Get upper and lower cdf values
257
+ low = norm_cdf((a - mean) / std)
258
+ up = norm_cdf((b - mean) / std)
259
+
260
+ # Uniformly fill tensor with values from [low, up], then translate to
261
+ # [2l-1, 2u-1].
262
+ tensor.uniform_(2 * low - 1, 2 * up - 1)
263
+
264
+ # Use inverse cdf transform for normal distribution to get truncated
265
+ # standard normal
266
+ tensor.erfinv_()
267
+
268
+ # Transform to proper mean, std
269
+ tensor.mul_(std * math.sqrt(2.))
270
+ tensor.add_(mean)
271
+
272
+ # Clamp to ensure it's in the proper range
273
+ tensor.clamp_(min=a, max=b)
274
+ return tensor
275
+
276
+
277
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
278
+ r"""Fills the input Tensor with values drawn from a truncated
279
+ normal distribution.
280
+
281
+ From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py
282
+
283
+ The values are effectively drawn from the
284
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
285
+ with values outside :math:`[a, b]` redrawn until they are within
286
+ the bounds. The method used for generating the random values works
287
+ best when :math:`a \leq \text{mean} \leq b`.
288
+
289
+ Args:
290
+ tensor: an n-dimensional `torch.Tensor`
291
+ mean: the mean of the normal distribution
292
+ std: the standard deviation of the normal distribution
293
+ a: the minimum cutoff value
294
+ b: the maximum cutoff value
295
+
296
+ Examples:
297
+ >>> w = torch.empty(3, 5)
298
+ >>> nn.init.trunc_normal_(w)
299
+ """
300
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
301
+
302
+
303
+ # From PyTorch
304
+ def _ntuple(n):
305
+
306
+ def parse(x):
307
+ if isinstance(x, collections.abc.Iterable):
308
+ return x
309
+ return tuple(repeat(x, n))
310
+
311
+ return parse
312
+
313
+
314
+ to_1tuple = _ntuple(1)
315
+ to_2tuple = _ntuple(2)
316
+ to_3tuple = _ntuple(3)
317
+ to_4tuple = _ntuple(4)
318
+ to_ntuple = _ntuple
basicsr/archs/rrdbnet_arch.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ from basicsr.utils.registry import ARCH_REGISTRY
6
+ from .arch_util import default_init_weights, make_layer, pixel_unshuffle
7
+
8
+
9
+ class ResidualDenseBlock(nn.Module):
10
+ """Residual Dense Block.
11
+
12
+ Used in RRDB block in ESRGAN.
13
+
14
+ Args:
15
+ num_feat (int): Channel number of intermediate features.
16
+ num_grow_ch (int): Channels for each growth.
17
+ """
18
+
19
+ def __init__(self, num_feat=64, num_grow_ch=32):
20
+ super(ResidualDenseBlock, self).__init__()
21
+ self.conv1 = nn.Conv2d(num_feat, num_grow_ch, 3, 1, 1)
22
+ self.conv2 = nn.Conv2d(num_feat + num_grow_ch, num_grow_ch, 3, 1, 1)
23
+ self.conv3 = nn.Conv2d(num_feat + 2 * num_grow_ch, num_grow_ch, 3, 1, 1)
24
+ self.conv4 = nn.Conv2d(num_feat + 3 * num_grow_ch, num_grow_ch, 3, 1, 1)
25
+ self.conv5 = nn.Conv2d(num_feat + 4 * num_grow_ch, num_feat, 3, 1, 1)
26
+
27
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
28
+
29
+ # initialization
30
+ default_init_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1)
31
+
32
+ def forward(self, x):
33
+ x1 = self.lrelu(self.conv1(x))
34
+ x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
35
+ x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
36
+ x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
37
+ x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
38
+ # Emperically, we use 0.2 to scale the residual for better performance
39
+ return x5 * 0.2 + x
40
+
41
+
42
+ class RRDB(nn.Module):
43
+ """Residual in Residual Dense Block.
44
+
45
+ Used in RRDB-Net in ESRGAN.
46
+
47
+ Args:
48
+ num_feat (int): Channel number of intermediate features.
49
+ num_grow_ch (int): Channels for each growth.
50
+ """
51
+
52
+ def __init__(self, num_feat, num_grow_ch=32):
53
+ super(RRDB, self).__init__()
54
+ self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)
55
+ self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)
56
+ self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)
57
+
58
+ def forward(self, x):
59
+ out = self.rdb1(x)
60
+ out = self.rdb2(out)
61
+ out = self.rdb3(out)
62
+ # Emperically, we use 0.2 to scale the residual for better performance
63
+ return out * 0.2 + x
64
+
65
+
66
+ @ARCH_REGISTRY.register()
67
+ class RRDBNet(nn.Module):
68
+ """Networks consisting of Residual in Residual Dense Block, which is used
69
+ in ESRGAN.
70
+
71
+ ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.
72
+
73
+ We extend ESRGAN for scale x2 and scale x1.
74
+ Note: This is one option for scale 1, scale 2 in RRDBNet.
75
+ We first employ the pixel-unshuffle (an inverse operation of pixelshuffle to reduce the spatial size
76
+ and enlarge the channel size before feeding inputs into the main ESRGAN architecture.
77
+
78
+ Args:
79
+ num_in_ch (int): Channel number of inputs.
80
+ num_out_ch (int): Channel number of outputs.
81
+ num_feat (int): Channel number of intermediate features.
82
+ Default: 64
83
+ num_block (int): Block number in the trunk network. Defaults: 23
84
+ num_grow_ch (int): Channels for each growth. Default: 32.
85
+ """
86
+
87
+ def __init__(self, num_in_ch, num_out_ch, scale=4, num_feat=64, num_block=23, num_grow_ch=32):
88
+ super(RRDBNet, self).__init__()
89
+ self.scale = scale
90
+ if scale == 2:
91
+ num_in_ch = num_in_ch * 4
92
+ elif scale == 1:
93
+ num_in_ch = num_in_ch * 16
94
+ self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)
95
+ self.body = make_layer(RRDB, num_block, num_feat=num_feat, num_grow_ch=num_grow_ch)
96
+ self.conv_body = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
97
+ # upsample
98
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
99
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
100
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
101
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
102
+
103
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
104
+
105
+ def forward(self, x):
106
+ if self.scale == 2:
107
+ feat = pixel_unshuffle(x, scale=2)
108
+ elif self.scale == 1:
109
+ feat = pixel_unshuffle(x, scale=4)
110
+ else:
111
+ feat = x
112
+ feat = self.conv_first(feat)
113
+ body_feat = self.conv_body(self.body(feat))
114
+ feat = feat + body_feat
115
+ # upsample
116
+ feat = self.lrelu(self.conv_up1(F.interpolate(feat, scale_factor=2, mode='nearest')))
117
+ feat = self.lrelu(self.conv_up2(F.interpolate(feat, scale_factor=2, mode='nearest')))
118
+ out = self.conv_last(self.lrelu(self.conv_hr(feat)))
119
+ return out
basicsr/utils/realesrgan_utils.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import math
3
+ import numpy as np
4
+ import os
5
+ import queue
6
+ import threading
7
+ import torch
8
+ from basicsr.utils.download_util import load_file_from_url
9
+ from torch.nn import functional as F
10
+
11
+ # ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12
+
13
+
14
+ class RealESRGANer():
15
+ """A helper class for upsampling images with RealESRGAN.
16
+
17
+ Args:
18
+ scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4.
19
+ model_path (str): The path to the pretrained model. It can be urls (will first download it automatically).
20
+ model (nn.Module): The defined network. Default: None.
21
+ tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop
22
+ input images into tiles, and then process each of them. Finally, they will be merged into one image.
23
+ 0 denotes for do not use tile. Default: 0.
24
+ tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10.
25
+ pre_pad (int): Pad the input images to avoid border artifacts. Default: 10.
26
+ half (float): Whether to use half precision during inference. Default: False.
27
+ """
28
+
29
+ def __init__(self,
30
+ scale,
31
+ model_path,
32
+ model=None,
33
+ tile=0,
34
+ tile_pad=10,
35
+ pre_pad=10,
36
+ half=False,
37
+ device=None,
38
+ gpu_id=None):
39
+ self.scale = scale
40
+ self.tile_size = tile
41
+ self.tile_pad = tile_pad
42
+ self.pre_pad = pre_pad
43
+ self.mod_scale = None
44
+ self.half = half
45
+
46
+ # initialize model
47
+ if gpu_id:
48
+ self.device = torch.device(
49
+ f'cuda:{gpu_id}' if torch.cuda.is_available() else 'cpu') if device is None else device
50
+ else:
51
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device
52
+ # if the model_path starts with https, it will first download models to the folder: realesrgan/weights
53
+ if model_path.startswith('https://'):
54
+ model_path = load_file_from_url(
55
+ url=model_path, model_dir=os.path.join('weights/realesrgan'), progress=True, file_name=None)
56
+ loadnet = torch.load(model_path, map_location=torch.device('cpu'))
57
+ # prefer to use params_ema
58
+ if 'params_ema' in loadnet:
59
+ keyname = 'params_ema'
60
+ else:
61
+ keyname = 'params'
62
+ model.load_state_dict(loadnet[keyname], strict=True)
63
+ model.eval()
64
+ self.model = model.to(self.device)
65
+ if self.half:
66
+ self.model = self.model.half()
67
+
68
+ def pre_process(self, img):
69
+ """Pre-process, such as pre-pad and mod pad, so that the images can be divisible
70
+ """
71
+ img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()
72
+ self.img = img.unsqueeze(0).to(self.device)
73
+ if self.half:
74
+ self.img = self.img.half()
75
+
76
+ # pre_pad
77
+ if self.pre_pad != 0:
78
+ self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), 'reflect')
79
+ # mod pad for divisible borders
80
+ if self.scale == 2:
81
+ self.mod_scale = 2
82
+ elif self.scale == 1:
83
+ self.mod_scale = 4
84
+ if self.mod_scale is not None:
85
+ self.mod_pad_h, self.mod_pad_w = 0, 0
86
+ _, _, h, w = self.img.size()
87
+ if (h % self.mod_scale != 0):
88
+ self.mod_pad_h = (self.mod_scale - h % self.mod_scale)
89
+ if (w % self.mod_scale != 0):
90
+ self.mod_pad_w = (self.mod_scale - w % self.mod_scale)
91
+ self.img = F.pad(self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), 'reflect')
92
+
93
+ def process(self):
94
+ # model inference
95
+ self.output = self.model(self.img)
96
+
97
+ def tile_process(self):
98
+ """It will first crop input images to tiles, and then process each tile.
99
+ Finally, all the processed tiles are merged into one images.
100
+
101
+ Modified from: https://github.com/ata4/esrgan-launcher
102
+ """
103
+ batch, channel, height, width = self.img.shape
104
+ output_height = height * self.scale
105
+ output_width = width * self.scale
106
+ output_shape = (batch, channel, output_height, output_width)
107
+
108
+ # start with black image
109
+ self.output = self.img.new_zeros(output_shape)
110
+ tiles_x = math.ceil(width / self.tile_size)
111
+ tiles_y = math.ceil(height / self.tile_size)
112
+
113
+ # loop over all tiles
114
+ for y in range(tiles_y):
115
+ for x in range(tiles_x):
116
+ # extract tile from input image
117
+ ofs_x = x * self.tile_size
118
+ ofs_y = y * self.tile_size
119
+ # input tile area on total image
120
+ input_start_x = ofs_x
121
+ input_end_x = min(ofs_x + self.tile_size, width)
122
+ input_start_y = ofs_y
123
+ input_end_y = min(ofs_y + self.tile_size, height)
124
+
125
+ # input tile area on total image with padding
126
+ input_start_x_pad = max(input_start_x - self.tile_pad, 0)
127
+ input_end_x_pad = min(input_end_x + self.tile_pad, width)
128
+ input_start_y_pad = max(input_start_y - self.tile_pad, 0)
129
+ input_end_y_pad = min(input_end_y + self.tile_pad, height)
130
+
131
+ # input tile dimensions
132
+ input_tile_width = input_end_x - input_start_x
133
+ input_tile_height = input_end_y - input_start_y
134
+ tile_idx = y * tiles_x + x + 1
135
+ input_tile = self.img[:, :, input_start_y_pad:input_end_y_pad, input_start_x_pad:input_end_x_pad]
136
+
137
+ # upscale tile
138
+ try:
139
+ with torch.no_grad():
140
+ output_tile = self.model(input_tile)
141
+ except RuntimeError as error:
142
+ print('Error', error)
143
+ # print(f'\tTile {tile_idx}/{tiles_x * tiles_y}')
144
+
145
+ # output tile area on total image
146
+ output_start_x = input_start_x * self.scale
147
+ output_end_x = input_end_x * self.scale
148
+ output_start_y = input_start_y * self.scale
149
+ output_end_y = input_end_y * self.scale
150
+
151
+ # output tile area without padding
152
+ output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale
153
+ output_end_x_tile = output_start_x_tile + input_tile_width * self.scale
154
+ output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale
155
+ output_end_y_tile = output_start_y_tile + input_tile_height * self.scale
156
+
157
+ # put tile into output image
158
+ self.output[:, :, output_start_y:output_end_y,
159
+ output_start_x:output_end_x] = output_tile[:, :, output_start_y_tile:output_end_y_tile,
160
+ output_start_x_tile:output_end_x_tile]
161
+
162
+ def post_process(self):
163
+ # remove extra pad
164
+ if self.mod_scale is not None:
165
+ _, _, h, w = self.output.size()
166
+ self.output = self.output[:, :, 0:h - self.mod_pad_h * self.scale, 0:w - self.mod_pad_w * self.scale]
167
+ # remove prepad
168
+ if self.pre_pad != 0:
169
+ _, _, h, w = self.output.size()
170
+ self.output = self.output[:, :, 0:h - self.pre_pad * self.scale, 0:w - self.pre_pad * self.scale]
171
+ return self.output
172
+
173
+ @torch.no_grad()
174
+ def enhance(self, img, outscale=None, alpha_upsampler='realesrgan'):
175
+ h_input, w_input = img.shape[0:2]
176
+ # img: numpy
177
+ img = img.astype(np.float32)
178
+ if np.max(img) > 256: # 16-bit image
179
+ max_range = 65535
180
+ print('\tInput is a 16-bit image')
181
+ else:
182
+ max_range = 255
183
+ img = img / max_range
184
+ if len(img.shape) == 2: # gray image
185
+ img_mode = 'L'
186
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
187
+ elif img.shape[2] == 4: # RGBA image with alpha channel
188
+ img_mode = 'RGBA'
189
+ alpha = img[:, :, 3]
190
+ img = img[:, :, 0:3]
191
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
192
+ if alpha_upsampler == 'realesrgan':
193
+ alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2RGB)
194
+ else:
195
+ img_mode = 'RGB'
196
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
197
+
198
+ # ------------------- process image (without the alpha channel) ------------------- #
199
+ self.pre_process(img)
200
+ if self.tile_size > 0:
201
+ self.tile_process()
202
+ else:
203
+ self.process()
204
+ output_img = self.post_process()
205
+ output_img = output_img.data.squeeze().float().cpu().clamp_(0, 1).numpy()
206
+ output_img = np.transpose(output_img[[2, 1, 0], :, :], (1, 2, 0))
207
+ if img_mode == 'L':
208
+ output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY)
209
+
210
+ # ------------------- process the alpha channel if necessary ------------------- #
211
+ if img_mode == 'RGBA':
212
+ if alpha_upsampler == 'realesrgan':
213
+ self.pre_process(alpha)
214
+ if self.tile_size > 0:
215
+ self.tile_process()
216
+ else:
217
+ self.process()
218
+ output_alpha = self.post_process()
219
+ output_alpha = output_alpha.data.squeeze().float().cpu().clamp_(0, 1).numpy()
220
+ output_alpha = np.transpose(output_alpha[[2, 1, 0], :, :], (1, 2, 0))
221
+ output_alpha = cv2.cvtColor(output_alpha, cv2.COLOR_BGR2GRAY)
222
+ else: # use the cv2 resize for alpha channel
223
+ h, w = alpha.shape[0:2]
224
+ output_alpha = cv2.resize(alpha, (w * self.scale, h * self.scale), interpolation=cv2.INTER_LINEAR)
225
+
226
+ # merge the alpha channel
227
+ output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2BGRA)
228
+ output_img[:, :, 3] = output_alpha
229
+
230
+ # ------------------------------ return ------------------------------ #
231
+ if max_range == 65535: # 16-bit image
232
+ output = (output_img * 65535.0).round().astype(np.uint16)
233
+ else:
234
+ output = (output_img * 255.0).round().astype(np.uint8)
235
+
236
+ if outscale is not None and outscale != float(self.scale):
237
+ output = cv2.resize(
238
+ output, (
239
+ int(w_input * outscale),
240
+ int(h_input * outscale),
241
+ ), interpolation=cv2.INTER_LANCZOS4)
242
+
243
+ return output, img_mode
244
+
245
+
246
+ class PrefetchReader(threading.Thread):
247
+ """Prefetch images.
248
+
249
+ Args:
250
+ img_list (list[str]): A image list of image paths to be read.
251
+ num_prefetch_queue (int): Number of prefetch queue.
252
+ """
253
+
254
+ def __init__(self, img_list, num_prefetch_queue):
255
+ super().__init__()
256
+ self.que = queue.Queue(num_prefetch_queue)
257
+ self.img_list = img_list
258
+
259
+ def run(self):
260
+ for img_path in self.img_list:
261
+ img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
262
+ self.que.put(img)
263
+
264
+ self.que.put(None)
265
+
266
+ def __next__(self):
267
+ next_item = self.que.get()
268
+ if next_item is None:
269
+ raise StopIteration
270
+ return next_item
271
+
272
+ def __iter__(self):
273
+ return self
274
+
275
+
276
+ class IOConsumer(threading.Thread):
277
+
278
+ def __init__(self, opt, que, qid):
279
+ super().__init__()
280
+ self._queue = que
281
+ self.qid = qid
282
+ self.opt = opt
283
+
284
+ def run(self):
285
+ while True:
286
+ msg = self._queue.get()
287
+ if isinstance(msg, str) and msg == 'quit':
288
+ break
289
+
290
+ output = msg['output']
291
+ save_path = msg['save_path']
292
+ cv2.imwrite(save_path, output)
293
+ print(f'IO worker {self.qid} is done.')
inference_codeformer.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import cv2
3
  import argparse
@@ -20,15 +21,41 @@ if __name__ == '__main__':
20
  parser.add_argument('--has_aligned', action='store_true', help='Input are cropped and aligned faces')
21
  parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face')
22
  parser.add_argument('--draw_box', action='store_true')
 
 
23
 
24
  args = parser.parse_args()
 
 
25
  if args.test_path.endswith('/'): # solve when path ends with /
26
  args.test_path = args.test_path[:-1]
27
 
28
  w = args.w
29
  result_root = f'results/{os.path.basename(args.test_path)}_{w}'
30
 
31
- # set up the Network
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9,
33
  connect_list=['32', '64', '128', '256']).to(device)
34
 
@@ -98,7 +125,12 @@ if __name__ == '__main__':
98
 
99
  # paste_back
100
  if not args.has_aligned:
101
- bg_img = None
 
 
 
 
 
102
  face_helper.get_inverse_affine(None)
103
  # paste each restored face to the input image
104
  restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box)
 
1
+ # Modified by Shangchen Zhou from: https://github.com/TencentARC/GFPGAN/blob/master/inference_gfpgan.py
2
  import os
3
  import cv2
4
  import argparse
 
21
  parser.add_argument('--has_aligned', action='store_true', help='Input are cropped and aligned faces')
22
  parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face')
23
  parser.add_argument('--draw_box', action='store_true')
24
+ parser.add_argument('--bg_upsampler', type=str, default='realesrgan', help='background upsampler. Default: realesrgan')
25
+ parser.add_argument('--bg_tile', type=int, default=400, help='Tile size for background sampler. Default: 400')
26
 
27
  args = parser.parse_args()
28
+
29
+ # ------------------------ input & output ------------------------
30
  if args.test_path.endswith('/'): # solve when path ends with /
31
  args.test_path = args.test_path[:-1]
32
 
33
  w = args.w
34
  result_root = f'results/{os.path.basename(args.test_path)}_{w}'
35
 
36
+ # ------------------ set up background upsampler ------------------
37
+ if args.bg_upsampler == 'realesrgan':
38
+ if not torch.cuda.is_available(): # CPU
39
+ import warnings
40
+ warnings.warn('The unoptimized RealESRGAN is slow on CPU. We do not use it. '
41
+ 'If you really want to use it, please modify the corresponding codes.')
42
+ bg_upsampler = None
43
+ else:
44
+ from basicsr.archs.rrdbnet_arch import RRDBNet
45
+ from basicsr.utils.realesrgan_utils import RealESRGANer
46
+ model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
47
+ bg_upsampler = RealESRGANer(
48
+ scale=2,
49
+ model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',
50
+ model=model,
51
+ tile=args.bg_tile,
52
+ tile_pad=10,
53
+ pre_pad=0,
54
+ half=True) # need to set False in CPU mode
55
+ else:
56
+ bg_upsampler = None
57
+
58
+ # ------------------ set up CodeFormer restorer -------------------
59
  net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9,
60
  connect_list=['32', '64', '128', '256']).to(device)
61
 
 
125
 
126
  # paste_back
127
  if not args.has_aligned:
128
+ # upsample the background
129
+ if bg_upsampler is not None:
130
+ # Now only support RealESRGAN for upsampling background
131
+ bg_img = bg_upsampler.enhance(img, outscale=args.upscale)[0]
132
+ else:
133
+ bg_img = None
134
  face_helper.get_inverse_affine(None)
135
  # paste each restored face to the input image
136
  restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box)