utils.py 22.1 KB
Newer Older
Touklakos's avatar
Touklakos committed
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



#-*- coding: utf-8 -*-
#
# This file is part of DnCnn4Holo.
#
# Adapted from https://github.com/wbhu/DnCNN-tensorflow by Hu Wenbo
#
# DnCnn4Holo is a python script for phase image denoising.
# Home page: https://git-lium.univ-lemans.fr/tahon/dncnn-tensorflow-holography
#
# DnCnn4Holo is free software: you can redistribute it and/or modify
# it under the terms of the GNU LLesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# DnCnn4Holo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DnCnn4Holo.  If not, see <http://www.gnu.org/licenses/>.

"""
Copyright 2019-2020 Marie Tahon

    :mod:`utils.py` definition of util function for DnCnn4Holo

"""

import gc
import os
import sys
import re
import pathlib
import numpy as np
from PIL import Image
from scipy.io import loadmat, savemat
from glob import glob
#import ipdb


Marie Tahon's avatar
Marie Tahon committed
45
#import math
Touklakos's avatar
Touklakos committed
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
import nntools as nt
import torch



__license__ = "LGPL"
__author__ = "Marie Tahon"
__copyright__ = "Copyright 2019-2020 Marie Tahon"
__maintainer__ = "Marie Tahon"
__email__ = "marie.tahon@univ-lemans.fr"
__status__ = "Production"
#__docformat__ = 'reStructuredText'



def extract_sess_name(lp, ln, pt, stride, ps, np):
    """
    This method return a sessions name with his given parameters

    Arguments:
        lp (list[int])  : The different patterns used for training
        ln (str)        : The different noises used for training
        pt (str)        : The type of the pahse used
        stride (int)    : The stride of the patches
        ps (int)        : The size of the patches
        np (int)        : The number of patch per image
    """
#example of the call of the function:
#sess_name = extract_sess_name(hparams.train_patterns, hparams.train_noise, hparams.phase_type, hparams.stride, hparams.patch_size, hparams.patch_per_image)
    #return '-'.join(map(str, lp)) + '_' + '-'.join(map(str, ln)) + '_' + pt + '_' + str(stride) + '_' + str(ps) + '_' + str(np)
    return '-'.join(map(str, lp)) + '_' + ln + '_' + pt + '_' + str(stride) + '_' + str(ps) + '_' + str(np)



def get_files(path, regexp):
    """
    This method return every file matching a regular expression in a given directory

    Arguments:
        path (pathlib.Path) : The path of the directory
        regexp (str)        : The regular expression 
    """
    list_files = []
    for root, dirs, files in os.walk(path):
        #print(root, dirs, files)
        for name in files:
            #print(name, regexp)
            match = re.match(regexp, name)
            #print(match)
            if match:
                list_files.append(path.joinpath(name))
    return sorted(list_files)



def from_NATURAL(dir_noise, dir_clean, path_only):
    """
    This method return the clean and noisy images of the NATURAL BDD

    Arguments:
        dir_noise (str) : The path to the noisy references
        dir_clean (str) : The path to the clean references
    """
    print(dir_noise, dir_clean)
    regExp = '.*.png'
    #select_noisy = sorted(glob(dir_noise + '/*.png'))
    #select_clean = sorted(glob(dir_clean + '/*.png'))
    select_noisy = get_files(pathlib.Path(dir_noise), regExp)
    select_clean = get_files(pathlib.Path(dir_clean), regExp)
    if path_only:#return only the filenames, not the images
        return select_clean, select_noisy

    else:  #return the images directly, not only the filenames
        data_clean = []
        for file in select_clean:
            #ipdb.set_trace()
            im = Image.open(file).convert('L')
            data_clean.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
        data_noisy = []
        for file in select_noisy:
            im = Image.open(file).convert('L')
            data_noisy.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
        return data_clean, data_noisy



