-
Notifications
You must be signed in to change notification settings - Fork 68
/
selfdeblur_nonblind.py
140 lines (110 loc) · 4.61 KB
/
selfdeblur_nonblind.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
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
from networks.skip import skip
from networks.fcn import *
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=1000, 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="results/lai/uniform/nonblind/blurry/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/lai/uniform/nonblind/blurry/results", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=100, help='lfrequency to save results')
opt = parser.parse_args()
#print(opt)
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.01
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('kernel_01') != -1:
opt.kernel_size = [31, 31]
if imgname.find('kernel_02') != -1:
opt.kernel_size = [51, 51]
if imgname.find('kernel_03') != -1:
opt.kernel_size = [55, 55]
if imgname.find('kernel_04') != -1:
opt.kernel_size = [75, 75]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
path_to_kernel = os.path.join(opt.save_path, "%s_k.png" % imgname)
out_k = cv2.imread(path_to_kernel,cv2.IMREAD_GRAYSCALE)
out_k = np.expand_dims(np.float32(out_k/255.),0)
out_k = np_to_torch(out_k).type(dtype)
out_k = torch.clamp(out_k, 0., 1.)
out_k /= torch.sum(out_k)
opt.kernel_size = [out_k.shape[2], out_k.shape[3]]
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 = skip( input_depth, 1,
num_channels_down = [128, 128, 128, 128, 128],
num_channels_up = [128, 128, 128, 128, 128],
num_channels_skip = [16, 16, 16, 16, 16],
upsample_mode='bilinear',
need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')
net = net.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[700, 800, 900], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.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_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k, padding=0, bias=None)
total_loss = 1 - ssim(out_y, y)
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]]
imsave(save_path, out_x_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))