-
Notifications
You must be signed in to change notification settings - Fork 3
/
RCAN.py
113 lines (89 loc) · 3.03 KB
/
RCAN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import torch.nn as nn
def conv(in_channels, out_channels, kernel_size=3, bias=True):
return nn.Conv2d(
in_channels,
out_channels,
kernel_size=kernel_size,
padding=(kernel_size-1)//2, # same padding
bias=bias)
# Channel Attention (CA) Layer
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
# global average pooling: feature --> point
self.avg_pool = nn.AdaptiveAvgPool2d(1)
# feature channel downscale and upscale --> channel weight
self.conv_du = nn.Sequential(
conv(channel, channel // reduction, 1),
nn.ReLU(inplace=True),
conv(channel // reduction, channel, 1),
nn.Sigmoid())
def forward(self, x):
y = self.avg_pool(x)
y = self.conv_du(y)
return x * y
# Residual Channel Attention Block (RCAB)
class RCAB(nn.Module):
def __init__(self, args):
super(RCAB, self).__init__()
# init
self.num_feat = args.num_feat
self.reduction = args.reduction
# body
modules_body = [
conv(self.num_feat, self.num_feat),
nn.ReLU(True),
conv(self.num_feat, self.num_feat),
CALayer(self.num_feat, self.reduction)
]
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
res += x
return res
# Residual Group (RG)
class ResidualGroup(nn.Module):
def __init__(self, args):
super(ResidualGroup, self).__init__()
# init
self.n_resblocks = args.n_resblocks
self.num_feat = args.num_feat
# body
modules_body = [RCAB(args) for _ in range(self.n_resblocks)]
modules_body.append(conv(self.num_feat, self.num_feat))
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
res += x
return res
# Residual Channel Attention Network (RCAN)
class SRNet(nn.Module):
def __init__(self, args):
super(SRNet, self).__init__()
# init
self.num_channel = args.num_channel
self.num_feat = args.num_feat
self.scale = args.scale
self.n_resgroups = args.n_resgroups
# shallow
self.shallow = conv(self.num_channel, self.num_feat)
# RIR
modules_body = [ResidualGroup(args) for _ in range(self.n_resgroups)]
modules_body.append(conv(self.num_feat, self.num_feat))
self.body = nn.Sequential(*modules_body)
# Upsampler
self.conv_up = conv(self.num_feat, self.num_feat*self.scale*self.scale)
self.upsample = nn.PixelShuffle(self.scale)
self.conv_out = conv(self.num_feat, self.num_channel)
def forward(self, x):
# shallow feature
x = self.shallow(x)
# RIR
res = self.body(x)
# Residual
res += x
# upsample
up = self.conv_up(res)
up = self.upsample(up)
x = self.conv_out(up)
return x