def from_HOLODEEP(dir_noise, dir_clean, noise_eval, img_eval, path_only):
Marie Tahon's avatar
Marie Tahon committed
133
    """@deprecated ? -> yes if we use only .mat files in input with its structure in terms of PATTERNS
Touklakos's avatar
Touklakos committed
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
    This method return the clean and noisy images of the HOLODEEP BDD

    Arguments:
        dir_noise
        dir_clean
        noise_eval
        img_eval
    """
    pattern = {1: ('0','1'), 2: ('0','2'), 3: ('0','3'), 4:('73', '1'), 5:('100','1')}
    nois_pat = [str(n).replace('.','p') for n in noise_eval.split('-')]

    regExp = 'MFH2('
    for p in img_eval:
           for n in nois_pat:
                regExp += pattern[p][0] + n + '2' +  pattern[p][1] + '|'

    regExp = regExp[:-1] + ')_\d.*.tiff'

    select_noisy = get_files(pathlib.Path(dir_noise), regExp)
    select_clean = get_files(pathlib.Path(dir_clean), regExp)
    print('selected noisy / clean files:', len(select_noisy), len(select_clean))
    if path_only:#return only the filenames, not the images
        return select_clean, select_noisy


    else: #return the images directly, not only the filenames
        data_clean = []
        for file in select_clean:
            #ipdb.set_trace()
            im = Image.open(file).convert('L')
            data_clean.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
        data_noisy = []
        for file in select_noisy:
            im = Image.open(file).convert('L')
            data_noisy.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
        return data_clean, data_noisy



def from_DATABASE(dir_data, noise_eval, img_eval, flipupdown = False):
    """
    This method return the clean and the noisy image of a DATABASE
    The images will be returned if they matches the given patterns and noise levels

    Arguments:
        dir_data (str)          : The path to the database
        noise_eval (str)        : The noise levels to return
        img_eval (list[int])    : The patterns to return
    """
    select_noisy = []
    select_clean = []
    nois_pat = [str(n).replace('.','p') for n in noise_eval.split('-')]
    for p in img_eval:
        pat = dir_data + 'PATTERN' + str(p) + '/'
        for n in nois_pat:
            select_noisy.append(pat + 'MFH_' + n + '/NoisyPhase.mat')
            select_clean.append(pat + 'PhaseDATA.mat')

    #if isDebug: print('-->', len(select_noisy), len(select_clean))

    clean = []
    for file in select_clean:
Marie Tahon's avatar
Marie Tahon committed
196
        #print('clean eval data: ', file)
Touklakos's avatar
Touklakos committed
197
198
199
200
201
        im = loadMAT_flip(file, 'Phase', flipupdown)
        clean.append(im)
    
    noisy = []
    for file in select_noisy:
Marie Tahon's avatar
Marie Tahon committed
202
        #print('noisy eval data: ', file)
Touklakos's avatar
Touklakos committed
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
        im = loadMAT_flip(file, 'NoisyPhase', flipupdown)
        noisy.append(im)
    return clean, noisy


def loadMAT_flip(file, key, flipupdown):
    """
    This method load a .mat file and return a numpy.array

    Arguments:
        file (str)          : The path to the matlab file
        key (str)           : The key of the matlab file
        filpupdown (bool)   : True to return a fliped numpy.array, false otherwise
    """
    s = loadmat(file)
    if key in s:
        im = np.array(s[key])
    else:
        print('Existing keys are: ', s.keys())
        sys.exit('Key error when loading matlab file')
    if flipupdown:
        np.flipud(im)
    return im.reshape(1, im.shape[1], im.shape[0], 1)



def loadIM_flip(file, key, flipupdown):
    """
    This method load an image file and return a numpy.array

    Arguments:
        file (str)          : The path to the image file
        key (str)           : The key of the image file
        filpupdown (bool)   : True to return a fliped numpy.array, false otherwise
    """
    im = np.array(Image.open(file).convert('L'))
    im = (im * np.pi / 128.0) - np.pi

    print(im.min(), im.max())   
    return im.reshape(1, im.shape[1], im.shape[0], 1)


