超分辨率技术(1)-- SRCNN

超分辨率技术(Super-Resolution, SR)是指从观测到的低分辨率图像重建出相应的高分辨率图像,在监控设备、卫星图像和医学影像等领域都有重要的应用价值。
SRCNN是首个使用CNN结构的端到端的超分辨率算法。

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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import numpy as np
import torch
from torch import nn
from torch.utils import data
import torch.optim as optim
import PIL.Image as pil_image
import os

#========================================================
# 超参数设置
#========================================================

EPOCH = 20 # 遍历数据集次数
BATCH_SIZE = 5 # 批处理尺寸(batch_size)

#========================================================
# 数据加工
#========================================================

def get_patch(img_array, patch_size, stride):
# 将图片切成小块
patches = []
for i in range(0, img_array.shape[0] - patch_size + 1, stride):
for j in range(0, img_array.shape[1] - patch_size + 1, stride):
patches.append(img_array[i:i + patch_size, j:j + patch_size])
return patches

def prepare(input_path):
# 准备数据
scale = 2

names = os.listdir(input_path)
for name in names:
image_path = os.path.join(input_path, name)
# 高分辨率图像
hr = pil_image.open(image_path).convert('RGB')
hr_width = (hr.width // scale) * scale
hr_height = (hr.height // scale) * scale
hr = hr.resize((hr_width, hr_height), resample=pil_image.BICUBIC)

# 低分辨率图像(先缩小后放大)
lr = hr.resize((hr_width // scale, hr_height // scale), resample=pil_image.BICUBIC)
lr = lr.resize((lr.width * scale, lr.height * scale), resample=pil_image.BICUBIC)

hr = hr.convert('L')
lr = lr.convert('L')

hr = np.array(hr).astype(np.float32)
lr = np.array(lr).astype(np.float32)

hr_patches = get_patch(hr, 33, 14)
lr_patches = get_patch(lr, 33, 14)

lr_patches = np.array(lr_patches)
hr_patches = np.array(hr_patches)

np.save('Images2/lr.npy', lr_patches)
np.save('Images2/hr.npy', hr_patches)

class MyDataSet(data.Dataset):
def __init__(self):
self.lr = np.load('Images2/lr.npy')
self.hr = np.load('Images2/hr.npy')

def __len__(self):
return len(self.lr)

def __getitem__(self, index):
lr = self.lr[index] / 255.0
hr = self.hr[index] / 255.0
return torch.from_numpy(lr).unsqueeze(0), torch.from_numpy(hr).unsqueeze(0)

# prepare('Images/')

dataloader = torch.utils.data.DataLoader(
MyDataSet(),
batch_size=BATCH_SIZE,
shuffle=True,
drop_last=True
)

#========================================================
# 模型结构设计
#========================================================

class SRCNN(nn.Module):
def __init__(self, num_channels=1):
super(SRCNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(num_channels, 64, kernel_size=9, padding=4),
# 卷积后图像尺寸 (33+4*2-9)/步长+1 = 33
nn.ReLU(inplace=True)
)
self.conv2 = nn.Sequential(
nn.Conv2d(64, 32, kernel_size=5, padding=2),
# 卷积后图像尺寸 (33+2*2-5)/步长+1 = 33
nn.ReLU(inplace=True)
)
self.conv3 = nn.Conv2d(32, num_channels, kernel_size=5, padding=2)
# 卷积后图像尺寸 (33+2*2-5)/步长+1 = 33

def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x

#========================================================
# 模型实例化
#========================================================

# 定义是否使用GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = SRCNN().to(device)

# 定义损失函数loss function 和优化方式
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.0001)

#========================================================
# 训练模型
#========================================================

def train():
for epoch in range(EPOCH):
running_loss = 0.0

for i, data in enumerate(dataloader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)

optimizer.zero_grad()

preds = net(inputs)

loss = criterion(preds, labels)
loss.backward()

optimizer.step()

running_loss += loss.item()

print('[%d] loss: %.3f' % (epoch + 1, running_loss))
torch.save(net.state_dict(), '%s/SRCNN_best.pth' % ('./model/'))
print('Finished Training')

#========================================================
# 测试模型
#========================================================

def convert_rgb_to_ycbcr(img):
y = 16. + (64.738 * img[:, :, 0] + 129.057 * img[:, :, 1] + 25.064 * img[:, :, 2]) / 256.
cb = 128. + (-37.945 * img[:, :, 0] - 74.494 * img[:, :, 1] + 112.439 * img[:, :, 2]) / 256.
cr = 128. + (112.439 * img[:, :, 0] - 94.154 * img[:, :, 1] - 18.285 * img[:, :, 2]) / 256.
return np.array([y, cb, cr]).transpose([1, 2, 0])

def convert_ycbcr_to_rgb(img):
r = 298.082 * img[:, :, 0] / 256. + 408.583 * img[:, :, 2] / 256. - 222.921
g = 298.082 * img[:, :, 0] / 256. - 100.291 * img[:, :, 1] / 256. - 208.120 * img[:, :, 2] / 256. + 135.576
b = 298.082 * img[:, :, 0] / 256. + 516.412 * img[:, :, 1] / 256. - 276.836
return np.array([r, g, b]).transpose([1, 2, 0])

def test(image_file):
net.load_state_dict(torch.load("./model/SRCNN_best.pth")) # 加载模型参数
net.eval() # 设置模式为验证模式

image = pil_image.open(image_file).convert('RGB')
image = image.resize((image.width*2, image.height*2), resample=pil_image.BICUBIC)
image.save('01.jpg')

image = np.array(image).astype(np.float32)

ycbcr = convert_rgb_to_ycbcr(image)

image = ycbcr[..., 0]
image /= 255.
image = torch.from_numpy(image).to(device)
image = image.unsqueeze(0).unsqueeze(0)

with torch.no_grad():
pred = net(image).clamp(0.0, 1.0)

pred = pred.mul(255.0).cpu().numpy().squeeze(0).squeeze(0)
output = np.array([pred, ycbcr[..., 1], ycbcr[..., 2]]).transpose([1, 2, 0])
output = np.clip(convert_ycbcr_to_rgb(output), 0.0, 255.0).astype(np.uint8)

output = pil_image.fromarray(output)
output.save('01_2.jpg')

#========================================================
# 主程序
#========================================================

if __name__ == '__main__':
train()
test('2.jpg')
0%