-
Notifications
You must be signed in to change notification settings - Fork 3
/
UtilityMine.py
278 lines (240 loc) · 8.97 KB
/
UtilityMine.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
#from utils.denoising_utils import *
from numpy import linalg as LA
import numpy as np
#from skimage._shared import *
#from skimage.util import *
#from skimage.metrics.simple_metrics import _as_floats
#from skimage.metrics.simple_metrics import mean_squared_error
#from skimage._shared.utils import *
#from pymf.dist import l1_distance
dtype_range = {np.bool_: (False, True),
np.bool8: (False, True),
np.float16: (-1, 1),
np.float32: (-1, 1),
np.float64: (-1, 1)}
import torch
import torch.nn as nn
def fill_noise(x, noise_type):
"""Fills tensor `x` with noise of type `noise_type`."""
if noise_type == 'u':
x.uniform_()
elif noise_type == 'n':
x.normal_()
else:
assert False
def get_noise(input_depth, method, spatial_size, noise_type='u', var=1./10):
"""Returns a pytorch.Tensor of size (1 x `input_depth` x `spatial_size[0]` x `spatial_size[1]`)
initialized in a specific way.
Args:
input_depth: number of channels in the tensor
method: `noise` for fillting tensor with noise; `meshgrid` for np.meshgrid
spatial_size: spatial size of the tensor to initialize
noise_type: 'u' for uniform; 'n' for normal
var: a factor, a noise will be multiplicated by. Basically it is standard deviation scaler.
"""
if isinstance(spatial_size, int):
spatial_size = (spatial_size, spatial_size)
if method == 'noise':
shape = [1, input_depth, spatial_size[0], spatial_size[1]]
net_input = torch.zeros(shape)
fill_noise(net_input, noise_type)
net_input *= var
elif method == 'meshgrid':
assert input_depth == 2
X, Y = np.meshgrid(np.arange(0, spatial_size[1])/float(spatial_size[1]-1), np.arange(0, spatial_size[0])/float(spatial_size[0]-1))
meshgrid = np.concatenate([X[None,:], Y[None,:]])
net_input= torch.from_numpy(meshgrid)
else:
assert False
return net_input
def get_params(opt_over, net, net_input, downsampler=None):
'''Returns parameters that we want to optimize over.
Args:
opt_over: comma separated list, e.g. "net,input" or "net"
net: network
net_input: torch.Tensor that stores input `z`
'''
opt_over_list = opt_over.split(',')
params = []
for opt in opt_over_list:
if opt == 'net':
params += [x for x in net.parameters() ]
elif opt=='down':
assert downsampler is not None
params = [x for x in downsampler.parameters()]
elif opt == 'input':
net_input.requires_grad = True
params += [net_input]
else:
assert False, 'what is it?'
return params
def compare_snr(image_true, image_test, *, data_range=None):
"""
Compute the signal to noise ratio (PSNR) for an image.
"""
check_shape_equality(image_true, image_test)
if data_range is None:
if image_true.dtype != image_test.dtype:
warn("Inputs have mismatched dtype. Setting data_range based on "
"im_true.", stacklevel=2)
dmin, dmax = dtype_range[image_true.dtype.type]
true_min, true_max = np.min(image_true), np.max(image_true)
if true_max > dmax or true_min < dmin:
raise ValueError(
"im_true has intensity values outside the range expected for "
"its data type. Please manually specify the data_range")
if true_min >= 0:
# most common case (255 for uint8, 1 for float)
data_range = dmax
else:
data_range = dmax - dmin
image_true, image_test = _as_floats(image_true, image_test)
err = mean_squared_error(image_true, image_test)
return 10 * np.log10((np.mean(image_test ** 2, dtype=np.float64)) / err)
def find_endmember(EE,E):
"""
Find the closest matches to E from EE in terms of l_2 norm
"""
n1=EE.shape[1];
n2=E.shape[1];
error=np.zeros((1,n1))
index=np.zeros((n2))
for i in range(n2):
for j in range(n1):
error[0,j]= np.linalg.norm(E[:,i]-EE[:,j],2)
b=np.argmin(error,axis=1)
index[i] = b
E_est = EE[:,index[0:n2].astype(int)]
return E_est
def add_noise(img_np, sigma):
"""Adds Gaussian noise to an image.
Args:
img_np: image, np.array with values from 0 to 1
sigma: std of the noise
"""
"""
img_noisy_np = np.clip(img_np + np.random.normal(scale=sigma, size=img_np.shape), 0, 1).astype(np.float32)
img_noisy_pil = np_to_pil(img_noisy_np)
return img_noisy_pil, img_noisy_np
"""
img_noisy_np = img_np + np.random.normal(scale=sigma, size=img_np.shape)
return img_noisy_np
def Eucli_dist(x,y):
a=np.subtract(x, y)
return np.dot(a.T,a)
def Endmember_reorder(x):
[D,N]=x.shape
a=np.zeros((N,1))
for i in range(N):
a[i,0]=np.dot(x[:,i].T,x[:,i])
per=np.argsort(a,axis=0)
# I=np.sort(a)
return per
def Endmember_reorder2(A,E1):
index = []
_,p=A.shape
error=np.zeros((1,p))
for l in range(p):
for n in range(p):
error[0,n] = Eucli_dist(A[:,l],E1[:,n])
b=np.argmin(error)
index=np.append(index,b)
index=index.astype(int)
return index
# def Vec_1d(x):
# [D,N]=x.shape
# if D==1:
# y=np.reshape(x,(1,N))
# elif N==1:
# y=np.reshape(x,(D,1))
# return y
def Endmember_extract(x,p):
[D,N]=x.shape
# If no distf given, use Euclidean distance function
Z1=np.zeros((1,1))
O1=np.ones((1,1))
# Find farthest point
d=np.zeros((p,N))
I=np.zeros((p,1))
V=np.zeros((1,N))
ZD=np.zeros((D,1))
# if nargin<4
for i in range(N):
d[0,i]=Eucli_dist(x[:,i].reshape(D,1),ZD)
# d[0,i]=l1_distance(x[:,i].reshape(D,1),ZD)
# else
# for i=1:N
# d(1,i)=distf(x(:,i),zeros(D,1),opt);
I=np.argmax(d[0,:])
#if nargin<4
for i in range(N):
d[0,i] = Eucli_dist(x[:,i].reshape(D,1),x[:,I].reshape(D,1))
# d[0,i] = l1_distance(x[:,i].reshape(D,1),x[:,I].reshape(D,1))
# else
# for i=1:N
# d(1,i)=distf(x(:,i),x(:,I(1)),opt);
for v in range(1,p):
#D=[d[0:v-2,I] ; np.ones((1,v-1)) 0]
D1=np.concatenate((d[0:v,I].reshape((v,I.size)), np.ones((v,1))),axis=1)
D2=np.concatenate((np.ones((1,v)),Z1),axis=1)
D4=np.concatenate((D1,D2),axis=0)
D4=np.linalg.inv(D4)
for i in range(N):
D3=np.concatenate((d[0:v,i].reshape((v,1)), O1),axis=0)
V[0,i]=np.dot(np.dot(D3.T,D4),D3)
I=np.append(I,np.argmax(V))
# if nargin<4
for i in range(N):
#d[v,i]=l1_distance(x[:,i].reshape(D,1),x[:,I[v]].reshape(D,1))
d[v,i]=Eucli_dist(x[:,i].reshape(D,1),x[:,I[v]].reshape(D,1))
# else
# for i=1:N
# d(v,i)=distf(x(:,i),x(:,I(v)),opt);
per=np.argsort(I)
I=np.sort(I)
d=d[per,:]
return I, d
def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero', downsample_mode='stride'):
downsampler = None
if stride != 1 and downsample_mode != 'stride':
if downsample_mode == 'avg':
downsampler = nn.AvgPool2d(stride, stride)
elif downsample_mode == 'max':
downsampler = nn.MaxPool2d(stride, stride)
elif downsample_mode in ['lanczos2', 'lanczos3']:
downsampler = Downsampler(n_planes=out_f, factor=stride, kernel_type=downsample_mode, phase=0.5, preserve_size=True)
else:
assert False
stride = 1
padder = None
to_pad = int((kernel_size - 1) / 2)
if pad == 'reflection':
padder = nn.ReflectionPad2d(to_pad)
to_pad = 0
convolver = nn.Conv2d(in_f, out_f, kernel_size, stride, padding=to_pad, bias=bias)
layers = filter(lambda x: x is not None, [padder, convolver, downsampler])
return nn.Sequential(*layers)
def torch_dim(x,dim):
return torch.sqrt(torch.sum(x*x,dim));
def remove_norm(x):
# [D,N]=x.shape
# for i in range(N):
# x[:,i] = x[:,i]/LA.norm(x[:,i], axis=0)
# return x
return x/LA.norm(x, axis=0)
def remove_norm_torch(x):
# [D,N]=x.shape
# for i in range(N):
# x[:,i] = x[:,i]/torch.norm(x, p=2, dim=0)
# return x
return torch.div(x, torch.norm(x, p=2, dim=0))
def np_to_torch(img_np):
'''Converts image in numpy.array to torch.Tensor.
From C x W x H [0..1] to C x W x H [0..1]
'''
return torch.from_numpy(img_np)[None, :]
def torch_to_np(img_var):
'''Converts an image in torch.Tensor format to np.array.
From 1 x C x W x H [0..1] to C x W x H [0..1]
'''
return img_var.detach().cpu().numpy()[0]