def wrap_phase(x):
    """
    This method return the given numpy.array wrap between [-pi; pi]

    Arguments:
        x (numpy.array) : The numpy.array to wrap
    """
    return (x + np.pi) % (2 * np.pi) - np.pi


def phase_to_image(data, name):
    """
    This method save a numpy.array in a .tiff format with a given name

    Arguments:
        data (numpy.array)  : The numpy.array to save 
        name (str)          : The saving name
    """
    #normalize brute phase between -pi and pi between 0 and 1
    #data = (data - data.min())/ (data.max() - data.min())
    #if not (data.min() >= -np.pi) and (data.max() <= np.pi):
    #    data = np.unwrap(data)

    data = wrap_phase(data)
    data = min_max_norm(data) #resale entre 0 et 1
    np.clip(data, 0, 1) #supprime les valeurs inférieures à 0 et supérieures à 1
Marie Tahon's avatar
Marie Tahon committed
271
    #print(data.min(), data.max())
Touklakos's avatar
Touklakos committed
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
    data = (data * 255).astype('uint8') #formate les données pour faire une image.
    im = Image.fromarray(data[0,:,:,0])
    im.save(name, 'tiff')



def data_augmentation(image, mode):
    """
    This method return a rotated and/or fliped numpy.array

    Arguments:
        image (numpy.array) : The image to transform
        mode (int)          : The mode of transormation (see sources)
    """
    if mode == 0:
        # original
        return image
    elif mode == 1:
        # flip up and down
        return np.flipud(image)
    elif mode == 2:
        # rotate counterwise 90 degree
        return np.rot90(image)
    elif mode == 3:
        # rotate 90 degree and flip up and down
        image = np.rot90(image)
        return np.flipud(image)
    elif mode == 4:
        # rotate 180 degree
        return np.rot90(image, k=2)
    elif mode == 5:
        # rotate 180 degree and flip
        image = np.rot90(image, k=2)
        return np.flipud(image)
    elif mode == 6:
        # rotate 270 degree
        return np.rot90(image, k=3)
    elif mode == 7:
        # rotate 270 degree and flip
        image = np.rot90(image, k=3)
        return np.flipud(image)


def min_max_norm(X):
    return (X - X.min())/(X.max() - X.min())

def norm_to_sincos(X):
    return 2* X -1

def norm_to_phase(X):
    #assume normalized value is between -0.5 and 0.5
    #return (2 * np.pi * X ) - np.pi 
    return 2 *np.pi * X

def phase_to_norm(X):
    return (X + np.pi) / (2* np.pi)

def sincos_to_norm(X):
    return (X + 1) / 2



def rotate_data(data, nb_rotation):
    """
    This method return a copied and increased numpy.array for a given number of rotation

    Arguments:
        data (numpy.array)  : The data to increase
        nb_rotation (int)   : The number of increase (cliped between 1 and 8)
    """
    nb_rotation = np.clip(nb_rotation, 1, 8)
    
    numPatch = data.shape[0]
    newshape = (numPatch * nb_rotation, data.shape[1], data.shape[2], data.shape[3])
    data_n = np.zeros(shape = newshape)
    cpt = 0
    for k in range(numPatch):
        for i in range(nb_rotation):
            data_n[i*numPatch + k,:,:,0] = data_augmentation(data[k,:,:,0], i)
    
    print('nb of rotation: ', numPatch* nb_rotation)
    return data_n


