-
Notifications
You must be signed in to change notification settings - Fork 68
/
selfdeblur_levin_reproduce.py
159 lines (127 loc) · 5.43 KB
/
selfdeblur_levin_reproduce.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
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
# coding: utf-8
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument("--preprocess", type=bool, default=False, help='run prepare_data or not')
parser.add_argument('--num_iter', type=int, default=2, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="imgs/levin/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/levin_reproduce/", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=1, help='frequency to save results')
opt = parser.parse_args()
#print(opt)
#os.environ['CUDA_VISIBLE_DEVICES'] = '1'
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.0001
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel1') != -1:
opt.kernel_size = [17, 17]
if imgname.find('kernel2') != -1:
opt.kernel_size = [15, 15]
if imgname.find('kernel3') != -1:
opt.kernel_size = [13, 13]
if imgname.find('kernel4') != -1:
opt.kernel_size = [27, 27]
if imgname.find('kernel5') != -1:
opt.kernel_size = [11, 11]
if imgname.find('kernel6') != -1:
opt.kernel_size = [19, 19]
if imgname.find('kernel7') != -1:
opt.kernel_size = [21, 21]
if imgname.find('kernel8') != -1:
opt.kernel_size = [21, 21]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = torch.load(os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
net = net.type(dtype)
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = torch.load(os.path.join(opt.save_path, "%s_knet.pth" % imgname))
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
L1 = torch.nn.L1Loss(reduction='sum').type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()},{'params':net_kernel.parameters(),'lr':0e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[700, 800, 900], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# net_input_kernel = net_input_kernel_saved + reg_noise_std*torch.zeros(net_input_kernel_saved.shape).type_as(net_input_kernel_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
if step < 0:
total_loss = mse(out_y, y)
else:
total_loss = 1 - ssim(out_y, y) # + tv_loss(out_x) #+ tv_loss2(out_k_m)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
#out_x_np = np.uint8(out_x_np*255)
#cv2.imwrite(save_path, out_x_np)
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
#torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
#torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))