imicpe 0.0.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- imicpe/__init__.py +0 -0
- imicpe/optim/__init__.py +8 -0
- imicpe/optim/metrics.py +9 -0
- imicpe/optim/operators.py +369 -0
- imicpe/optim/pnnDataset.py +122 -0
- imicpe/optim/pnnTrainer.py +137 -0
- imicpe/optim/pnnUtils.py +52 -0
- imicpe-0.0.9.dist-info/LICENSE +21 -0
- imicpe-0.0.9.dist-info/METADATA +44 -0
- imicpe-0.0.9.dist-info/RECORD +12 -0
- imicpe-0.0.9.dist-info/WHEEL +5 -0
- imicpe-0.0.9.dist-info/top_level.txt +1 -0
imicpe/__init__.py
ADDED
|
File without changes
|
imicpe/optim/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from .metrics import mse, snr
|
|
2
|
+
from .operators import Id, D, Dt, L, Lt, generateDiff3D, generatePSF, A, At, S, St, opNorm, matNorm
|
|
3
|
+
from .pnnDataset import BSDSDataset, NoisyDataset
|
|
4
|
+
from .pnnTrainer import Trainer, Metrics
|
|
5
|
+
from .pnnUtils import chooseDevice, torchImg2Numpy, getData
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
cameraman = os.path.join(os.path.dirname(__file__), 'cameraman.tif')
|
imicpe/optim/metrics.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import ndimage
|
|
4
|
+
import igl
|
|
5
|
+
|
|
6
|
+
############################################################
|
|
7
|
+
## identity operator
|
|
8
|
+
############################################################
|
|
9
|
+
def Id(x):
|
|
10
|
+
"""
|
|
11
|
+
Id Opérateur identité
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
X (numpy.ndarray) signal 1D
|
|
15
|
+
ou: image non vectorisée 2D
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
(numpy.ndarray) X
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
return x
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
############################################################
|
|
25
|
+
## differential forward and backward operators
|
|
26
|
+
############################################################
|
|
27
|
+
# gradient
|
|
28
|
+
def D(x):
|
|
29
|
+
"""
|
|
30
|
+
D Calcule le gradient par différences finies à droite.
|
|
31
|
+
Autrement dit, D(x) calcule le produit matriciel Dx.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
X (numpy.ndarray) signal 1D
|
|
35
|
+
ou: image non vectorisée 2D
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
(numpy.ndarray) Gradient de X
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
if x.ndim == 1:
|
|
42
|
+
grad = np.concatenate((x[1:] - x[:-1], [0]))/2.
|
|
43
|
+
|
|
44
|
+
elif x.ndim == 2:
|
|
45
|
+
sz = x.shape
|
|
46
|
+
Dx_im = np.concatenate(( x[:,1:] - x[:,:-1] , np.zeros((sz[0],1)) ), axis=1)/ 2.
|
|
47
|
+
Dy_im = np.concatenate(( x[1:,:] - x[:-1,:] , np.zeros((1,sz[1])) ), axis=0)/ 2.
|
|
48
|
+
|
|
49
|
+
grad = np.array([Dx_im,Dy_im])
|
|
50
|
+
return grad
|
|
51
|
+
|
|
52
|
+
def Dt(x):
|
|
53
|
+
"""
|
|
54
|
+
Dt Calcule l’adjoint gradient par différences finies à droite.
|
|
55
|
+
Autrement dit, Dt(x) calcule le produit matriciel D'x.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
X (numpy.ndarray) signal 1D
|
|
59
|
+
ou: image non vectorisée 2D
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
(numpy.ndarray) Divergence de X
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
if x.ndim == 1:
|
|
66
|
+
div = - np.concatenate(([x[0]], x[1:-1] - x[:-2], [-x[-2]])) /2.
|
|
67
|
+
|
|
68
|
+
elif x.ndim == 3:
|
|
69
|
+
x1 = x[0]
|
|
70
|
+
x2 = x[1]
|
|
71
|
+
div = - np.concatenate((x1[:,[0]], x1[:,1:-1] - x1[:,:-2], -x1[:,[-2]]), axis=1) /2. \
|
|
72
|
+
- np.concatenate((x2[[0],:], x2[1:-1,:] - x2[:-2,:], -x2[[-2],:]), axis=0) /2.
|
|
73
|
+
return div
|
|
74
|
+
|
|
75
|
+
# laplacian
|
|
76
|
+
def L(x):
|
|
77
|
+
"""
|
|
78
|
+
L Calcule la dérivée seconde d’un signal, ou le laplacien dans le cas d’une image.
|
|
79
|
+
Autrement dit, L(x) calcule le produit matriciel Lx.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
X (numpy.ndarray) signal 1D
|
|
83
|
+
ou: image non vectorisée 2D
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
(numpy.ndarray) Laplacien de X
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
if x.ndim == 1:
|
|
90
|
+
ker = np.array([1, -2, 1])
|
|
91
|
+
#lap = np.convolve(x,ker,'same')
|
|
92
|
+
lap = ndimage.convolve1d(x,ker,mode='nearest')
|
|
93
|
+
elif x.ndim == 2:
|
|
94
|
+
ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
|
|
95
|
+
#ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
|
|
96
|
+
lap = ndimage.convolve(x,ker,mode='nearest')
|
|
97
|
+
return lap
|
|
98
|
+
|
|
99
|
+
def Lt(x):
|
|
100
|
+
"""
|
|
101
|
+
Lt Calcule l’adjoint du laplacien.
|
|
102
|
+
Autrement dit, Lt(x) calcule le produit matriciel L'x.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
X (numpy.ndarray) signal 1D
|
|
106
|
+
ou: image non vectorisée 2D
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
(numpy.ndarray) Adjoint du Laplacien de X
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
if x.ndim == 1:
|
|
113
|
+
ker = np.array([1, -2, 1])
|
|
114
|
+
#lap = np.correlate(x,ker,'same')
|
|
115
|
+
lap = ndimage.correlate1d(x,ker,mode='nearest')
|
|
116
|
+
elif x.ndim == 2:
|
|
117
|
+
ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
|
|
118
|
+
#ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
|
|
119
|
+
lap = ndimage.correlate(x,ker,mode='nearest')
|
|
120
|
+
return lap
|
|
121
|
+
|
|
122
|
+
def generateDiff3D(vert, faces, dtype):
|
|
123
|
+
"""
|
|
124
|
+
generateDiff3D Génère la matrice de différentiation de type DTYPE (ordre 1 ou 2) en 3D
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
VERT (numpy.ndarray) matrice Nx3 dont la i-ème ligne correspond au vecteur
|
|
128
|
+
de coordonnées (X,Y,Z) du i-ème point du maillage
|
|
129
|
+
FACES (numpy.ndarray) matrice Nx3 dont la i-ème ligne donne les numéros des
|
|
130
|
+
3 points composant un triangle du maillage
|
|
131
|
+
DTYPE(str) 'gradient', 'laplacian'
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
(numpy.ndarray) matrice 3D de différentiation de type DTYPE
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
if dtype == 'gradient':
|
|
138
|
+
matG = igl.grad(vert, faces)
|
|
139
|
+
elif dtype == 'laplacien':
|
|
140
|
+
matG = igl.cotmatrix(vert, faces)
|
|
141
|
+
|
|
142
|
+
return (matG/np.amax(matG)).toarray()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
############################################################
|
|
147
|
+
## blurring operators
|
|
148
|
+
############################################################
|
|
149
|
+
def generatePSF(dim,blurtype,kernelSize):
|
|
150
|
+
"""
|
|
151
|
+
generatePSF Génère le noyau de convolution d’un flou de dimension DIM, de type BLURTYPE,
|
|
152
|
+
et de taille KERNELSIZE.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
DIM (str) ’1D’ ou ’2D’
|
|
156
|
+
BLURTYPE (str) ’none’, ’gaussian’ ou ’uniform’
|
|
157
|
+
KERNELSIZE (int) entier impair
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
(numpy.ndarray) Noyau de convolution
|
|
161
|
+
|
|
162
|
+
-> voir les fonctions A(x,h) et At(x,h).
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
# compute kernel
|
|
166
|
+
if blurtype == 'none':
|
|
167
|
+
h = np.array([1.])
|
|
168
|
+
|
|
169
|
+
elif blurtype == 'gaussian':
|
|
170
|
+
std = kernelSize/6
|
|
171
|
+
x = np.linspace(-(kernelSize-1)/2, (kernelSize-1)/2, kernelSize)
|
|
172
|
+
arg = -x**2/(2*std**2)
|
|
173
|
+
h = np.exp(arg)
|
|
174
|
+
|
|
175
|
+
elif blurtype == 'uniform':
|
|
176
|
+
h = np.ones(kernelSize)
|
|
177
|
+
|
|
178
|
+
# kernel normalization
|
|
179
|
+
h = h/sum(h)
|
|
180
|
+
|
|
181
|
+
# return kernel
|
|
182
|
+
if dim == '1D':
|
|
183
|
+
ker = h
|
|
184
|
+
elif dim == '2D':
|
|
185
|
+
ker = np.tensordot(h,h, axes=0)
|
|
186
|
+
|
|
187
|
+
return ker
|
|
188
|
+
|
|
189
|
+
def A(x,psf):
|
|
190
|
+
"""
|
|
191
|
+
A Permet de flouter l’image X par un flou de noyau PSF.
|
|
192
|
+
Autrement dit, A(x,h) calcule le produit de convolution h*x, ou de manière équivalente, calcule
|
|
193
|
+
le produit matriciel Hx.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
X (numpy.ndarray) signal 1D
|
|
197
|
+
ou: image non vectorisée 2D
|
|
198
|
+
PSF (numpy.ndarray) doit être générée à partir de la fonction generatePSF
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
(numpy.ndarray) Convolution de X par le noyau PSF
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
if x.ndim == 1:
|
|
205
|
+
b = np.convolve(x,psf,'same')
|
|
206
|
+
elif x.ndim == 2:
|
|
207
|
+
b = ndimage.convolve(x,psf,mode='nearest')
|
|
208
|
+
|
|
209
|
+
return b
|
|
210
|
+
|
|
211
|
+
def At(x,psf):
|
|
212
|
+
"""
|
|
213
|
+
At Permet de flouter l’image X par un flou de noyau la transposée de PSF.
|
|
214
|
+
Autrement dit, A(x,h) calcule le produit de convolution h'*x, ou de manière équivalente, calcule
|
|
215
|
+
le produit matriciel H'x.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
X (numpy.ndarray) signal 1D
|
|
219
|
+
ou: image non vectorisée 2D
|
|
220
|
+
PSF (numpy.ndarray) doit être générée à partir de la fonction generatePSF
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
(numpy.ndarray) Correlation de X par le noyau PSF
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
if x.ndim == 1:
|
|
227
|
+
b = np.correlate(x,psf,'same')
|
|
228
|
+
elif x.ndim == 2:
|
|
229
|
+
b = ndimage.correlate(x,psf,mode='nearest')
|
|
230
|
+
|
|
231
|
+
return b
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
############################################################
|
|
236
|
+
## TP3 - cartoon + texture decomposition operators (only 2D)
|
|
237
|
+
############################################################
|
|
238
|
+
def S(x):
|
|
239
|
+
"""
|
|
240
|
+
S Convolue X avec un noyau KER.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
X (numpy.ndarray) image non vectorisée 2D
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
(numpy.ndarray) Convolution de X par le noyau KER
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
h,w = x.shape
|
|
250
|
+
|
|
251
|
+
ox = np.linspace(-w/2+1/2, w/2-1/2, w)
|
|
252
|
+
oy = np.linspace(-h/2+1/2, h/2-1/2, h)
|
|
253
|
+
X,Y = np.meshgrid(ox, oy)
|
|
254
|
+
dist = np.sqrt(X**2/w**2 + Y**2/h**2); # anisotropic distance
|
|
255
|
+
n = 5
|
|
256
|
+
fc = 1/3 # in [0,1] since dist is normalized
|
|
257
|
+
ker = 1./(1 + (dist/fc)**(2*n))
|
|
258
|
+
|
|
259
|
+
imf = np.real(np.fft.ifft2(np.fft.ifftshift(ker*np.fft.fftshift(np.fft.fft2(x)))))
|
|
260
|
+
|
|
261
|
+
return imf
|
|
262
|
+
|
|
263
|
+
def St(x):
|
|
264
|
+
"""
|
|
265
|
+
S Corrèle X avec un noyau KER.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
X (numpy.ndarray) image non vectorisée 2D
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
(numpy.ndarray) Correlation de X par le noyau KER
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
h,w = x.shape
|
|
275
|
+
|
|
276
|
+
ox = np.linspace(-w/2+1/2, w/2-1/2, w)
|
|
277
|
+
oy = np.linspace(-h/2+1/2, h/2-1/2, h)
|
|
278
|
+
X,Y = np.meshgrid(ox, oy)
|
|
279
|
+
dist = np.sqrt(X**2/w**2 + Y**2/h**2); # anisotropic distance
|
|
280
|
+
n = 5
|
|
281
|
+
fc = 1/3 # in [0,1] since dist is normalized
|
|
282
|
+
ker = 1./(1 + (dist/fc)**(2*n))
|
|
283
|
+
|
|
284
|
+
imf = np.real(np.fft.ifft2(np.fft.ifftshift(np.conj(ker)*np.fft.fftshift(np.fft.fft2(x)))))
|
|
285
|
+
|
|
286
|
+
return imf
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
############################################################
|
|
291
|
+
## Operator and matrix norm
|
|
292
|
+
############################################################
|
|
293
|
+
def opNorm(op,opt,dim):
|
|
294
|
+
"""
|
|
295
|
+
opNorm Calcule la norme de l'opérateur OP, dont
|
|
296
|
+
l'opérateur transposé est OPT, en dimension DIM
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
OP (function) opérateur direct
|
|
300
|
+
OPT (function) opérateur adjoint
|
|
301
|
+
DIM (str) '1D', '2D'
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
(float) norme de l'opérateur OP
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
def T(x):
|
|
308
|
+
return opt(op(x))
|
|
309
|
+
|
|
310
|
+
if dim == '1D':
|
|
311
|
+
xn = np.random.standard_normal((64))
|
|
312
|
+
elif dim == '2D':
|
|
313
|
+
xn = np.random.standard_normal((64,64))
|
|
314
|
+
|
|
315
|
+
xnn = xn
|
|
316
|
+
|
|
317
|
+
n = np.zeros((1000,),float)
|
|
318
|
+
n[1] = 1
|
|
319
|
+
tol = 1e-4
|
|
320
|
+
rhon = n[1]+2*tol
|
|
321
|
+
|
|
322
|
+
k = 1
|
|
323
|
+
while abs(n[k]-rhon)/n[k] >= tol:
|
|
324
|
+
xn = T(xnn)
|
|
325
|
+
xnn = T(xn)
|
|
326
|
+
|
|
327
|
+
rhon = n[k]
|
|
328
|
+
n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
|
|
329
|
+
|
|
330
|
+
k = k+1
|
|
331
|
+
|
|
332
|
+
N = n[k-1] + 1e-16
|
|
333
|
+
return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def matNorm(M):
|
|
337
|
+
"""
|
|
338
|
+
matNorm Calcule la norme de la matrice M
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
M (numpy.ndarray) matrice dont on souhaite calculer la norme
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
(float) norme de la matrice M
|
|
345
|
+
"""
|
|
346
|
+
|
|
347
|
+
def T(x):
|
|
348
|
+
return np.dot(M.T, np.dot(M,x))
|
|
349
|
+
|
|
350
|
+
xn = np.random.standard_normal((M.shape[1]))
|
|
351
|
+
xnn = xn
|
|
352
|
+
|
|
353
|
+
n = np.zeros((1000,),float)
|
|
354
|
+
n[1] = 1
|
|
355
|
+
tol = 1e-4
|
|
356
|
+
rhon = n[1]+2*tol
|
|
357
|
+
|
|
358
|
+
k = 1
|
|
359
|
+
while abs(n[k]-rhon)/n[k] >= tol:
|
|
360
|
+
xn = T(xnn)
|
|
361
|
+
xnn = T(xn)
|
|
362
|
+
|
|
363
|
+
rhon = n[k]
|
|
364
|
+
n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
|
|
365
|
+
|
|
366
|
+
k = k+1
|
|
367
|
+
|
|
368
|
+
N = n[k-1] + 1e-16
|
|
369
|
+
return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch import Generator
|
|
3
|
+
from torch.utils.data import Dataset, TensorDataset
|
|
4
|
+
from torchvision.transforms import ToTensor
|
|
5
|
+
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
""" dataset classes """
|
|
13
|
+
class BSDSDataset(Dataset):
|
|
14
|
+
def __init__(self, root_dir="data/bsds500", mode="train",
|
|
15
|
+
image_size=(256, 256), image_cnt=None,
|
|
16
|
+
gray=False, device="cpu"):
|
|
17
|
+
""" BSDS500 Dataset construction
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
root_dir: str or Path object
|
|
22
|
+
Local path to the dataset
|
|
23
|
+
mode: str
|
|
24
|
+
Dataset type: "train", "val" or "test"
|
|
25
|
+
image_size: tuple of int
|
|
26
|
+
Crop the image to the given size
|
|
27
|
+
image_cnt: int
|
|
28
|
+
If specified, extract at most the given number of images
|
|
29
|
+
gray: bool
|
|
30
|
+
If True, convert images to grayscale
|
|
31
|
+
device: str or torch.device
|
|
32
|
+
Device where the dataset is created
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
# Properties
|
|
36
|
+
self.root_dir = Path(root_dir)
|
|
37
|
+
self.mode = mode
|
|
38
|
+
self.image_size = image_size
|
|
39
|
+
self.gray = gray
|
|
40
|
+
self.device = device
|
|
41
|
+
|
|
42
|
+
# Create the list of corresponding images (sorted for reprocibility purpose)
|
|
43
|
+
self.image_list = sorted((self.root_dir / self.mode).glob("*.jpg"))
|
|
44
|
+
if image_cnt is not None:
|
|
45
|
+
self.image_list = self.image_list[:image_cnt]
|
|
46
|
+
|
|
47
|
+
def __repr__(self):
|
|
48
|
+
""" Nice representation when displaying the variable """
|
|
49
|
+
return f"BSDSDataset(mode={self.mode}, image_size={self.image_size})"
|
|
50
|
+
|
|
51
|
+
def __len__(self):
|
|
52
|
+
""" Number of samples """
|
|
53
|
+
return len(self.image_list)
|
|
54
|
+
|
|
55
|
+
def __getitem__(self, idx):
|
|
56
|
+
""" Reading a sample """
|
|
57
|
+
|
|
58
|
+
# set image path and id
|
|
59
|
+
image_path = self.image_list[idx]
|
|
60
|
+
image_id = int(image_path.stem)
|
|
61
|
+
|
|
62
|
+
# load and crop clean image
|
|
63
|
+
clean_image = Image.open(image_path).convert('RGB')
|
|
64
|
+
i = max(0, (clean_image.size[0] - self.image_size[0]) // 2)
|
|
65
|
+
j = max(0, (clean_image.size[1] - self.image_size[1]) // 2)
|
|
66
|
+
clean_image = clean_image.crop([
|
|
67
|
+
i, j,
|
|
68
|
+
min(clean_image.size[0], i + self.image_size[0]),
|
|
69
|
+
min(clean_image.size[1], j + self.image_size[1]),
|
|
70
|
+
])
|
|
71
|
+
clean_image = ToTensor()(clean_image).to(self.device) # move to the requested device
|
|
72
|
+
|
|
73
|
+
# optional conversion to grayscale
|
|
74
|
+
if self.gray:
|
|
75
|
+
clean_image = clean_image.mean(-3, keepdim=True)
|
|
76
|
+
|
|
77
|
+
return clean_image, image_id
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class NoisyDataset(Dataset):
|
|
81
|
+
def __init__(self, dataset, degradation_model, sigma=0.1, seed=None):
|
|
82
|
+
""" Noisy Dataset construction
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
dataset: torch.utils.data.Dataset
|
|
87
|
+
Original BSDS dataset
|
|
88
|
+
degradation_model: function handle
|
|
89
|
+
Function modeling the degradation model
|
|
90
|
+
sigma: float
|
|
91
|
+
Standard deviation of the noise (default: 0.1)
|
|
92
|
+
seed: int
|
|
93
|
+
If specified, the whole dataset is reproductible with given seed.
|
|
94
|
+
"""
|
|
95
|
+
self.dataset = dataset
|
|
96
|
+
self.degradation_model = degradation_model
|
|
97
|
+
self.sigma = sigma
|
|
98
|
+
self.seed = seed if seed is not None else Generator().seed()
|
|
99
|
+
|
|
100
|
+
def __repr__(self):
|
|
101
|
+
return f"NoisyDataset(dataset={self.dataset}, sigma={self.sigma})"
|
|
102
|
+
|
|
103
|
+
def __len__(self):
|
|
104
|
+
return len(self.dataset)
|
|
105
|
+
|
|
106
|
+
def __getitem__(self, idx):
|
|
107
|
+
clean_image, image_id = self.dataset[idx]
|
|
108
|
+
|
|
109
|
+
# generate noisy image
|
|
110
|
+
noisy_image = self.degradation_model(clean_image, self.sigma, seed=self.seed)
|
|
111
|
+
|
|
112
|
+
return noisy_image, clean_image, int(image_id)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def toTensorDataset(self):
|
|
116
|
+
""" Store the whole dataset in memory """
|
|
117
|
+
noised_images, clean_images, images_id = zip(*self)
|
|
118
|
+
return TensorDataset(
|
|
119
|
+
torch.stack(noised_images),
|
|
120
|
+
torch.stack(clean_images),
|
|
121
|
+
torch.tensor(images_id),
|
|
122
|
+
)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch.utils.data import DataLoader
|
|
3
|
+
|
|
4
|
+
from tqdm.notebook import tqdm
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
""" Trainer class """
|
|
9
|
+
class Trainer():
|
|
10
|
+
def __init__(self,
|
|
11
|
+
model, optimizer, loss,
|
|
12
|
+
batch_size,
|
|
13
|
+
train_dataset, val_dataset=None,
|
|
14
|
+
check_val_every_n_epoch=1):
|
|
15
|
+
|
|
16
|
+
self.model = model
|
|
17
|
+
self.optimizer = optimizer
|
|
18
|
+
self.loss = loss
|
|
19
|
+
self.batch_size = batch_size
|
|
20
|
+
self.train_dataloader = train_dataset
|
|
21
|
+
self.val_dataloader = val_dataset
|
|
22
|
+
self.check_val_every_n_epoch = check_val_every_n_epoch
|
|
23
|
+
self.metrics = Metrics()
|
|
24
|
+
self.history = {}
|
|
25
|
+
self.epoch = 0
|
|
26
|
+
|
|
27
|
+
# dataloaders
|
|
28
|
+
self.train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
|
|
29
|
+
if self.val_dataloader is None:
|
|
30
|
+
self.val_dataloader = None
|
|
31
|
+
else:
|
|
32
|
+
self.val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=True)
|
|
33
|
+
|
|
34
|
+
def run(self, num_epoch):
|
|
35
|
+
""" Run training until the given number of epochs is reached """
|
|
36
|
+
try:
|
|
37
|
+
# progress bar
|
|
38
|
+
training_pbar = tqdm(
|
|
39
|
+
iterable=range(self.epoch, num_epoch),
|
|
40
|
+
initial=self.epoch,
|
|
41
|
+
total=num_epoch,
|
|
42
|
+
desc="Training",
|
|
43
|
+
unit="epoch"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
for _ in training_pbar:
|
|
47
|
+
self.training_epoch()
|
|
48
|
+
training_pbar.set_postfix(self.history["Training"][-1][1])
|
|
49
|
+
if self.epoch % self.check_val_every_n_epoch == 0:
|
|
50
|
+
self.validation_epoch()
|
|
51
|
+
epoch, metrics = self.history["Validation"][-1]
|
|
52
|
+
print(f"Validation epoch {epoch:4d} | " + " | ".join((f"{k}: {v:.2e}" for k, v in metrics.items())))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
except KeyboardInterrupt:
|
|
56
|
+
""" Stop training if Ctrl-C is pressed """
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
def training_epoch(self):
|
|
60
|
+
""" Train for one epoch """
|
|
61
|
+
device = self.device
|
|
62
|
+
self.metrics.init()
|
|
63
|
+
for x, target, *_ in self.train_dataloader:
|
|
64
|
+
x = x.to(device)
|
|
65
|
+
target = target.to(device)
|
|
66
|
+
|
|
67
|
+
y = self.model(x)
|
|
68
|
+
loss = self.loss(y, target)
|
|
69
|
+
self.optimizer.zero_grad()
|
|
70
|
+
loss.backward()
|
|
71
|
+
self.optimizer.step()
|
|
72
|
+
|
|
73
|
+
self.metrics.accumulate(loss, x, y, target)
|
|
74
|
+
|
|
75
|
+
self.epoch += 1
|
|
76
|
+
self.log("Training", self.epoch, self.metrics.summarize())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def validation_epoch(self):
|
|
80
|
+
""" Run a validation step """
|
|
81
|
+
if self.val_dataloader is None:
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
device = self.device
|
|
85
|
+
self.metrics.init()
|
|
86
|
+
with torch.no_grad():
|
|
87
|
+
for x, target, *_ in self.val_dataloader:
|
|
88
|
+
x = x.to(device)
|
|
89
|
+
target = target.to(device)
|
|
90
|
+
|
|
91
|
+
y = self.model(x)
|
|
92
|
+
loss = self.loss(y, target)
|
|
93
|
+
|
|
94
|
+
self.metrics.accumulate(loss, x, y, target)
|
|
95
|
+
|
|
96
|
+
self.log("Validation", self.epoch, self.metrics.summarize())
|
|
97
|
+
|
|
98
|
+
def log(self, mode, epoch, metrics):
|
|
99
|
+
history = self.history.setdefault(mode, [])
|
|
100
|
+
history.append((epoch, metrics))
|
|
101
|
+
#print(f"{mode} epoch {epoch:4d} | " + " | ".join((f"{k}: {v:.2e}" for k, v in metrics.items())))
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def device(self):
|
|
105
|
+
""" Training device defined from the device of the first parameter of the model """
|
|
106
|
+
return next(self.model.parameters()).device
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Metrics:
|
|
112
|
+
""" Compute metrics from training and validation steps """
|
|
113
|
+
def init(self):
|
|
114
|
+
self.metrics = dict()
|
|
115
|
+
self.cnt = 0
|
|
116
|
+
self.tic = time.perf_counter()
|
|
117
|
+
|
|
118
|
+
def accumulate(self, loss, x, y, target):
|
|
119
|
+
with torch.no_grad():
|
|
120
|
+
self.metrics["Loss"] = self.metrics.get("Loss", 0) + loss.item()
|
|
121
|
+
self.metrics["PSNR"] = self.metrics.get("PSNR", 0) + self.__PSNR__(y, target).mean().item()
|
|
122
|
+
self.cnt += 1
|
|
123
|
+
|
|
124
|
+
def summarize(self):
|
|
125
|
+
self.toc = time.perf_counter()
|
|
126
|
+
metrics = {k: v / self.cnt for k, v in self.metrics.items()}
|
|
127
|
+
metrics["Wall time"] = self.toc - self.tic
|
|
128
|
+
return metrics
|
|
129
|
+
|
|
130
|
+
def __PSNR__(self, img1, img2):
|
|
131
|
+
# optional: get last 3 dimensions (CxNxM) to ensure compatibility with a single sample
|
|
132
|
+
dims = list(range(max(0, img1.ndim - 3), img1.ndim))
|
|
133
|
+
# otherwise:
|
|
134
|
+
#dims = list(range(1, img1.ndim))
|
|
135
|
+
|
|
136
|
+
# necessity to take the mean along only the last 3 dimensions
|
|
137
|
+
return 10 * torch.log10(1. / (img1 - img2).pow(2).mean(dims))
|
imicpe/optim/pnnUtils.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def chooseDevice(device=None):
|
|
5
|
+
if device == None:
|
|
6
|
+
# setting device on GPU if available, else MPS (Apple M1) or CPU
|
|
7
|
+
if torch.cuda.is_available():
|
|
8
|
+
device = torch.device('cuda') # CUDA backend for NVIDIA or AMD graphic cards
|
|
9
|
+
else:
|
|
10
|
+
try:
|
|
11
|
+
if torch.backends.mps.is_available():
|
|
12
|
+
device = torch.device('mps') # MPS for Apple M# processors
|
|
13
|
+
else:
|
|
14
|
+
device = torch.device('cpu')
|
|
15
|
+
except AttributeError:
|
|
16
|
+
device = torch.device('cpu')
|
|
17
|
+
else:
|
|
18
|
+
device = torch.device(device)
|
|
19
|
+
|
|
20
|
+
print('Using device:', device)
|
|
21
|
+
print()
|
|
22
|
+
|
|
23
|
+
# additional info when using cuda
|
|
24
|
+
if device.type == 'cuda':
|
|
25
|
+
print(torch.cuda.get_device_name(0))
|
|
26
|
+
print('Memory Usage:')
|
|
27
|
+
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
|
|
28
|
+
print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
|
|
29
|
+
|
|
30
|
+
return device
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def torchImg2Numpy(image):
|
|
35
|
+
# reorder dimensions (C, N, M) -> (M, N, C) and move to CPU
|
|
36
|
+
image = torch.moveaxis(image, [0, 1, 2], [2, 0, 1]).to('cpu')
|
|
37
|
+
|
|
38
|
+
if image.shape[-1] == 1:
|
|
39
|
+
image = image[..., 0]
|
|
40
|
+
|
|
41
|
+
return image.numpy()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def getData(trainer, mode):
|
|
45
|
+
data = dict()
|
|
46
|
+
for epoch, record in trainer.history[mode]:
|
|
47
|
+
data.setdefault("epoch", []).append(epoch)
|
|
48
|
+
for metric, value in record.items():
|
|
49
|
+
data.setdefault(metric, []).append(value)
|
|
50
|
+
|
|
51
|
+
return data
|
|
52
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [year] [fullname]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: imicpe
|
|
3
|
+
Version: 0.0.9
|
|
4
|
+
Summary: Toolbox for Maths,Signal,Image Teaching @ CPE
|
|
5
|
+
Author-email: Marion Foare <marion.foare@cpe.fr>, Eric Van Reeth <eric.vanreeth@cpe.fr>, Arthur Gautheron <arthur.gautheron@cpe.fr>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Project-URL: Homepage, https://www.cpe.fr
|
|
8
|
+
Project-URL: Documentation, https://toolbox-imi-cpe-msi-1bcfcdd75992c038486502447f7f6937f3492f60127.pages.in2p3.fr/
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
|
|
18
|
+
Developped and maintained for teaching usage only!
|
|
19
|
+
|
|
20
|
+
# Installation
|
|
21
|
+
|
|
22
|
+
## In a Jupyter Notebook
|
|
23
|
+
|
|
24
|
+
```!pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
25
|
+
|
|
26
|
+
## In a local environment
|
|
27
|
+
|
|
28
|
+
```pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
29
|
+
|
|
30
|
+
# Usage example
|
|
31
|
+
|
|
32
|
+
The example below uses the kurtosis method available in the `tsa` subpackage of `msicpe`.
|
|
33
|
+
It requires `numpy.randn` to generate a gaussian distribution of N points.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import numpy as np
|
|
37
|
+
from msicpe.tsa import kurtosis
|
|
38
|
+
N=10000
|
|
39
|
+
|
|
40
|
+
x=np.randn(1,N)
|
|
41
|
+
kurt=kurtosis(x)
|
|
42
|
+
|
|
43
|
+
print(kurt)
|
|
44
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
imicpe/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
imicpe/optim/__init__.py,sha256=m3A1xTbMnHMqOx8EFWi71BRyVmlCdVL4qtNYWct0rjQ,360
|
|
3
|
+
imicpe/optim/metrics.py,sha256=AHqudKDch1_jc7X2_9hz30RamEqfQ132GXr3qW81VPY,187
|
|
4
|
+
imicpe/optim/operators.py,sha256=xYhXc4CSA6MN1mlsaS3LnvIIOBIu-OjY3uVA8liuTgc,10859
|
|
5
|
+
imicpe/optim/pnnDataset.py,sha256=PFh5u0SXx761O6N6vVfWfEDmzmCm87eYzAL7mWHBRrw,3971
|
|
6
|
+
imicpe/optim/pnnTrainer.py,sha256=3ygh9XwFJN7jMPsEG3LHLa8sgBbDd9Yu_QWg4ZtM_DM,4571
|
|
7
|
+
imicpe/optim/pnnUtils.py,sha256=LXU7wRfuEi6t-2VG2NStPAOzu19OKTxzNNnbHESpC2U,1523
|
|
8
|
+
imicpe-0.0.9.dist-info/LICENSE,sha256=ACwmltkrXIz5VsEQcrqljq-fat6ZXAMepjXGoe40KtE,1069
|
|
9
|
+
imicpe-0.0.9.dist-info/METADATA,sha256=05KEy34rdvtqfn10vIYHe7wc9Aq-eP8G3hX3EImLN6M,1272
|
|
10
|
+
imicpe-0.0.9.dist-info/WHEEL,sha256=uCRv0ZEik_232NlR4YDw4Pv3Ajt5bKvMH13NUU7hFuI,91
|
|
11
|
+
imicpe-0.0.9.dist-info/top_level.txt,sha256=6_gSXCYolzjXHaIDeAsZ_M3nLXdqrMKt48XCz3reJc0,7
|
|
12
|
+
imicpe-0.0.9.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
imicpe
|