def normalize_data(data,phase_type, rdm, phase_augmentation = False):
    """
    This method :
        - return the given numpy.array                                              if phase_type=="phi"
        - return the cosinus of a given numpy.array                                 if phase_type=="cos"
        - return the sinus of a given numpy.array                                   if phase_type=="sin"
        - return a random distribution of sinus and cosinus of a given numpy.array  if phase_type=="two" and phase_augmentation==False  
        - return a numpy.array increased 8 times                                    if phase_type=="two" and phase_augmentation==True

    Arguments:
        data (numpy.array)                  : The numpy.array to transform
        phase_type (str)                    : The type of transformation
        rdm (numpy.array)                   : The random distribution if phase_type=="two" and phase_augmentation==False  
        phase_augmentation (bool, optional) : True to increased the returned data, False otherwise 
    """
    #every data sets are normalized between 0 and 1
    if phase_type == 'phi':
        return data
    elif phase_type == 'cos':
        return np.cos( data)
    elif phase_type == 'sin':
        return np.sin(data)
    elif (phase_type == 'two') & (phase_augmentation == False):
        data_n = np.zeros(shape = data.shape)
        cpt = 0
        for k, r in enumerate(rdm):
            if r == 0:
                data_n[k,:,:,:] =  np.cos( data[k,:,:,:])
                cpt += 1
            else:
                data_n[k,:,:,:] = np.sin( data[k,:,:,:])
        print('Nb of cos files :', cpt)
        return data_n
    elif (phase_type == 'two') & (phase_augmentation == True):
        numPatch = data.shape[0]
Touklakos's avatar
Touklakos committed
391
        newshape = (numPatch * 8, data.shape[1], data.shape[2], data.shape[3])
Touklakos's avatar
Touklakos committed
392
393
394
        data_n = np.zeros(shape = newshape)
        cpt = 0
        for k in range(numPatch):
Marie Tahon's avatar
Marie Tahon committed
395
396
397
398
399
400
401
402
403
            data_n[0*numPatch + k,:,:,0] =  np.cos(                           data[k,:,:,0])
            data_n[1*numPatch + k,:,:,0] =  np.sin(                           data[k,:,:,0])
            data_n[2*numPatch + k,:,:,0] =  np.cos( np.transpose(             data[k,:,:,0]) )
            data_n[3*numPatch + k,:,:,0] =  np.sin( np.transpose(             data[k,:,:,0]) )
            data_n[4*numPatch + k,:,:,0] =  np.cos(                 np.pi/4 + data[k,:,:,0])
            data_n[5*numPatch + k,:,:,0] =  np.sin(                 np.pi/4 + data[k,:,:,0])
            data_n[6*numPatch + k,:,:,0] =  np.cos( np.transpose(   np.pi/4 + data[k,:,:,0]) )
            data_n[7*numPatch + k,:,:,0] =  np.sin( np.transpose(   np.pi/4 + data[k,:,:,0]) )
        print('nb of (cos + sin) * transpose * phase + pi/4: ', numPatch * 8)
Touklakos's avatar
Touklakos committed
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
        return data_n
    else:
        print('[!] phase type not exists (phi|cos|sin|two)')
        sys.exit()


class train_data():
    def __init__(self, filepath='./data/image_clean_patches_train.npy', noisyfilepath='./data/image_noisy_patches_train.npy', phase_type='two'):
        self.filepath = filepath
        assert '.npy' in filepath
        if not os.path.exists(filepath):
            print("[!] Clean data file not exists")
            sys.exit(1)
        self.noisyfilepath = noisyfilepath
        assert '.npy' in noisyfilepath
        if not os.path.exists(noisyfilepath):
            print("[!] Noisy data file not exists")
            sys.exit()
        self.phase_type = phase_type

    def __enter__(self):
        print("[*] Loading data...")
        if self.phase_type == 'two':
            rdm = np.random.randint(0, 2, len(filepath))
        else:
            rdm = None
        clean = normalize_data(np.load(self.filepath).astype(np.float32), self.phase_type, rdm) #normalize the data to -1+1
Marie Tahon's avatar
Marie Tahon committed
431
        #rdm = np.random.randn(1,2, )
Touklakos's avatar
Touklakos committed
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
        noisy = normalize_data(np.load(self.noisyfilepath).astype(np.float32), self.phase_type, rdm) #normalize the data to -1+1
        print(clean.shape)
        idx = np.random.permutation(clean.shape[0])
        #np.random.shuffle(self.data)
        self.clean = clean[idx, :, :, :]
        self.noisy = noisy[idx, :, :, :]
        print("[*] Load successfully...")
        return self.clean, self.noisy

    def __exit__(self, type, value, trace):
        del self.clean
        del self.noisy
        gc.collect()
        print("In __exit__()")


