-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodels.py
1722 lines (1287 loc) · 66.1 KB
/
models.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, division
import tensorflow as tf
from keras.models import Model
from keras.layers import Concatenate, Add,Subtract, Average, Input, Dense,Dropout, Flatten, BatchNormalization, Activation, LeakyReLU ,ELU,Lambda
from keras.layers.convolutional import Conv2D,Convolution2D, MaxPooling2D, UpSampling2D,ZeroPadding2D, Convolution2DTranspose ,SeparableConv2D,Conv2DTranspose
from keras.layers.advanced_activations import PReLU
from keras.regularizers import l1,l2 ,L1L2
activity_l1 = l1
activity_l2 = l2
from keras import backend as K
from keras.utils.np_utils import to_categorical
import keras.callbacks as callbacks
import keras.optimizers as optimizers
from advanced import HistoryCheckpoint, SubPixelUpscaling ,SubpixelConv2D
from keras_subpixel import Subpixel
import img_utils
import numpy as np
from numpy.lib.stride_tricks import as_strided as ast
import os ,gc
import time
import sys
import math
import scipy
import skimage
from scipy.ndimage.filters import gaussian_filter
from skimage import exposure
from skimage.transform import rescale
from skimage.color import rgb2ycbcr , ycbcr2rgb ,gray2rgb ,rgb2gray
#from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral,
# denoise_wavelet, estimate_sigma)
train_path = img_utils.output_path
validation_path = img_utils.validation_output_path
path_X = img_utils.output_path + "X/"
path_Y = img_utils.output_path + "y/"
print(K.image_dim_ordering())
def PSNRLoss(y_true, y_pred):
"""
PSNR is Peek Signal to Noise Ratio, which is similar to mean squared error.
It can be calculated as
PSNR = 20 * log10(MAXp) - 10 * log10(MSE)
When providing an unscaled input, MAXp = 255. Therefore 20 * log10(255)== 48.1308036087.
However, since we are scaling our input, MAXp = 1. Therefore 20 * log10(1) = 0.
Thus we remove that component completely and only compute the remaining MSE component.
"""
return K.mean(y_pred)
return -10. * np.log10(K.mean(K.square(y_pred - y_true)))
def PSNRLossTest(y_true, y_pred):
"""
PSNR is Peek Signal to Noise Ratio, which is similar to mean squared error.
It can be calculated as
PSNR = 20 * log10(MAXp) - 10 * log10(MSE)
When providing an unscaled input, MAXp = 255. Therefore 20 * log10(255)== 48.1308036087.
However, since we are scaling our input, MAXp = 1. Therefore 20 * log10(1) = 0.
Thus we remove that component completely and only compute the remaining MSE component.
"""
#return K.mean(y_pred)
return -10. * np.log10(K.mean(K.square(y_pred - y_true)))
def psnr(y_true, y_pred):
assert y_true.shape == y_pred.shape, "Cannot calculate PSNR. Input shapes not same." \
" y_true shape = %s, y_pred shape = %s" % (str(y_true.shape),
str(y_pred.shape))
return -10. * np.log10(np.mean(np.square(y_pred - y_true)))
def psnr2(img1, img2):
mse = np.mean( (img1 - img2) ** 2 )
if mse == 0:
return 100
PIXEL_MAX = 255.0
return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
def psnr3(img1, img2):
mse = np.mean( (img1 - img2) ** 2 )
if mse == 0:
return 100
PIXEL_MAX = 255.0
return 10 * math.log10((PIXEL_MAX ** 2)/ math.sqrt(mse))
class BaseSuperResolutionModel(object):
def __init__(self, model_name, scale_factor):
"""
Base model to provide a standard interface of adding Super Resolution models
"""
self.model = None # type: Model
self.model_name = model_name
self.scale_factor = scale_factor
self.weight_path = None
self.type_scale_type = "norm" # Default = "norm" = 1. / 255
self.type_requires_divisible_shape = False
self.type_true_upscaling = False
self.evaluation_func = None
self.uses_learning_phase = False
def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=2) -> Model:
"""
Subclass dependent implementation.
"""
if self.type_requires_divisible_shape:
assert height * img_utils._image_scale_multiplier % 4 == 0, "Height of the image must be divisible by 4"
assert width * img_utils._image_scale_multiplier % 4 == 0, "Width of the image must be divisible by 4"
if K.image_dim_ordering() == "th":
shape = (channels, width * img_utils._image_scale_multiplier, height * img_utils._image_scale_multiplier)
else:
shape = (width * img_utils._image_scale_multiplier, height * img_utils._image_scale_multiplier, channels)
print("shape")
print(shape)
print(img_utils._image_scale_multiplier)
init = Input(shape=shape)
return init
def fit(self, batch_size=2, nb_epochs=100, save_history=True, history_fn="Model History.txt") -> Model:
"""
Standard method to train any of the models.
"""
samples_per_epoch = img_utils.image_count()
#samples_per_epoch =10000
val_count = img_utils.val_image_count()
if self.model == None: self.create_model(batch_size=batch_size)
callback_list = [callbacks.ModelCheckpoint(self.weight_path, monitor='val_PSNRLoss', save_best_only=False,
mode='max', save_weights_only=True ,period=1)]
if save_history: callback_list.append(HistoryCheckpoint(history_fn))
print("Training model : %s" % (self.__class__.__name__))
trainset=img_utils.image_generator(train_path, scale_factor=self.scale_factor,
small_train_images=self.type_true_upscaling,
batch_size=batch_size)
self.model.fit_generator(trainset, steps_per_epoch=samples_per_epoch,
epochs=nb_epochs, callbacks=callback_list,
validation_data=img_utils.image_generator(validation_path,
scale_factor=self.scale_factor,
small_train_images=self.type_true_upscaling,
batch_size=batch_size),
validation_steps=val_count)
return self.model
def evaluate(self, validation_dir):
if self.type_requires_divisible_shape:
_evaluate_denoise(self, validation_dir)
else:
_evaluate(self, validation_dir)
def upVideo(self, imgObj, save_intermediate=False, return_image=False, suffix="scaled",
patch_size=8, mode="patch", verbose=False):
print("SHAAAAAAAAAAAAAAAAA")
print (imgObj.shape)
img_width, img_height = imgObj.shape[0], imgObj.shape[1]
images = np.expand_dims(imgObj, axis=0)
# Transpose and Process images
img_conv = images.astype(np.float32) / 255.
model = self.create_model(img_height,img_width ,load_weights=True)
# Create prediction for image patches
result = model.predict(img_conv, batch_size=128, verbose=verbose)
result = result[0, :, :, :] # Access the 3 Dimensional image vector
#print(result.shape)
result = np.clip(result, 0, 255).astype('uint8')
return result
def upscaleStepPatch(self, img_path, save_intermediate=False, return_image=False, suffix="scaled",
patch_size=256,scalemulti=4,step_patch=64, mode="patch", verbose=True):
"""
Standard method to upscale an image.
:param img_path: path to the image
:param save_intermediate: saves the intermediate upscaled image (bilinear upscale)
:param return_image: returns a image of shape (height, width, channels).
:param suffix: suffix of upscaled image
:param patch_size: size of each patch grid
:param verbose: whether to print messages
:param mode: mode of upscaling. Can be "patch" or "fast"
"""
import os
from scipy.misc import imread, imresize, imsave
print("IMAGEPATH")
print(img_path)
# Destination path
path = os.path.splitext(img_path)
filename = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameNumpy = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + '.npy'
filenameM = path[0] + "_A" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameN = path[0] + "_N" + suffix + "(%dx)" % (self.scale_factor) + path[1]
# Read image
scale_factor = int(self.scale_factor)
scale_factor = 1
true_img = imread(img_path, mode='RGB')
#true_img = gaussian_filter(true_img, sigma=0.5)
#true_img =cv2.imread(img_path,1)
init_height , init_width = true_img.shape[0], true_img.shape[1]
orig_height , orig_width = true_img.shape[0], true_img.shape[1]
bordersize=patch_size
imgageRebuildini = np.zeros( (init_height+bordersize,init_width+bordersize,3))
imgageRebuildini[0 : init_height , 0 : init_width]=true_img
true_img=imgageRebuildini
init_height , init_width = true_img.shape[0], true_img.shape[1]
if verbose: print("Old Size : ", true_img.shape)
if verbose: print("New Size : (%d, %d, 3)" % (init_height * scale_factor, init_width * scale_factor))
print (init_width)
#return
#img_height, img_width = 0, 0
#if mode == "patch" and self.type_true_upscaling:
# Overriding mode for True Upscaling models
# mode = 'fast'
# print("Patch mode does not work with True Upscaling models yet. Defaulting to mode='fast'")
#return
if mode == 'patch':
#arr_patch=np.zeros((2,)
# Create patches
step_patch=64
#if init_width % scalemulti != 0 or init_height % scalemulti != 0 :
if init_width % step_patch != 0 or init_height % step_patch != 0 :
new_w=int((init_width/step_patch)+1)*step_patch
new_h=int((init_height/step_patch)+1)*step_patch
#Crop image to by multiple
new_img = np.zeros((new_h,new_w,3))
new_img[0 :init_height,0 : init_width] =true_img
true_img=new_img
#Reinitialise w ,h
init_height , init_width = true_img.shape[0], true_img.shape[1]
print (init_width)
print("new SHAPEEEEE")
print("new SHAPEEEEE : ", true_img.shape)
if self.type_requires_divisible_shape:
if patch_size % 4 != 0:
print("Deep Denoise requires patch size which is multiple of 4.\nSetting patch_size = 8.")
patch_size = 8
#step_patch=16
images ,counterrebuildtople= img_utils.extract_patches_Step(true_img, (patch_size, patch_size),step_patch)
#images = img_utils.subimage_build_patch_global(true_img, patch_size,patch_size,5000)
#images = img_utils.extract_patches_2dlocal(true_img,imagesfull, (patch_size, patch_size) ,step=step_patch)
print (images.shape)
nb_images = images.shape[0]
patch_shape = (int(init_width * scale_factor), int(init_height * scale_factor), 3)
#out_im=img_utils.rebuild_from_patches_Step(true_img,images, (patch_size, patch_size),counterrebuildtople, scale_factor,step_patch)
#imsave('/home/www/imgsuper/val_images/testX4.png', out_im)
x_width=int(images.shape[1]*scalemulti)
x_height=int(images.shape[2]*scalemulti)
patch_shape = (nb_images,int(patch_size *scalemulti), int(patch_size *scalemulti), 3)
arr_patch_min=np.zeros(patch_shape).astype(np.float32)
#for i in range( nb_images ):
# patchel=images[i]
#w_img=img_utils.imresize(patchel, (x_width, x_height), interp='bicubic')
# w_img=rescale(patchel,4)
#arr_patch_min[i] = w_img
#imsave('/home/www/imgsuper/val_images/batchmini/testX4_'+str(i)+'.png', patchel)
#imsave('/home/www/imgsuper/val_images/batch/testX4_'+str(i)+'.png', w_img)
#imagesset=arr_patch_min
#out_im=img_utils.rebuild_from_patches_Step(true_img,imagesset, (patch_size, patch_size),counterrebuildtople, scalemulti,step_patch)
#imsave('/home/www/imgsuper/val_images/testXX4.png', out_im)
#images=arr_patch_min
img_height ,img_width = images.shape[1], images.shape[2]
print("Number of patches = %d, Patch Shape = (%d, %d)" % (nb_images, img_height, img_width))
#return
else:
# Use full image for super resolution
img_height ,img_width = self.__match_autoencoder_size(img_height, img_width, init_height,
init_width, scale_factor)
#if (img_height*4) >2100 or (img_width*4)>2100:
# sys.exit("Error message")
#print("Image is reshaped to : (%d, %d, %d)" % (images.shape[1], images.shape[2], images.shape[3]))
# Save intermediate bilinear scaled image is needed for comparison.
#save_intermediate=True
#return
intermediate_img = None
if save_intermediate:
if verbose: print("Saving intermediate image.")
fn = path[0] + "_intermediate_" + path[1]
intermediate_img = imresize(true_img, (init_width * scale_factor, init_height * scale_factor))
#imsave(fn, intermediate_img)
imsave(fn, images[0, :, :, :])
#print(images[0, :, :, :].shape)
# Transpose and Process images
if K.image_dim_ordering() == "th":
img_conv = images.transpose((0, 3, 1, 2)).astype(np.float32) / 255.
else:
img_conv = images.astype(np.float32) / 255.
model = self.create_model(img_height, img_width, load_weights=True)
if verbose: print("Model loaded.")
# Create prediction for image patches
result = model.predict(img_conv, batch_size=1, verbose=verbose)
if verbose: print("De-processing images.")
# Deprocess patches
if K.image_dim_ordering() == "th":
result = result.transpose((0, 2, 3, 1)).astype(np.float32) * 255.
else:
result = result.astype(np.float32) * 255.
for j in range(5):
im=result[j]
#imsave(filenameM, im)
del model
K.clear_session()
gc.collect()
#print(result.shape)
# Output shape is (original_width * scale, original_height * scale, nb_channels)
if mode == 'patch':
scale_factor=1
out_shape = (int( init_height* scale_factor), int(init_width * scale_factor), 3)
out_shape_patch = (int( init_height), int(init_width ),3)
#out_shape = (101,60,3)
#out_shape = (60,101,3)
#out_shape = (init_height+8,init_width+8,3)
#out_shape = (init_width+patch_size,init_height+patch_size,3)
print(out_shape)
print("------")
print(out_shape)
#(93, 52, 3)
print(result.shape)
print(true_img.shape)
#result = img_utils.combine_patches(result, out_shape, scale_factor)
#result = img_utils.combine_patches(result, out_shape_patch, scale_factor)
#result = img_utils.reconstruct_from_patches_2dlocal(imagesfull,result, out_shape_patch ,step=step_patch)
result=img_utils.rebuild_from_patches_Step(true_img,result, (patch_size, patch_size),counterrebuildtople, scalemulti,step_patch)
#result = img_utils.subimage_combine_patches_global(true_img , result, patch_size* 2, patch_size*2, 2)
else:
result = result[0, :, :, :] # Access the 3 Dimensional image vector
#print(result.shape)
if verbose: print("Shape out net.")
print(result.shape)
#np.save(filenameNumpy, result)
#result = np.rint(result)
result = np.clip(result, 0, 255).astype('uint8')
#result =result.astype('uint8')
#result=result[0 :orig_height,0 : orig_width]
if verbose: print("Shape initial.")
print(result.shape)
if verbose: print("\nCompleted De-processing image.")
#result=scipy.misc.imfilter(result,ftype='edge_enhance_more')
#result=scipy.misc.imfilter(result,ftype='edge_enhance')
#result=denoise_wavelet(result, multichannel=True, convert2ycbcr=True)
#p2, p98 = np.percentile(result, (2,98))
#result= exposure.rescale_intensity(result, in_range=(p2, p98))
#result=scipy.misc.imfilter(result,ftype='sharpen')
#result= scipy.ndimage.rotate(result, -1*angle, reshape=False)
if return_image:
# Return the image without saving. Useful for testing images.
return result
if verbose: print("Saving image.")
outresult= result[0:orig_height*scalemulti , 0:orig_width*scalemulti ]
#result = imresize(result, (out_width, out_height),interp='bicubic')
#imsave(filename, result)
imsave(filename, outresult)
def upscalePatch(self, img_path, save_intermediate=False, return_image=False, suffix="scaled",
patch_size=32,scalemulti=4, mode="patch", verbose=True):
"""
Standard method to upscale an image.
:param img_path: path to the image
:param save_intermediate: saves the intermediate upscaled image (bilinear upscale)
:param return_image: returns a image of shape (height, width, channels).
:param suffix: suffix of upscaled image
:param patch_size: size of each patch grid
:param verbose: whether to print messages
:param mode: mode of upscaling. Can be "patch" or "fast"
"""
import os
from scipy.misc import imread, imresize, imsave
# Destination path
path = os.path.splitext(img_path)
filename = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameNumpy = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + '.npy'
filenameM = path[0] + "_A" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameN = path[0] + "_N" + suffix + "(%dx)" % (self.scale_factor) + path[1]
# Read image
scale_factor = int(self.scale_factor)
scale_factor = 1
true_img = imread(img_path, mode='RGB')
#true_img =cv2.imread(img_path,1)
init_height , init_width = true_img.shape[0], true_img.shape[1]
orig_height , orig_width = true_img.shape[0], true_img.shape[1]
if verbose: print("Old Size : ", true_img.shape)
if verbose: print("New Size : (%d, %d, 3)" % (init_height * scale_factor, init_width * scale_factor))
print (init_width)
#return
#img_height, img_width = 0, 0
#if mode == "patch" and self.type_true_upscaling:
# Overriding mode for True Upscaling models
# mode = 'fast'
# print("Patch mode does not work with True Upscaling models yet. Defaulting to mode='fast'")
#return
if mode == 'patch':
#arr_patch=np.zeros((2,)
# Create patches
step_patch=4
#if init_width % scalemulti != 0 or init_height % scalemulti != 0 :
if init_width % step_patch != 0 or init_height % step_patch != 0 :
new_w=int((init_width/step_patch)+1)*step_patch
new_h=int((init_height/step_patch)+1)*step_patch
#Crop image to by multiple
new_img = np.zeros((new_h,new_w,3))
new_img[0 :init_height,0 : init_width] =true_img
true_img=new_img
#Reinitialise w ,h
init_height , init_width = true_img.shape[0], true_img.shape[1]
print (init_width)
print("new SHAPEEEEE")
print("new SHAPEEEEE : ", true_img.shape)
if self.type_requires_divisible_shape:
if patch_size % 4 != 0:
print("Deep Denoise requires patch size which is multiple of 4.\nSetting patch_size = 8.")
patch_size = 8
#step_patch=16
imagesfull = img_utils.make_patchesOrig(true_img, scale_factor, patch_size, verbose)
#images = img_utils.subimage_build_patch_global(true_img, patch_size,patch_size,5000)
images = img_utils.extract_patches_2dlocal(true_img,imagesfull, (patch_size, patch_size) ,step=step_patch)
print (images.shape)
#return
nb_images = images.shape[0]
patch_shape = (int(init_width * scale_factor), int(init_height * scale_factor), 3)
x_width=int(images.shape[1]/scalemulti)
x_height=int(images.shape[2]/scalemulti)
patch_shape = (nb_images,int(patch_size /scalemulti), int(patch_size /scalemulti), 3)
arr_patch_min=np.zeros(patch_shape).astype(np.float32)
for i in range( nb_images ):
patchel=images[i]
arr_patch_min[i] = img_utils.imresize(patchel, (x_width, x_height), interp='bicubic')
images=arr_patch_min
img_height ,img_width = images.shape[1], images.shape[2]
print("Number of patches = %d, Patch Shape = (%d, %d)" % (nb_images, img_height, img_width))
else:
# Use full image for super resolution
img_height ,img_width = self.__match_autoencoder_size(img_height, img_width, init_height,
init_width, scale_factor)
#if (img_height*4) >2100 or (img_width*4)>2100:
# sys.exit("Error message")
#print("Image is reshaped to : (%d, %d, %d)" % (images.shape[1], images.shape[2], images.shape[3]))
# Save intermediate bilinear scaled image is needed for comparison.
#save_intermediate=True
#return
intermediate_img = None
if save_intermediate:
if verbose: print("Saving intermediate image.")
fn = path[0] + "_intermediate_" + path[1]
intermediate_img = imresize(true_img, (init_width * scale_factor, init_height * scale_factor))
#imsave(fn, intermediate_img)
imsave(fn, images[0, :, :, :])
#print(images[0, :, :, :].shape)
# Transpose and Process images
if K.image_dim_ordering() == "th":
img_conv = images.transpose((0, 3, 1, 2)).astype(np.float32) / 255.
else:
img_conv = images.astype(np.float32) / 255.
model = self.create_model(img_height, img_width, load_weights=True)
if verbose: print("Model loaded.")
# Create prediction for image patches
result = model.predict(img_conv, batch_size=2, verbose=verbose)
if verbose: print("De-processing images.")
# Deprocess patches
if K.image_dim_ordering() == "th":
result = result.transpose((0, 2, 3, 1)).astype(np.float32) * 255.
else:
result = result.astype(np.float32) * 255.
for j in range(5):
im=result[j]
#imsave(filenameM, im)
#print(result.shape)
# Output shape is (original_width * scale, original_height * scale, nb_channels)
if mode == 'patch':
scale_factor=1
out_shape = (int( init_height* scale_factor), int(init_width * scale_factor), 3)
out_shape_patch = (int( init_height), int(init_width ),3)
#out_shape = (101,60,3)
#out_shape = (60,101,3)
#out_shape = (init_height+8,init_width+8,3)
#out_shape = (init_width+patch_size,init_height+patch_size,3)
print(out_shape)
print("------")
print(out_shape)
#(93, 52, 3)
print(result.shape)
print(true_img.shape)
#result = img_utils.combine_patches(result, out_shape, scale_factor)
#result = img_utils.combine_patches(result, out_shape_patch, scale_factor)
result = img_utils.reconstruct_from_patches_2dlocal(imagesfull,result, out_shape_patch ,step=step_patch)
#result = img_utils.subimage_combine_patches_global(true_img , result, patch_size* 2, patch_size*2, 2)
else:
result = result[0, :, :, :] # Access the 3 Dimensional image vector
#print(result.shape)
if verbose: print("Shape out net.")
print(result.shape)
#np.save(filenameNumpy, result)
#result = np.rint(result)
result = np.clip(result, 0, 255).astype('uint8')
#result =result.astype('uint8')
result=result[0 :orig_height,0 : orig_width]
if verbose: print("Shape initial.")
print(result.shape)
if verbose: print("\nCompleted De-processing image.")
#result=scipy.misc.imfilter(result,ftype='edge_enhance_more')
#result=scipy.misc.imfilter(result,ftype='edge_enhance')
#result=denoise_wavelet(result, multichannel=True, convert2ycbcr=True)
#p2, p98 = np.percentile(result, (2,98))
#result= exposure.rescale_intensity(result, in_range=(p2, p98))
#result=scipy.misc.imfilter(result,ftype='sharpen')
#result= scipy.ndimage.rotate(result, -1*angle, reshape=False)
if return_image:
# Return the image without saving. Useful for testing images.
return result
if verbose: print("Saving image.")
#result = imresize(result, (out_width, out_height),interp='bicubic')
imsave(filename, result)
def upscale(self, img_path, save_intermediate=False, return_image=False, suffix="scaled",
patch_size=32, mode="patch", verbose=True):
"""
Standard method to upscale an image.
:param img_path: path to the image
:param save_intermediate: saves the intermediate upscaled image (bilinear upscale)
:param return_image: returns a image of shape (height, width, channels).
:param suffix: suffix of upscaled image
:param patch_size: size of each patch grid
:param verbose: whether to print messages
:param mode: mode of upscaling. Can be "patch" or "fast"
"""
import os
from scipy.misc import imread, imresize, imsave
flip_img=False
# Destination path
path = os.path.splitext(img_path)
filename = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameNumpy = path[0] + "_" + suffix + "(%dx)" % (self.scale_factor) + '.npy'
filenameM = path[0] + "_A" + suffix + "(%dx)" % (self.scale_factor) + path[1]
filenameN = path[0] + "_N" + suffix + "(%dx)" % (self.scale_factor) + path[1]
# Read image
scale_factor = int(self.scale_factor)
true_img = imread(img_path, mode='RGB')
#true_img =cv2.imread(img_path,1)
init_width, init_height = true_img.shape[0], true_img.shape[1]
if verbose: print("Old Size : ", true_img.shape)
if verbose: print("New Size : (%d, %d, 3)" % (init_height * scale_factor, init_width * scale_factor))
img_height, img_width = 0, 0
if mode == "patch" and self.type_true_upscaling:
# Overriding mode for True Upscaling models
mode = 'fast'
print("Patch mode does not work with True Upscaling models yet. Defaulting to mode='fast'")
if mode == 'patch':
# Create patches
if self.type_requires_divisible_shape:
if patch_size % 4 != 0:
print("Deep Denoise requires patch size which is multiple of 4.\nSetting patch_size = 8.")
patch_size = 8
true_img = imresize(true_img, (init_width*4, init_height*4),interp='bicubic')
print(patch_size)
imsave(filenameM, true_img)
images = img_utils.make_patches(true_img, scale_factor, patch_size, verbose)
nb_images = images.shape[0]
print(true_img.shape)
print(nb_images)
#return
x_width=int(images.shape[1]/4)
x_height=int(images.shape[2]/4)
patch_shape = (nb_images,int(patch_size /4), int(patch_size /4), 3)
arr_patch_min=np.zeros(patch_shape).astype(np.float32)
for i in range( nb_images ):
patchel=images[i]
arr_patch_min[i] = img_utils.imresize(patchel, (x_width, x_height), interp='bicubic')
images=arr_patch_min
#images = img_utils.subimage_build_patch_global(true_img, patch_size,patch_size,5000)
nb_images = images.shape[0]
img_width, img_height = images.shape[1], images.shape[2]
print("Number of patches = %d, Patch Shape = (%d, %d)" % (nb_images, img_height, img_width))
else:
# Use full image for super resolution
img_height ,img_width = self.__match_autoencoder_size(img_height, img_width, init_height,
init_width, scale_factor)
#img_width=32
#img_height=32
out_width=img_width
out_height=img_height
#true_img = gaussian_filter(true_img, sigma=0.4)
angle=5
flip_img=False
#true_img = scipy.ndimage.rotate(true_img, angle, reshape=False)
#true_img=rgb2ycbcr(true_img)
scaletmp=1
img_width=int(img_width/scaletmp)
img_height=int(img_height/scaletmp)
#true_img = imresize(true_img, (img_widtha, img_heighta),interp='bicubic')
#print("SIZE W H")
#print(img_width)
#print(img_height)
#make alb negru
#make alb negru
#true_img = skimage.color.rgb2gray(true_img)
#true_img = skimage.color.gray2rgb(true_img)
#true_img = scipy.ndimage.rotate(true_img, angle, reshape=True)
if flip_img:
true_img = np.fliplr(true_img)
#img_width=int(img_width/4)
#img_height=int(img_height/4)
#true_img = imresize(true_img, (int(img_width*2), int(img_height*2) ),interp='bicubic')
#true_img = imresize(true_img, (int(img_width/2), int(img_height/2) ),interp='bicubic')
#true_img = imresize(true_img, (int(img_width/2), int(img_height/2) ),interp='nearest')
#images = imresize(true_img, (img_width, img_height) ,interp='nearest')
#images = true_img
#true_img=denoise_wavelet(true_img, multichannel=True, convert2ycbcr=True)
#p2, p98 = np.percentile(true_img, (2, 98))
#true_img= exposure.rescale_intensity(true_img, in_range=(p2, p98))
#true_img = gaussian_filter(true_img, sigma=0.3)
#true_img=exposure.adjust_log(true_img, 0.7)
#images = imresize(true_img, (img_width, img_height))
#true_img =img_utils.SetGama(true_img,0.2)
#images = imresize(true_img, (img_width, img_height),interp='nearest')
#imsave(filenameM, true_img)
#true_img=scipy.misc.imfilter(true_img,ftype='sharpen')
#images = imresize(true_img, (img_width, img_height),interp='bilinear')
images = imresize(true_img, (img_width, img_height),interp='bicubic')
#imsave(filenameM, images)
#images = gaussian_filter(images, sigma=0.2)
#true_img = imresize(true_img, (16, 16))
#images = imresize(true_img, (img_width, img_height),interp='nearest')
#images=np.fliplr(images)
#true_img = gaussian_filter(true_img, sigma=0.5)
#images=exposure.adjust_log(images, 1)
imagesBic = imresize(images, (init_width, init_height),interp='bicubic')
#images=rgb2ycbcr(images)
#images=gray2rgb(rgb2gray(images))
imsave(filenameM, images)
#exit()
images = np.expand_dims(images, axis=0)
#if (img_height*4) >2100 or (img_width*4)>2100:
# sys.exit("Error message")
#print("Image is reshaped to : (%d, %d, %d)" % (images.shape[1], images.shape[2], images.shape[3]))
# Save intermediate bilinear scaled image is needed for comparison.
#save_intermediate=True
intermediate_img = None
if save_intermediate:
if verbose: print("Saving intermediate image.")
fn = path[0] + "_intermediate_" + path[1]
intermediate_img = imresize(true_img, (init_width * scale_factor, init_height * scale_factor))
#imsave(fn, intermediate_img)
imsave(fn, images[0, :, :, :])
#print(images[0, :, :, :].shape)
# Transpose and Process images
if K.image_dim_ordering() == "th":
img_conv = images.transpose((0, 3, 1, 2)).astype(np.float32) / 255.
else:
img_conv = images.astype(np.float32) / 255.
model = self.create_model(img_height, img_width, load_weights=True)
if verbose: print("Model loaded.")
# Create prediction for image patches
result = model.predict(img_conv, batch_size=10, verbose=verbose)
if verbose: print("De-processing images.")
# Deprocess patches
if K.image_dim_ordering() == "th":
result = result.transpose((0, 2, 3, 1)).astype(np.float32) * 255.
else:
result = result.astype(np.float32) * 255.
#print(result.shape)
# Output shape is (original_width * scale, original_height * scale, nb_channels)
del model
K.clear_session()
gc.collect()
if mode == 'patch':
scale_factor=4
out_shape = (int(init_width * scale_factor), int(init_height * scale_factor), 3)
#out_shape = (101,60,3)
#out_shape = (60,101,3)
#out_shape = (init_height+8,init_width+8,3)
#out_shape = (init_width+patch_size,init_height+patch_size,3)
print(out_shape)
print("------")
print(out_shape)
#(93, 52, 3)
print(result.shape)
print(true_img.shape)
#result = img_utils.combine_patches(result, out_shape, scale_factor)
result = img_utils.combine_patches(result, out_shape, scale_factor)
#result = img_utils.subimage_combine_patches_global(true_img , result, patch_size* 2, patch_size*2, 2)
else:
result = result[0, :, :, :] # Access the 3 Dimensional image vector
#print(result.shape)
if verbose: print("Saving numpy.")
#np.save(filenameNumpy, result)
#result = np.rint(result)
result = np.clip(result, 0, 255).astype('uint8')
#result = np.clip(result, 0, 235).astype('uint8')
#result =result.astype('uint8')
if verbose: print("\nCompleted De-processing image.")
#result=scipy.misc.imfilter(result,ftype='edge_enhance_more')
#result=scipy.misc.imfilter(result,ftype='edge_enhance')
#result=denoise_wavelet(result, multichannel=True, convert2ycbcr=True)
p2, p98 = np.percentile(result, (2,98))
#result= exposure.rescale_intensity(result, in_range=(p2, p98))
#result=scipy.misc.imfilter(result,ftype='sharpen')
#result= scipy.ndimage.rotate(result, -1*angle, reshape=False)
if return_image:
# Return the image without saving. Useful for testing images.
return result
if flip_img:
result = np.fliplr(result)
if verbose: print("Saving image.")
#result=ycbcr2rgb(result)
#result = imresize(result, (out_width, out_height),interp='bicubic')
imsave(filename, result)
#cv2.imwrite(filename, result)
#f_resizenearest = imresize(result, (int(init_width), int(init_height)), interp='nearest')
#f_resizenearest = imresize(result, (int(img_width), int(img_height)))
#imsave(filenameN, f_resizenearest)
def __match_autoencoder_size(self, img_height, img_width, init_height, init_width, scale_factor):
if self.type_requires_divisible_shape:
if not self.type_true_upscaling:
# AE model but not true upsampling
if ((init_height * scale_factor) % 4 != 0) or ((init_width * scale_factor) % 4 != 0) or \
(init_height % 2 != 0) or (init_width % 2 != 0):
print("AE models requires image size which is multiple of 4.")
img_height = ((init_height * scale_factor) // 4) * 4
img_width = ((init_width * scale_factor) // 4) * 4
else:
# No change required
img_height, img_width = init_height * scale_factor, init_width * scale_factor
else:
# AE model and true upsampling
if ((init_height) % 4 != 0) or ((init_width) % 4 != 0) or \
(init_height % 2 != 0) or (init_width % 2 != 0):
print("AE models requires image size which is multiple of 4.")
img_height = ((init_height) // 4) * 4
img_width = ((init_width) // 4) * 4
else:
# No change required
img_height, img_width = init_height, init_width
else:
# Not AE but true upsampling
if self.type_true_upscaling:
img_height, img_width = init_height, init_width
else:
# Not AE and not true upsampling
img_height, img_width = init_height * scale_factor, init_width * scale_factor
return img_height, img_width
def resizeX2diff(my_input): # resizes input tensor wrt. ref_tensor
#H, W = ref_tensor.get_shape()[1], ref.get_shape()[2]
#prev_shape = my_input.output.get_shape()
prev_shape = my_input._keras_shape
size = [2 * int(s) for s in prev_shape[1:3]]
#return tf.image.resize_nearest_neighbor(my_input, size)
#return tf.image.resize_bicubic(my_input, size)
return tf.image.resize_bilinear(my_input, size)
def resizeX2diff_outputshape(my_input_shape):
shape = list(my_input_shape)
print (shape)
size = [2 * int(s) for s in my_input_shape[1:3]]
shape[1]=size[0]
shape[2]=size[1]
print (shape)
return tuple(shape)
def resizeXX4(my_input): # resizes input tensor wrt. ref_tensor
#H, W = ref_tensor.get_shape()[1], ref.get_shape()[2]
#prev_shape = my_input.output.get_shape()
prev_shape = my_input._keras_shape
size = [4 * int(s) for s in prev_shape[1:3]]
#return tf.image.resize_nearest_neighbor(my_input, size)
#return tf.image.resize_bicubic(my_input, size)
return tf.image.resize_bilinear(my_input, size)
def resizeXX4_outputshape(my_input_shape):
shape = list(my_input_shape)
print (shape)
size = [4 * int(s) for s in my_input_shape[1:3]]
shape[1]=size[0]
shape[2]=size[1]
print (shape)
return tuple(shape)
def resize2bil(my_input): # resizes input tensor wrt. ref_tensor
#H, W = ref_tensor.get_shape()[1], ref.get_shape()[2]
#prev_shape = my_input.output.get_shape()
prev_shape = my_input._keras_shape
size = [2 * int(s) for s in prev_shape[1:3]]
#return tf.image.resize_nearest_neighbor(my_input, size)
#return tf.image.resize_bicubic(my_input, size)
return tf.image.resize_bilinear(my_input, size)
#return tf.image.resize_bilinear(my_input, size)
def resize2bic(my_input): # resizes input tensor wrt. ref_tensor
#H, W = ref_tensor.get_shape()[1], ref.get_shape()[2]
#prev_shape = my_input.output.get_shape()
prev_shape = my_input._keras_shape
size = [2 * int(s) for s in prev_shape[1:3]]
#return tf.image.resize_nearest_neighbor(my_input, size)
return tf.image.resize_bicubic(my_input, size)
#return tf.image.resize_bilinear(my_input, size)
def resizeResScale(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(0.999, my_input)
def resizeResScaleVar(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(1.007, my_input)
def resizeRsDi(my_input): # resizes input tensor wrt. ref_tensor 1.01 0.991 0.995 1.003
return tf.scalar_mul(1.000, my_input)
def resizeRsD(my_input): # resizes input tensor wrt. ref_tensor 0.0997
return tf.scalar_mul(0.1000 , my_input)
def resizeRes01RsD(my_input): # resizes input tensor wrt. ref_tensor 0.0996
return tf.scalar_mul(0.1, my_input)
def resizeX1(my_input): # resizes input tensor wrt. ref_tensor 1.01 0.991 0.995 1.003
return tf.scalar_mul(1.00, my_input)
def resizeX4bic(my_input): # resizes input tensor wrt. ref_tensor
#H, W = ref_tensor.get_shape()[1], ref.get_shape()[2]
#prev_shape = my_input.output.get_shape()
prev_shape = my_input._keras_shape
size = [4 * int(s) for s in prev_shape[1:3]]
#return tf.image.resize_nearest_neighbor(my_input, size)
return tf.image.resize_bicubic(my_input, size)
#return tf.image.resize_bilinear(my_input, size)
def resizeBlockLight09(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(0.9, my_input)
def resizeBlock01(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(0.1, my_input)
def resizeBlockLight(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(0.1, my_input)
def resizeBlockLight01(my_input): # resizes input tensor wrt. ref_tensor
return tf.scalar_mul(0.1, my_input)
def resizeBlockLight001(my_input): # resizes input tensor wrt. ref_tensor
#return tf.scalar_mul(0.0997, my_input)
return tf.scalar_mul(0.1, my_input)
class Difvdsr4(BaseSuperResolutionModel):
def __init__(self, scale_factor):
super(Difvdsr4, self).__init__("Image ScaleGen", scale_factor)
#self.weight_path = "weights_ScaleDiff/scaleNNDiff %dX.h5" % (self.scale_factor)