-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
178 lines (140 loc) · 4.94 KB
/
utils.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
import os
import time
import torch
import mindspore
import random
import shutil
import numpy as np
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
def set_random_seed(seed, deterministic=False):
random.seed(seed)
np.random.seed(seed)
def prepare_dir(results_dir, experiment, delete=True):
'''
prepare needed dirs.
'''
models_dir = os.path.join(results_dir, experiment, 'models')
log_dir = os.path.join(results_dir, experiment, 'log')
train_images_dir = os.path.join(results_dir, experiment, 'images', 'train')
val_images_dir = os.path.join(results_dir, experiment, 'images', 'val')
clean_dir(models_dir, delete=delete)
clean_dir(log_dir, delete=delete)
clean_dir(train_images_dir, delete=delete)
clean_dir(val_images_dir, delete=delete)
return models_dir, log_dir, train_images_dir, val_images_dir
def clean_dir(path, delete=False, contain=False):
'''
if delete is True: if path exist, then delete it's files and folders under it, if not, make it;
if delete is False: if path not exist, make it.
'''
if not os.path.exists(path):
os.makedirs(path)
elif delete:
delete_under(path, contain=contain)
def delete_under(path, contain=False):
'''
delete all files and folders under path
:param path: Folder to be deleted
:param contain: delete root or not
'''
if contain:
shutil.rmtree(path)
else:
del_list = os.listdir(path)
for f in del_list:
file_path = os.path.join(path, f)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
def print_para_num(model):
'''
function: print the number of total parameters and trainable parameters
'''
total_params = sum(p.numel() for p in model.parameters())
total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print('total parameters: %d' % total_params)
print('trainable parameters: %d' % total_trainable_params)
class AverageMeter(object):
"""
Computes and stores the average and current value
"""
def __init__(self):
self.reset()
def reset(self):
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.sum += val
self.count += n
def average(self, auto_reset=False):
avg = self.sum / self.count
if auto_reset:
self.reset()
return avg
class Timer(object):
"""
Computes the times.
"""
def __init__(self, start=True):
if start:
self.start()
def start(self):
self.time_begin = time.time()
def timeit(self, auto_reset=True):
times = time.time() - self.time_begin
if auto_reset:
self.start()
return times
def get_metrics(tensor_image1, tensor_image2, psnr_only=True, reduction=False):
'''
function: given a batch tensor image pair, get the mean or sum psnr and ssim value.
input: range:[0,1] type:tensor.FloatTensor format:[b,c,h,w] RGB
output: two python value, e.g., psnr_value, ssim_value
'''
if len(tensor_image1.shape) != 4 or len(tensor_image2.shape) != 4:
raise Excpetion('a batch tensor image pair should be given!')
numpy_imgs = tensor2img(tensor_image1)
numpy_gts = tensor2img(tensor_image2)
psnr_value, ssim_value = 0., 0.
batch_size = numpy_imgs.shape[0]
for i in range(batch_size):
if not psnr_only:
ssim_value += structural_similarity(numpy_imgs[i],numpy_gts[i], multichannel=True, gaussian_weights=True, use_sample_covariance=False)
psnr_value += peak_signal_noise_ratio(numpy_imgs[i],numpy_gts[i])
if reduction:
psnr_value = psnr_value/batch_size
ssim_value = ssim_value/batch_size
if not psnr_only:
return psnr_value, ssim_value
else:
return psnr_value
def tensor2img(tensor_image):
'''
function: transform a tensor image to a numpy image
input: range:[0,1] type:tensor.FloatTensor format:[b,c,h,w] RGB
output: range:[0,255] type:numpy.uint8 format:[b,h,w,c] RGB
'''
tensor_image = tensor_image*255
tensor_image = tensor_image.permute([0, 2, 3, 1])
if tensor_image.device != 'cpu':
tensor_image = tensor_image.cpu()
numpy_image = np.uint8(tensor_image.numpy())
return numpy_image
def check_padding(x):
h, w = x.size(2), x.size(3)
meta_size = 16
if (h % 16) == 0:
h_pad = 0
else:
h_pad = meta_size - (h % 16)
if (w % 16) == 0:
w_pad = 0
else:
w_pad = meta_size - (w % 16)
pad = mindspore.ops.Zeros(padding=(0, w_pad, 0, h_pad))
x = pad(x)
return x
def check_path(path):
if not os.path.exists(path):
os.makedirs(path)