def load_train_data(filepath='./data/image_clean_patches_train.npy', noisyfilepath='./data/image_noisy_patches_train.npy', phase_type = 'two'):
    """
    This method load and return clean and noisy references

    Arguments:
        filepath (str, optional)        : The path to the clean references
        noisyfilepath (str, optional)   : The path to the noisy references
        phase_type (str, optional)      : The type of phase (no impact)
    """
    assert '.npy' in filepath
    if not os.path.exists(filepath):
        print("[!] Clean data file not exists")
        sys.exit(1)
    assert '.npy' in noisyfilepath
    if not os.path.exists(noisyfilepath):
        print("[!] Noisy data file not exists")
        sys.exit()

    print("[*] Loading data...")
Marie Tahon's avatar
Marie Tahon committed
467
468
    clean = np.load(filepath)
    noisy = np.load(noisyfilepath)
Touklakos's avatar
Touklakos committed
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
    #if phase_type == 'two':
    #    rdm = np.random.randint(0, 2, len(filepath))
    #else:
    #    rdm = None
    #clean = normalize_data(np.load(filepath).astype(np.float32), phase_type, rdm) #normalize the data to -1+1
    #noisy = normalize_data(np.load(noisyfilepath).astype(np.float32), phase_type, rdm) #normalize the data to -1+1
    #shuffle
    idx = np.random.permutation(clean.shape[0])
        #np.random.shuffle(self.data)
    print("[*] Load successfully...")
    return clean[idx,:,:,:], noisy[idx,:,:,:]

#return train_data(filepath=filepath, noisyfilepath=noisyfilepath, phase_type=phase_type)


def load_test_data(file, key, flipupdown = False):
    """
    This method load a .mat or an image file and return a numpy.array

    Arguments:
        file (str)                  : The path to the file
        key (str)                   : The key of the file
        filpupdown (bool, optional) : True to return a fliped numpy.array, false otherwise
    """
    _, ext = os.path.splitext(file)
    if ext == '.mat':
        return loadMAT_flip(file, key, flipupdown)
    else:
        return loadIM_flip(file, key, flipupdown)


def load_eval_data(dir_data, noise_eval, img_eval):
    """
    see from_DATABASE
    """
Marie Tahon's avatar
Marie Tahon committed
504
    clean, noisy = from_DATABASE(dir_data, noise_eval, img_eval, flipupdown = False)
Touklakos's avatar
Touklakos committed
505
    #if phase_type == 'two':
Marie Tahon's avatar
Marie Tahon committed
506
507
508
509
    #    clean_cos = normalize_data(clean.astype(np.float32), 'cos')
    #    clean_sin = normalize_data(clean.astype(np.float32), 'sin')
    #    noisy_cos = normalize_data(noisy.astype(np.float32), 'cos')
    #    noisy_sin = normalize_data(noisy.astype(np.float32), 'sin')
Touklakos's avatar
Touklakos committed
510
511
    #    return clean, noisy, clean_cos, noisy_cos, clean_sin, noisy_sin
    #elif phase_type == 'phi':
Marie Tahon's avatar
Marie Tahon committed
512
513
    #    clean_phi = normalize_data(clean.astype(np.float32), 'phi')
    #    noisy_phi = normalize_data(clean.astype(np.float32), 'phi')
Touklakos's avatar
Touklakos committed
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
    #clean_n = [x / (2 * np.pi) + 0.5 for x in clean]
    #noisy_n = [x / (2 * np.pi) + 0.5 for x in noisy]
    return clean, noisy



def load_images(filelist, noisyfilelist, phase_type):
    # pixel value range 0-255
    if not (isinstance(filelist, list) or isinstance(noisyfilelist,list)):
        exit('Problem with evaluation file list')
        #im = Image.open(filelist).convert('L')
        #data =  np.array(im).reshape(1, im.size[1], im.size[0], 1)
        #return data
    data_clean = []
    for file in filelist:
        im = Image.open(file).convert('L')
        data_clean.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
    data_noisy = []
    for file in noisyfilelist:
        im = Image.open(file).convert('L')
        data_noisy.append(np.array(im).reshape(1, im.size[1], im.size[0], 1))
    return data_clean, data_noisy


