-
Notifications
You must be signed in to change notification settings - Fork 1
/
undergraduate_project.py
517 lines (423 loc) · 16.7 KB
/
undergraduate_project.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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# -*- coding: utf-8 -*-
"""UnderGraduate_Project.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1w8yICbVKQQoWOYx0arH4qUWCGLkJPcld
"""
!nvidia-smi
# Commented out IPython magic to ensure Python compatibility.
import numpy as np
from tensorflow.keras import layers
from keras.preprocessing import image
import tensorflow as tf
from keras.models import Model,load_model
from keras.utils import to_categorical
import os
import keras
from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization
from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau, EarlyStopping
from keras.layers import Lambda
from keras.optimizers import Adam, SGD
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
import random
from PIL import Image
from random import shuffle
# %load_ext tensorboard
import datetime
"""**Prepare**"""
import numpy as np
from numpy import genfromtxt
from numpy import asarray
import math
import copy
import os
from PIL import Image
import cv2
import shutil
patch_size = 64 #input = 64x64
label_size = 128 #output = 128x128
#get RGGB bayer image
def bayer_reverse(img):
height,width,c = img.shape;
tmp = np.zeros([height,width]);
for i in range( height ):
for j in range( width ):
if i % 2 == 0 :
if j % 2 == 0:
tmp[i][j] = img[i][j][0];#R
else:
tmp[i][j] = img[i][j][1];#G
else :
if j % 2 == 0:
tmp[i][j] = img[i][j][1];#G
else:
tmp[i][j] = img[i][j][2];#B
return tmp;
#split image to prepare the train set
def split(img,name,dir_path):
height,width,c = img.shape;
count = 0;
for i in range(0, height, 30):
for j in range(0, width, 30):
if( i + label_size < height and j + label_size < width ):
label = np.zeros([label_size,label_size,3])
tmp2 = np.zeros([label_size,label_size,3])
tmp2 = img[ i : i + label_size, j : j + label_size,:]
label_img = Image.fromarray(tmp2)
label[:,:,0] = tmp2[:,:,2]
label[:,:,1] = tmp2[:,:,1]
label[:,:,2] = tmp2[:,:,0]
label_path = os.path.join(dir_path,'label/'+name.split('.')[0] +'_'+str(count)+'.png')
cv2.imwrite(label_path,label)
zoom = label_img.resize((patch_size,patch_size), Image.BICUBIC)
tmp3 = np.zeros([patch_size,patch_size])
patch = np.zeros([patch_size,patch_size])
zoom2 = np.array(zoom)
patch = bayer_reverse(zoom2)
patch_path = os.path.join(dir_path,'patch/'+name.split('.')[0] +'_'+str(count)+'.png')
cv2.imwrite(patch_path, patch)
count = count + 1
def main():
path = 'drive/My Drive/Colab Notebooks/undergraduate_project'
if os.path.exists(os.path.join(path,'patch')):
shutil.rmtree(os.path.join(path,'patch'))
os.makedirs(os.path.join(path,'patch'))
if os.path.exists(os.path.join(path,'label')):
shutil.rmtree(os.path.join(path,'label'))
os.makedirs(os.path.join(path,'label'))
dataset_path = os.path.join(path,'BSD200')
entries = os.listdir(dataset_path)
for entry in entries:
print(entry)
img_path = dataset_path + '/' + entry
img = Image.open(img_path)
img = np.array(img)
split(img,entry,path)
if __name__ == '__main__':
main()
"""**Training**"""
import numpy as np
from tensorflow.keras import layers
from keras.preprocessing import image
import tensorflow as tf
from keras.models import Model,load_model
from keras.utils import to_categorical
import os
import keras
from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau, EarlyStopping
from keras.layers import Lambda
from keras.optimizers import Adam
from keras import backend as K
import random
from PIL import Image
from random import shuffle
train_image = []
train_label = []
patch_size = 64
label_size = 128
dir_path = 'drive/My Drive/Colab Notebooks/undergraduate_project'
patch_path = os.path.join(dir_path,'patch')
entries = os.listdir(patch_path)
for entry in entries:
im = Image.open(patch_path+'/'+entry)
img = image.img_to_array(im)
# print(img.shape)
# img = img/255.
train_image.append(img)
train_image= np.stack(train_image)
print(train_image.shape)
label_path = os.path.join(dir_path,'label')
entries = os.listdir(label_path)
for entry in entries:
im = Image.open(label_path+'/'+entry)
img = image.img_to_array(im)
# img = img/255.
train_label.append(img)
train_label = np.stack(train_label)
print(train_label.shape)
index = [i for i in range(train_image.shape[0])]
shuffle(index)
train_image = train_image[index,:,:,:];
train_label = train_label[index,:,:,:];
# np.save('drive/My Drive/Colab Notebooks/undergraduate_project/train_image.npy', train_image)
# np.save('drive/My Drive/Colab Notebooks/undergraduate_project/train_label.npy', train_label)
############################# Model Structure ################################################
def create_model():
inputs = keras.Input(shape=(None,None,1))
##Subpixel Construction
sub_layer_2 = Lambda(lambda x:tf.nn.space_to_depth(x,2))
init = sub_layer_2(inputs=inputs)
##Learning Residual (DCNN)
####Conv 3x3x64x64 + PReLu
x = keras.layers.Conv2D(filters = 64, #feature map number
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,1))(init)
x = keras.layers.Conv2D(filters = 64, #feature map number
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.Conv2D(filters = 64, #feature map number
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
# x = keras.layers.BatchNormalization()(x)
# x = keras.layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(x)
####Residual Block
for i in range(6):
start = x
Conv1 = keras.layers.Conv2D(filters=64,
kernel_size = 1,
strides = 1, # 2
padding = 'same',
input_shape = (None,None,64))(start)
Conv1 = keras.layers.LeakyReLU()(Conv1)
# Conv1_BN = keras.layers.BatchNormalization()(Conv1)
# Conv1_BN = Dropout(0.5)(Conv1_BN)
# PReLu = keras.layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(Conv1)
Conv2 = keras.layers.Conv2D(filters=64,
kernel_size = 3,
strides = 1, # 2
padding = 'same',
input_shape = (None,None,64))(Conv1)
Conv2 = keras.layers.LeakyReLU()(Conv2)
# Conv2_BN = keras.layers.BatchNormalization()(Conv2)
# Conv2_BN = Dropout(0.5)(Conv2_BN)
# PReLu = keras.layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(Conv2)
Conv3 = keras.layers.Conv2D(filters=64,
kernel_size = 1,
strides = 1, # 2
padding = 'same',
input_shape = (None,None,64))(Conv2)
# Conv3 = keras.layers.LeakyReLU()(Conv3)
# Concatenate
x = keras.layers.Add()([Conv3,x])
####Conv 3x3x64x64 + PReLu
x = keras.layers.Conv2D(filters = 64,
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.Conv2D(filters = 64,
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.Conv2D(filters = 64,
kernel_size = 3,
strides = 1, # 2
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
# x = keras.layers.BatchNormalization()(x)
# x = keras.layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(x)
####Conv 3x3x64x48
x = keras.layers.Conv2D(filters = 64,
kernel_size = 3,
strides = 1,
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.Conv2D(filters = 64,
kernel_size = 3,
strides = 1,
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.Conv2D(filters = 48,
kernel_size = 3,
strides = 1,
padding = 'same',
activation = 'relu',
input_shape = (None,None,64))(x)
x = keras.layers.BatchNormalization()(x)
###########Learning Residual (DCNN)############
##Recovery From Subpixel
sub_layer = Lambda(lambda x:tf.nn.depth_to_space(x,4))
Residual_Output = sub_layer(inputs=x)
##Initial Prediction
R = Lambda(lambda x: x[:,:,:,0])(init)
G = Lambda(lambda x: x[:,:,:,1:3])(init)
G = Lambda(lambda x: K.mean(x, axis=3))(G)
B = Lambda(lambda x: x[:,:,:,3])(init)
# print(init.shape)
# print(R.shape)
# print(G.shape)
# print(B.shape)
R = Lambda(lambda x: tf.expand_dims(x, -1))(R)
G = Lambda(lambda x: tf.expand_dims(x, -1))(G)
B = Lambda(lambda x: tf.expand_dims(x, -1))(B)
#rgb = tf.keras.backend.stack((R, G,B),axis = 3)
# print(R.shape)
rg = keras.layers.Concatenate(axis = 3)([R , G])
rgb = keras.layers.Concatenate(axis = 3)([rg,B])
# print(rgb.shape)
Coarse_Output = keras.layers.UpSampling2D(size=(4, 4), interpolation="bilinear")(rgb) #size=4 , from W/2,H/2 ---> 2W,2H
## +
outputs = keras.layers.Add()([Residual_Output,Coarse_Output])
#outputs = Residual_Output
model = keras.Model(inputs=inputs, outputs=outputs, name="JDMSR_model")
return model
batch_size = 32
lr = 0.001
e_num = 50
dir_path = 'drive/My Drive/Colab Notebooks/undergraduate_project'
model = create_model()
model.summary()
sgd = SGD(lr=lr, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=1.0)
model.compile(optimizer=Adam(), loss = 'mean_squared_error', metrics = ['accuracy'])
checkpoint = ModelCheckpoint(os.path.join(dir_path,'model.hdf5'),verbose=1, monitor='loss', save_best_only=True, save_weights_only=True)
rrp = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=2, verbose=1, mode='min', min_lr=0.000002)
early_stopping = EarlyStopping(monitor='loss', patience=10, verbose=1, mode='auto')
history = model.fit(train_image, train_label, epochs=e_num, batch_size=batch_size,verbose=1,validation_split = 0.1,callbacks=[checkpoint, rrp],shuffle = True)
# Plotting
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot()
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Accuracy - 2')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='lower right')
plt.savefig('model_accuracy2.png')
plt.show()
plt.plot()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Loss - 2')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.savefig('model_loss2.png')
plt.show()
"""**Validation**"""
from keras.models import load_model
from keras.layers import Lambda
from keras.preprocessing import image
import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from keras import backend as K
import os
import math
import shutil
width_change = 0
height_change = 0
dir_path = 'drive/My Drive/Colab Notebooks/undergraduate_project'
model = create_model()
model.load_weights(os.path.join(dir_path,'model.hdf5'))
input_path = os.path.join(dir_path, 'Set14')
output_path = os.path.join(dir_path, 'output')
output_path2 = os.path.join(dir_path, 'output2')
output_path3 = os.path.join(dir_path, 'output3')
if os.path.exists(output_path):
shutil.rmtree(output_path)
os.makedirs(output_path)
if os.path.exists(output_path2):
shutil.rmtree(output_path2)
os.makedirs(output_path2)
if os.path.exists(output_path3):
shutil.rmtree(output_path3)
os.makedirs(output_path3)
entries = os.listdir(input_path)
for entry in entries:
# Test Image
print('-----------')
path = input_path+'/'+entry
test_image = Image.open(path)
print(test_image.size)
if test_image.size[0] % 2 != 0: #odd size
test_image = test_image.resize((test_image.size[0]-1, test_image.size[1]), Image.BICUBIC)
if test_image.size[1] % 2 != 0:
test_image = test_image.resize((test_image.size[0], test_image.size[1]-1), Image.BICUBIC)
path = output_path+'/'+entry
test_image.save(path)
print(test_image.size)
test_image = test_image.resize((test_image.size[0]//2, test_image.size[1]//2), Image.BICUBIC)
print(test_image.size)
test_image_array = np.array(test_image)
test_image_array = bayer_reverse(test_image_array)
test_image_array = test_image_array[:,:,np.newaxis]
test_image = image.array_to_img(test_image_array)
test_image.save(output_path3+'/'+entry)
# print(test_image.shape)
print(test_image.size)
# print(test_image.shape)
test_image = np.array(test_image)
test_image = test_image[np.newaxis,:,:]
try:
out = model.predict(test_image)
except:
path = input_path+'/'+entry
test_image = Image.open(path)
if (test_image.size[0]//2)%2 != 0:
test_image = test_image.resize(((test_image.size[0]//2) - 1, test_image.size[1]//2), Image.BICUBIC)
if (test_image.size[1]//2)%2 != 0:
test_image = test_image.resize((test_image.size[0]//2 , (test_image.size[1]//2) - 1), Image.BICUBIC)
test_image_array = np.array(test_image)
test_image_array = bayer_reverse(test_image_array)
test_image_array = test_image_array[:,:,np.newaxis]
test_image = image.array_to_img(test_image_array)
print(test_image.size)
test_image.save(output_path3+'/'+entry)
test_image = np.array(test_image)
test_image = test_image[np.newaxis,:,:]
out = model.predict(test_image)
# print(out.shape)
out = out[0]
out = image.array_to_img(out)
path = output_path2+'/'+entry
out.save(path)
"""**Performance**"""
import cv2
import numpy as np
import math
import os
from google.colab.patches import cv2_imshow
from skimage.measure import compare_ssim
from skimage.measure import compare_ssim as ssim
def calculate_psnr(original, contrast):
mse = np.mean((original - contrast) ** 2)
if mse == 0:
return 100
max_value = 255.0
return 10 * math.log10(max_value**2 / mse)
path = 'drive/My Drive/Colab Notebooks/undergraduate_project'
input_path = os.path.join(path,'output')
output_path = os.path.join(path,'output2')
entries = os.listdir(input_path)
count = 0
total_psnr = 0.
total_ssim = 0.
for entry in entries:
img1 = cv2.imread(os.path.join(input_path,entry))
img2 = cv2.imread(os.path.join(output_path,entry))
img1 = cv2.resize(img1, (img2.shape[1], img2.shape[0]), interpolation=cv2.INTER_CUBIC)
# PSNR
psnr = calculate_psnr(img1,img2)
print("PSNR-{0}: {1:.10f}dB".format(entry,psnr))
# SSIM
ssim = compare_ssim(img1, img2, data_range=255.0 - 0.0,multichannel=True)
print("SSIM-{0}: {1:.10f}".format(entry,ssim))
total_psnr += psnr
total_ssim += ssim
count += 1
print(count)
total_psnr = total_psnr / count
total_ssim = total_ssim / count
print("\n=====================================")
print("Average PSNR:{:.10f}".format(total_psnr))
print("Average SSIM:{:.10f}".format(total_ssim))