def save_images(filepath, ground_truth, noisy_image=np.array([]), clean_image=np.array([])):
    # assert the pixel value range is 0-255
    #ground_truth = np.squeeze(ground_truth)
    #noisy_image = np.squeeze(noisy_image)
    #clean_image = np.squeeze(clean_image)
    if not ground_truth.any():
        cat_image = ground_truth
    elif noisy_image.size == 0 and clean_image.size== 0:
        cat_image = ground_truth
    else:
        cat_image = np.concatenate([ground_truth, noisy_image, clean_image], axis=1)
    phase_to_image(cat_image, filepath)

def save_MAT_images(filepath, values):
    #save values numpy array into matlab format (in order to perform iterations on predicted images)
Marie Tahon's avatar
Marie Tahon committed
553
    print("original size: ", values.reshape(values.shape[1], values.shape[2]).shape)
Touklakos's avatar
Touklakos committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
    mdict = {'NoisyPhase': values.reshape(values.shape[1], values.shape[2])}
    savemat(filepath, mdict, appendmat = False)

def rad_to_flat(img):
    return ((np.cos(img) + 1) / 2) * 255

def cal_psnr(im1, im2):
    # assert pixel value range is 0-255 and type is uint8
    mse = ((im1.astype(np.float) - im2.astype(np.float)) ** 2).mean()
    psnr = 10 * np.log10(255 ** 2 / mse)
    return psnr


def cal_std_phase(im1, im2):
    #assert pixel value range is 0-255 and type is uint8
    diff = im1 - im2 #im phase entre -pi et pi
    mse = np.angle(np.exp(1j * diff)) # difference de phase brute entre -2pi et 2pi
    dev = np.std(mse)
    return dev


Marie Tahon's avatar
Marie Tahon committed
575

Touklakos's avatar
Touklakos committed
576
def tf_psnr(im1, im2):
577
578
579
    '''
    this function is deprecated
    '''
Touklakos's avatar
Touklakos committed
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
    # assert pixel value range is 0-1
    #mse = tf.losses.mean_squared_error(labels=im2 * 255.0, predictions=im1 * 255.0)
    mse = tf.losses.mean_squared_error(labels=im2, predictions=im1)
    return 10.0 * (tf.log(1 / mse) / tf.log(10.0))





class NNRegressor(nt.NeuralNetwork):
    """
    This class represent an abstract neural network
    """

    def __init__(self):
        super(NNRegressor, self).__init__()
        self.mse = torch.nn.MSELoss()

    def criterion(self, y ,d):
        """
        This method return a float that evaluation the accuracy of the network

        Arguments:
            y (torch.Tensor)    : The predicted noise free reference
            d (torch.Tensor)    : The clean reference
        """
        return self.mse(y, d)




class DenoisingStatsManager(nt.StatsManager):
    """
    This class manage the stats of an experiment
    """

    def __init__(self):
        super(DenoisingStatsManager, self).__init__()


    def init(self):
        super(DenoisingStatsManager, self).init()
        self.running_psnr = 0


    def accumulate(self, loss, x, y, d):
        """
        This method add new results for the stats manager

        Arguments:
            loss (???)
            x (torch.Tensor)    : The noisy reference
            y (torch.Tensor)    : The predicted noise free reference
            d (torch.Tensor)    : The clean reference
        """
        #print("test accumulate")
        super(DenoisingStatsManager, self).accumulate(loss, x, y, d)
        n = x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3]
        self.running_psnr += 10*torch.log10(4*n/(torch.norm(y-d)**2))


    def summarize(self):
        """
        This method return the actual stats managed by the stats manager
        """
        loss = super(DenoisingStatsManager, self).summarize()
        psnr = self.running_psnr / self.number_update if(self.number_update !=0) else self.running_psnr
        return {'loss': loss, 'PSNR': psnr}