-
Notifications
You must be signed in to change notification settings - Fork 0
/
A_1k_arg_sampling.py
1315 lines (1052 loc) · 56.8 KB
/
A_1k_arg_sampling.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
import datetime
import os
from random import betavariate
import sys
import pandas as pd
sys.path.append('..')
import copy
import functools
import matplotlib.pyplot as plt
import torch
import numpy as np
import abc
from models.utils import from_flattened_numpy, to_flattened_numpy, get_score_fn
from scipy import integrate, io
from holo_tool import *
import sde_lib
from models import utils as mutils
from skimage.metrics import peak_signal_noise_ratio as compare_psnr, structural_similarity as compare_ssim, \
mean_squared_error as compare_mse
# import odl
import glob
import pydicom
from cv2 import imwrite, resize
from func_test import WriteInfo
from scipy.io import loadmat, savemat
from radon_utils import (create_sinogram, bp, filter_op,
fbp, reade_ima, write_img, sinogram_2c_to_img,
padding_img, unpadding_img, indicate)
from time import sleep
from skimage.metrics import peak_signal_noise_ratio as psnr, structural_similarity as ssim, \
mean_squared_error as mse
from cv2 import imwrite, resize
_CORRECTORS = {}
_PREDICTORS = {}
def set_predict(num):
if num == 0:
return 'None'
elif num == 1:
return 'EulerMaruyamaPredictor'
elif num == 2:
return 'ReverseDiffusionPredictor'
def set_correct(num):
if num == 0:
return 'None'
elif num == 1:
return 'LangevinCorrector'
elif num == 2:
return 'AnnealedLangevinDynamics'
def register_predictor(cls=None, *, name=None):
"""A decorator for registering predictor classes."""
def _register(cls):
if name is None:
local_name = cls.__name__
else:
local_name = name
if local_name in _PREDICTORS:
raise ValueError(f'Already registered model with name: {local_name}')
_PREDICTORS[local_name] = cls
return cls
if cls is None:
return _register
else:
return _register(cls)
def register_corrector(cls=None, *, name=None):
"""A decorator for registering corrector classes."""
def _register(cls):
if name is None:
local_name = cls.__name__
else:
local_name = name
if local_name in _CORRECTORS:
raise ValueError(f'Already registered model with name: {local_name}')
_CORRECTORS[local_name] = cls
return cls
if cls is None:
return _register
else:
return _register(cls)
def get_predictor(name):
return _PREDICTORS[name]
def get_corrector(name):
return _CORRECTORS[name]
def get_sampling_fn(config, sde, shape, inverse_scaler, eps):
"""Create a sampling function.
Args:
config: A `ml_collections.ConfigDict` object that contains all configuration information.
sde: A `sde_lib.SDE` object that represents the forward SDE.
shape: A sequence of integers representing the expected shape of a single sample.
inverse_scaler: The inverse data normalizer function.
eps: A `float` number. The reverse-time SDE is only integrated to `eps` for numerical stability.
Returns:
A function that takes random states and a replicated training state and outputs samples with the
trailing dimensions matching `shape`.
"""
sampler_name = config.sampling.method # pc
# Probability flow ODE sampling with black-box ODE solvers
if sampler_name.lower() == 'ode':
sampling_fn = get_ode_sampler(sde=sde,
shape=shape,
inverse_scaler=inverse_scaler,
denoise=config.sampling.noise_removal,
eps=eps,
device=config.device)
# Predictor-Corrector sampling. Predictor-only and Corrector-only samplers are special cases.
elif sampler_name.lower() == 'pc':
predictor = get_predictor(config.sampling.predictor.lower())
corrector = get_corrector(config.sampling.corrector.lower())
sampling_fn = get_pc_sampler(sde=sde,
shape=shape,
predictor=predictor,
corrector=corrector,
inverse_scaler=inverse_scaler,
snr=config.sampling.snr,
n_steps=config.sampling.n_steps_each,
probability_flow=config.sampling.probability_flow,
continuous=config.training.continuous,
denoise=config.sampling.noise_removal,
eps=eps,
device=config.device)
else:
raise ValueError(f"Sampler name {sampler_name} unknown.")
return sampling_fn
class Predictor(abc.ABC):
"""The abstract class for a predictor algorithm."""
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__()
self.sde = sde
# Compute the reverse SDE/ODE
self.rsde = sde.reverse(score_fn, probability_flow)
self.score_fn = score_fn
@abc.abstractmethod
def update_fn(self, x, t):
"""One update of the predictor.
Args:
x: A PyTorch tensor representing the current state
t: A Pytorch tensor representing the current time step.
Returns:
x: A PyTorch tensor of the next state.
x_mean: A PyTorch tensor. The next state without random noise. Useful for denoising.
"""
pass
class Corrector(abc.ABC):
"""The abstract class for a corrector algorithm."""
def __init__(self, sde, score_fn, snr, n_steps):
super().__init__()
self.sde = sde
self.score_fn = score_fn
self.snr = snr
self.n_steps = n_steps
@abc.abstractmethod
def update_fn(self, x, t):
"""One update of the corrector.
Args:
x: A PyTorch tensor representing the current state
t: A PyTorch tensor representing the current time step.
Returns:
x: A PyTorch tensor of the next state.
x_mean: A PyTorch tensor. The next state without random noise. Useful for denoising.
"""
pass
@register_predictor(name='euler_maruyama')
class EulerMaruyamaPredictor(Predictor):
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow)
def update_fn(self, x, t):
dt = -1. / self.rsde.N
z = torch.randn_like(x)
drift, diffusion = self.rsde.sde(x, t)
x_mean = x + drift * dt
x = x_mean + diffusion[:, None, None, None] * np.sqrt(-dt) * z
return x, x_mean
# ===================================================================== ReverseDiffusionPredictor
@register_predictor(name='reverse_diffusion')
class ReverseDiffusionPredictor(Predictor):
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow)
def update_fn(self, x, t):
f, G = self.rsde.discretize(x, t)
z = torch.randn_like(x)
x_mean = x - f
x = x_mean + G[:, None, None, None] * z
return x, x_mean
# =====================================================================
@register_predictor(name='ancestral_sampling')
class AncestralSamplingPredictor(Predictor):
"""The ancestral sampling predictor. Currently only supports VE/VP SDEs."""
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow)
if not isinstance(sde, sde_lib.VPSDE) and not isinstance(sde, sde_lib.VESDE):
raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.")
assert not probability_flow, "Probability flow not supported by ancestral sampling"
def vesde_update_fn(self, x, t):
sde = self.sde
timestep = (t * (sde.N - 1) / sde.T).long()
sigma = sde.discrete_sigmas[timestep]
adjacent_sigma = torch.where(timestep == 0, torch.zeros_like(t), sde.discrete_sigmas.to(t.device)[timestep - 1])
score = self.score_fn(x, t)
x_mean = x + score * (sigma ** 2 - adjacent_sigma ** 2)[:, None, None, None]
std = torch.sqrt((adjacent_sigma ** 2 * (sigma ** 2 - adjacent_sigma ** 2)) / (sigma ** 2))
noise = torch.randn_like(x)
x = x_mean + std[:, None, None, None] * noise
return x, x_mean
def vpsde_update_fn(self, x, t):
sde = self.sde
timestep = (t * (sde.N - 1) / sde.T).long()
beta = sde.discrete_betas.to(t.device)[timestep]
score = self.score_fn(x, t)
x_mean = (x + beta[:, None, None, None] * score) / torch.sqrt(1. - beta)[:, None, None, None]
noise = torch.randn_like(x)
x = x_mean + torch.sqrt(beta)[:, None, None, None] * noise
return x, x_mean
def update_fn(self, x, t):
if isinstance(self.sde, sde_lib.VESDE):
return self.vesde_update_fn(x, t)
elif isinstance(self.sde, sde_lib.VPSDE):
return self.vpsde_update_fn(x, t)
@register_predictor(name='none')
class NonePredictor(Predictor):
"""An empty predictor that does nothing."""
def __init__(self, sde, score_fn, probability_flow=False):
pass
def update_fn(self, x, t):
return x, x
# ================================================================================================== LangevinCorrector
@register_corrector(name='langevin')
class LangevinCorrector(Corrector):
def __init__(self, sde, score_fn, snr, n_steps):
super().__init__(sde, score_fn, snr, n_steps)
if not isinstance(sde, sde_lib.VPSDE) \
and not isinstance(sde, sde_lib.VESDE) \
and not isinstance(sde, sde_lib.subVPSDE):
raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.")
def update_fn(self, x, t):
sde = self.sde
score_fn = self.score_fn
n_steps = self.n_steps
target_snr = self.snr
if isinstance(sde, sde_lib.VPSDE) or isinstance(sde, sde_lib.subVPSDE):
timestep = (t * (sde.N - 1) / sde.T).long()
alpha = sde.alphas.to(t.device)[timestep]
else:
alpha = torch.ones_like(t)
for i in range(n_steps):
grad = score_fn(x, t)
noise = torch.randn_like(x)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
step_size = (target_snr * noise_norm / grad_norm) ** 2 * 2 * alpha
x_mean = x + step_size[:, None, None, None] * grad
x = x_mean + torch.sqrt(step_size * 2)[:, None, None, None] * noise
return x, x_mean
# ==================================================================================================
@register_corrector(name='ald')
class AnnealedLangevinDynamics(Corrector):
"""The original annealed Langevin dynamics predictor in NCSN/NCSNv2.
We include this corrector only for completeness. It was not directly used in our paper.
"""
def __init__(self, sde, score_fn, snr, n_steps):
super().__init__(sde, score_fn, snr, n_steps)
if not isinstance(sde, sde_lib.VPSDE) \
and not isinstance(sde, sde_lib.VESDE) \
and not isinstance(sde, sde_lib.subVPSDE):
raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.")
def update_fn(self, x, t):
sde = self.sde
score_fn = self.score_fn
n_steps = self.n_steps
target_snr = self.snr
if isinstance(sde, sde_lib.VPSDE) or isinstance(sde, sde_lib.subVPSDE):
timestep = (t * (sde.N - 1) / sde.T).long()
alpha = sde.alphas.to(t.device)[timestep]
else:
alpha = torch.ones_like(t)
std = self.sde.marginal_prob(x, t)[1]
for i in range(n_steps):
grad = score_fn(x, t)
noise = torch.randn_like(x)
step_size = (target_snr * std) ** 2 * 2 * alpha
x_mean = x + step_size[:, None, None, None] * grad
x = x_mean + noise * torch.sqrt(step_size * 2)[:, None, None, None]
return x, x_mean
@register_corrector(name='none')
class NoneCorrector(Corrector):
"""An empty corrector that does nothing."""
def __init__(self, sde, score_fn, snr, n_steps):
pass
def update_fn(self, x, t):
return x, x
# ========================================================================================================
def shared_predictor_update_fn(x, t, sde, model, predictor, probability_flow, continuous):
"""A wrapper that configures and returns the update function of predictors."""
score_fn = mutils.get_score_fn(sde, model, train=False, continuous=continuous)
if predictor is None:
# Corrector-only sampler
predictor_obj = NonePredictor(sde, score_fn, probability_flow)
else:
predictor_obj = predictor(sde, score_fn, probability_flow)
return predictor_obj.update_fn(x, t)
def shared_corrector_update_fn(x, t, sde, model, corrector, continuous, snr, n_steps):
"""A wrapper tha configures and returns the update function of correctors."""
score_fn = mutils.get_score_fn(sde, model, train=False, continuous=continuous)
if corrector is None:
# Predictor-only sampler
corrector_obj = NoneCorrector(sde, score_fn, snr, n_steps)
else:
corrector_obj = corrector(sde, score_fn, snr, n_steps)
return corrector_obj.update_fn(x, t)
# ========================================================================================================
def get_pc_sampler(sde, predictor, corrector, inverse_scaler, snr,
n_steps=1, probability_flow=False, continuous=False,
denoise=True, eps=1e-3, device='cuda', zl_arg=-1):
"""Create a Predictor-Corrector (PC) sampler.
Args:
sde: An `sde_lib.SDE` object representing the forward SDE.
shape: A sequence of integers. The expected shape of a single sample.
predictor: A subclass of `sampling.Predictor` representing the predictor algorithm.
corrector: A subclass of `sampling.Corrector` representing the corrector algorithm.
inverse_scaler: The inverse data normalizer.
snr: A `float` number. The signal-to-noise ratio for configuring correctors.
n_steps: An integer. The number of corrector steps per predictor update.
probability_flow: If `True`, solve the reverse-time probability flow ODE when running the predictor.
continuous: `True` indicates that the score model was continuously trained.
denoise: If `True`, add one-step denoising to the final samples.
eps: A `float` number. The reverse-time SDE and ODE are integrated to `epsilon` to avoid numerical issues.
device: PyTorch device.
Returns:
A sampling function that returns samples and the number of function evaluations during sampling.
"""
# Create predictor & corrector update functions
predictor_update_fn = functools.partial(shared_predictor_update_fn,
sde=sde,
predictor=predictor,
probability_flow=probability_flow,
continuous=continuous)
corrector_update_fn = functools.partial(shared_corrector_update_fn,
sde=sde,
corrector=corrector,
continuous=continuous,
snr=snr,
n_steps=n_steps)
def pc_sampler(img_model, check_num, predict, correct):
# path = glob.glob("./Test_CT/*")
# holoBatch = loadmat('./gt/all/gt_batch_holo.mat')['data']
psnrAll = [0, 0, 0]
ssimAll = [0, 0, 0]
mseAll = [0, 0, 0]
# ***********************************picNO
testNUM = 100
padding = 1200
M, N = 512, 512
sparse_cj = -1
SSN = -1
holo_result = np.zeros([testNUM, padding, padding])
amp_result = np.zeros([testNUM, padding, padding])
phase_result = np.zeros([testNUM, padding, padding])
for picNO in range(0, testNUM):
with torch.no_grad():
# region tool
def addNoise_king(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
img_sparse[SG: SG + T, SG: SG + T] = img[SG: SG + T, SG: SG + T]
img_sparse[SG: SG + T, BG: BG + T] = img[SG: SG + T, BG: BG + T]
img_sparse[BG: BG + T, SG: SG + T] = img[BG: BG + T, SG: SG + T]
img_sparse[BG: BG + T, BG: BG + T] = img[BG: BG + T, BG: BG + T]
return img_sparse
def DC_king(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img[SG: SG + T, SG: SG + T] = gtImg[SG: SG + T, SG: SG + T]
img[SG: SG + T, BG: BG + T] = gtImg[SG: SG + T, BG: BG + T]
img[BG: BG + T, SG: SG + T] = gtImg[BG: BG + T, SG: SG + T]
img[BG: BG + T, BG: BG + T] = gtImg[BG: BG + T, BG: BG + T]
return img
# 稀疏角与resize,只支持R2R3R4
def addNoise_sparse(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
block1 = img[SG: SG + T: sparse_cj, SG: SG + T]
block1 = resize(block1, (T, T))
block2 = img[SG: SG + T: sparse_cj, BG: BG + T]
block2 = resize(block2, (T, T))
block3 = img[BG: BG + T: sparse_cj, SG: SG + T]
block3 = resize(block3, (T, T))
block4 = img[BG: BG + T: sparse_cj, BG: BG + T]
block4 = resize(block4, (T, T))
img_sparse[SG: SG + T, SG: SG + T] = block1
img_sparse[SG: SG + T, BG: BG + T] = block2
img_sparse[BG: BG + T, SG: SG + T] = block3
img_sparse[BG: BG + T, BG: BG + T] = block4
return img_sparse
def DC_sparse(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
# img[SG: SG + T : sparse_cj, SG: SG + T] = gtImg[SG: SG + T: sparse_cj, SG: SG + T]
# img[SG: SG + T: sparse_cj, BG: BG + T] = gtImg[SG: SG + T: sparse_cj, BG: BG + T]
# img[BG: BG + T: sparse_cj, SG: SG + T] = gtImg[BG: BG + T: sparse_cj, SG: SG + T]
# img[BG: BG + T: sparse_cj, BG: BG + T] = gtImg[BG: BG + T: sparse_cj, BG: BG + T]
block1 = gtImg[SG: SG + T: sparse_cj, SG: SG + T]
block1 = resize(block1, (T, T))
block2 = gtImg[SG: SG + T: sparse_cj, BG: BG + T]
block2 = resize(block2, (T, T))
block3 = gtImg[BG: BG + T: sparse_cj, SG: SG + T]
block3 = resize(block3, (T, T))
block4 = gtImg[BG: BG + T: sparse_cj, BG: BG + T]
block4 = resize(block4, (T, T))
img[SG: SG + T, SG: SG + T] = block1
img[SG: SG + T, BG: BG + T] = block2
img[BG: BG + T, SG: SG + T] = block3
img[BG: BG + T, BG: BG + T] = block4
return img
# 补丁:增加了2/3,3/4的选项,sparse_cj=3就是采集2/3
def addNoise_sparse_mix(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
#img_sparse = np.zeros(img.shape, np.float32)
timeToSkip = 0
for i in range(0, size):
# 一组一组采集
if timeToSkip % sparse_cj == 0:
addTemp = i + sparse_cj - 1 # -1就是少采的那一行
img_sparse[SG + i: SG + addTemp, SG: SG + T] = img[SG + i: SG + addTemp, SG: SG + T]
img_sparse[SG + i: SG + addTemp, BG: BG + T] = img[SG + i: SG + addTemp, BG: BG + T]
img_sparse[BG + i: BG + addTemp, SG: SG + T] = img[BG + i: BG + addTemp, SG: SG + T]
img_sparse[BG + i: BG + addTemp, BG: BG + T] = img[BG + i: BG + addTemp, BG: BG + T]
timeToSkip = timeToSkip + 1
return img_sparse
def DC_sparse_mix(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
timeToSkip = 0
for i in range(0, size):
timeToSkip = timeToSkip + 1
if timeToSkip % sparse_cj == 0:
addTemp = i + sparse_cj - 1 #- 1
img[SG + i: SG + addTemp, SG: SG + T] = gtImg[SG + i: SG + addTemp, SG: SG + T]
img[SG + i: SG + addTemp, BG: BG + T] = gtImg[SG + i: SG + addTemp, BG: BG + T]
img[BG + i: BG + addTemp, SG: SG + T] = gtImg[BG + i: BG + addTemp, SG: SG + T]
img[BG + i: BG + addTemp, BG: BG + T] = gtImg[BG + i: BG + addTemp, BG: BG + T]
return img
# 行列都欠采,然后resize
def addNoise_sparse_SR(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
block1 = img[SG: SG + T, SG: SG + T]
#savemat('abcd_ori.mat', mdict={'data': block1})
block1 = cutRowColunm(block1,size)
#savemat('abcd_cut.mat', mdict={'data': block1})
block1 = resize(block1, (T, T))
#savemat('abcd_resize.mat', mdict={'data': block1})
block2 = img[SG: SG + T, BG: BG + T]
block2 = cutRowColunm(block2,size)
block2 = resize(block2, (T, T))
block3 = img[BG: BG + T, SG: SG + T]
block3 = cutRowColunm(block3,size)
block3 = resize(block3, (T, T))
block4 = img[BG: BG + T, BG: BG + T]
block4 = cutRowColunm(block4, size)
block4 = resize(block4, (T, T))
img_sparse[SG: SG + T, SG: SG + T] = block1
img_sparse[SG: SG + T, BG: BG + T] = block2
img_sparse[BG: BG + T, SG: SG + T] = block3
img_sparse[BG: BG + T, BG: BG + T] = block4
return img_sparse
def DC_sparse_SR(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
# img[SG: SG + T : sparse_cj, SG: SG + T] = gtImg[SG: SG + T: sparse_cj, SG: SG + T]
# img[SG: SG + T: sparse_cj, BG: BG + T] = gtImg[SG: SG + T: sparse_cj, BG: BG + T]
# img[BG: BG + T: sparse_cj, SG: SG + T] = gtImg[BG: BG + T: sparse_cj, SG: SG + T]
# img[BG: BG + T: sparse_cj, BG: BG + T] = gtImg[BG: BG + T: sparse_cj, BG: BG + T]
block1 = gtImg[SG: SG + T, SG: SG + T]
block1 = cutRowColunm(block1, size)
block1 = resize(block1, (T, T))
block2 = gtImg[SG: SG + T, BG: BG + T]
block2 = cutRowColunm(block2, size)
block2 = resize(block2, (T, T))
block3 = gtImg[BG: BG + T, SG: SG + T]
block3 = cutRowColunm(block3, size)
block3 = resize(block3, (T, T))
block4 = gtImg[BG: BG + T, BG: BG + T]
block4 = cutRowColunm(block4, size)
block4 = resize(block4, (T, T))
img[SG: SG + T, SG: SG + T] = block1
img[SG: SG + T, BG: BG + T] = block2
img[BG: BG + T, SG: SG + T] = block3
img[BG: BG + T, BG: BG + T] = block4
return img
def cutRowColunm(block,size):
fz = fzfm[0]
fm = fzfm[1]
# 删除列:
arr = np.array([], dtype=int)
for i in range(0, size // fm):
needToAdd = np.array([], dtype=int)
for j in range(fz):
needToAdd = np.append(needToAdd, [i * fm + fm - fz + j])
arr = np.append(arr, [needToAdd])
# block = np.delete(block, arr, axis=0)
# block = np.delete(block, arr, axis=1)
block = np.delete(block, arr, axis=0)
block = np.delete(block, arr, axis=1)
return block
# 行列都欠采,不resize
def addNoise_sparse_SR_2(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
gt = img[SG: SG + T, SG: SG + T]
block = img_sparse[SG: SG + T, SG: SG + T]
block1 = small_DC(block, gt, size)
gt = img[SG: SG + T, BG: BG + T]
block = img_sparse[SG: SG + T, BG: BG + T]
block2 = small_DC(block, gt, size)
gt = img[BG: BG + T, SG: SG + T]
block = img_sparse[BG: BG + T, SG: SG + T]
block3 = small_DC(block, gt, size)
gt = img[BG: BG + T, BG: BG + T]
block = img_sparse[BG: BG + T, BG: BG + T]
block4 = small_DC(block, gt, size)
img_sparse[SG: SG + T, SG: SG + T] = block1
img_sparse[SG: SG + T, BG: BG + T] = block2
img_sparse[BG: BG + T, SG: SG + T] = block3
img_sparse[BG: BG + T, BG: BG + T] = block4
return img_sparse
def DC_sparse_SR_2(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
gt = gtImg[SG: SG + T, SG: SG + T]
block = img[SG: SG + T, SG: SG + T]
block1 = small_DC(block, gt, size)
gt = gtImg[SG: SG + T, BG: BG + T]
block = img[SG: SG + T, BG: BG + T]
block2 = small_DC(block, gt, size)
gt = gtImg[BG: BG + T, SG: SG + T]
block = img[BG: BG + T, SG: SG + T]
block3 = small_DC(block, gt, size)
gt = gtImg[BG: BG + T, BG: BG + T]
block = img[BG: BG + T, BG: BG + T]
block4 = small_DC(block, gt, size)
img[SG: SG + T, SG: SG + T] = block1
img[SG: SG + T, BG: BG + T] = block2
img[BG: BG + T, SG: SG + T] = block3
img[BG: BG + T, BG: BG + T] = block4
return img
def small_DC(block, gt, size):
road = np.ones(block.shape, dtype=int)
fz = fzfm[0]
fm = fzfm[1]
# 删除列:
arr = np.array([], dtype=int)
for i in range(0, size // fm):
needToAdd = np.array([], dtype=int)
for j in range(fz):
needToAdd = np.append(needToAdd, [i * fm + fm - fz + j])
arr = np.append(arr, [needToAdd])
road[arr, :] = -666
road[:, arr] = -666
road[road != -666] = 1
for i in range(road.shape[0]):
for j in range(road.shape[1]):
if road[i, j] == 1:
block[i, j] = gt[i, j]
return block
# SSN
def addNoise_sensor(img, size=200, picSize=512, gap=10):
if gap + size >= picSize / 2:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
img_sparse = np.ones(img.shape, np.float32)
JZ = (picSize-size)//2
if SSN == 1:
img_sparse[SG: SG + T, SG: SG + T] = img[SG: SG + T, SG: SG + T] # 1
elif SSN == 2:
img_sparse[SG: SG + T, SG: SG + T] = img[SG: SG + T, SG: SG + T] # 1
img_sparse[BG: BG + T, BG: BG + T] = img[BG: BG + T, BG: BG + T] # 4
elif SSN == 3:
img_sparse[SG: SG + T, JZ: JZ + T] = img[SG: SG + T, JZ: JZ + T] # mid 1
img_sparse[BG: BG + T, SG: SG + T] = img[BG: BG + T, SG: SG + T] # 3
img_sparse[BG: BG + T, BG: BG + T] = img[BG: BG + T, BG: BG + T] # 4
elif SSN == 4:
img_sparse[SG: SG + T, SG: SG + T] = img[SG: SG + T, SG: SG + T] # 1
img_sparse[SG: SG + T, BG: BG + T] = img[SG: SG + T, BG: BG + T] # 2
img_sparse[BG: BG + T, SG: SG + T] = img[BG: BG + T, SG: SG + T] # 3
img_sparse[BG: BG + T, BG: BG + T] = img[BG: BG + T, BG: BG + T] # 4
return img_sparse
def DC_sensor(img, gtImg, size=200, picSize=512, gap=10):
if gap + size >= picSize:
raise Exception("hey man, your gap + size is bigger than picSize!")
SG = int(picSize / 2 - gap - size)
T = size
BG = size + 2 * gap + SG # picSize // 2 + gap
JZ = (picSize-size)//2
if SSN == 1:
img[SG: SG + T, SG: SG + T] = gtImg[SG: SG + T, SG: SG + T] # 1
elif SSN == 2:
img[SG: SG + T, SG: SG + T] = gtImg[SG: SG + T, SG: SG + T] # 1
img[BG: BG + T, BG: BG + T] = gtImg[BG: BG + T, BG: BG + T] # 4
elif SSN == 3:
img[SG: SG + T, JZ: JZ + T] = gtImg[SG: SG + T, JZ: JZ + T] # mid 1
img[BG: BG + T, SG: SG + T] = gtImg[BG: BG + T, SG: SG + T] # 3
img[BG: BG + T, BG: BG + T] = gtImg[BG: BG + T, BG: BG + T] # 4
elif SSN == 4:
img[SG: SG + T, SG: SG + T] = gtImg[SG: SG + T, SG: SG + T] # 1
img[SG: SG + T, BG: BG + T] = gtImg[SG: SG + T, BG: BG + T] # 2
img[BG: BG + T, SG: SG + T] = gtImg[BG: BG + T, SG: SG + T] # 3
img[BG: BG + T, BG: BG + T] = gtImg[BG: BG + T, BG: BG + T] # 4
return img
def holoSplit(holo, ifAbs=True):
if ifAbs:
holo = abs(holo)
complex_img = IFT((FT(holo)) * np.conj(prop))
amp_r = abs(complex_img)
phase_r = np.angle(complex_img)
return amp_r, phase_r
def toNumpy(tensor):
return np.squeeze(tensor.cpu().numpy())
def countPSM(aa, bb):
aa = np.squeeze(aa)
bb = np.squeeze(bb)
# 归一化
maxvalue1 = np.max(aa)
minvalue1 = np.min(aa)
aa = (aa - minvalue1) / (maxvalue1 - minvalue1)
maxvalue1 = np.max(bb)
minvalue1 = np.min(bb)
bb = (bb - minvalue1) / (maxvalue1 - minvalue1)
# x0 = aa
# print(f"the aa's max is : {np.max(x0)}, min is : {np.min(x0)} shape is :{x0.shape}")
# plt.imshow(x0, cmap=plt.get_cmap('gray'))
# plt.show()
#
# x0 = bb
# print(f"the bb's max is : {np.max(x0)}, min is : {np.min(x0)} shape is :{x0.shape}")
# plt.imshow(x0, cmap=plt.get_cmap('gray'))
# plt.show()
psnr0 = psnr(aa, bb, data_range=1)
ssim0 = ssim(aa, bb, gaussian_weights=True, use_sample_covariance=False, data_range=1.0)
ssim0 = ssim(aa, bb, data_range=1.0)
mse0 = mse(aa, bb)
psnr0 = round(psnr0, 2)
ssim0 = round(ssim0, 4)
mse0 = round(mse0, 6)
return psnr0, ssim0, mse0
def WriteInfo(path, **args):
"""
### 写入结果至CSV文件
### path : 文件路径
### **args : 需写入的变量数据,同时以标量或列表形式传入:
write_info('./raki_result.csv',psnr =[32.2],mse = [1.54],ssim= [0.9756],mae=[0.12])
"""
ppp = os.path.split(path)
if not os.path.isdir(ppp[0]):
os.makedirs(ppp[0])
# print(f"{pathDir} 创建成功")
try:
args = args['args']
except:
pass
# print(args)
# assert 0
args['Time'] = [str(datetime.datetime.now())[:-7]]
try:
df = pd.read_csv(path, encoding='utf-8', engine='python')
except:
df = pd.DataFrame()
df2 = pd.DataFrame(args)
df = df.append(df2)
df.to_csv(path, index=False)
def savePng(path, img):
ppp = os.path.split(path)
if not os.path.isdir(ppp[0]):
os.makedirs(ppp[0])
# print(f"{pathDir} 创建成功")
plt.imshow(img, cmap=plt.get_cmap('gray'))
plt.savefig(f'{path}')
def getInsideIndex(pad=padding, size=N):
return int((pad - size) / 2)
def addPaddingAmp(amp, pad=padding, size=N):
# amp is 512*512
temp = np.ones((pad, pad), np.float32)
if size > 512:
raise Exception("hey man, your cut is too big!")
inIn = getInsideIndex(512, size)
amp_cut = amp[inIn:inIn + size, inIn:inIn + size]
inIn = getInsideIndex(pad, size)
temp[inIn:inIn + size, inIn:inIn + size] = amp_cut
return temp
def addPaddingPhase(phase, pad=padding, size=N):
temp = np.zeros((pad, pad), np.float32)
if size > 512:
raise Exception("hey man, your cut is too big!")
inIn = getInsideIndex(512, size)
phase_cut = phase[inIn:inIn + size, inIn:inIn + size]
inIn = getInsideIndex(pad, size)
temp[inIn:inIn + size, inIn:inIn + size] = phase_cut
return temp
def getFormatPSM(psnr2, ssim2, mse2):
return f"{('%.2f' % psnr2)}/{('%.4f' % ssim2)}/{('%.4f' % mse2)}"
# endregion
# ---------------------------------------------------
learning_Objet = 4
# 0 1 2 3 4
learning_List = ['0', '7', 'all', 'letter', 'all_100']
learning_Objet = learning_List[learning_Objet]
ampBatch = loadmat(f'./gt/{learning_Objet}/gt_batch_amp.mat')['data']
phaseBatch = loadmat(f'./gt/{learning_Objet}/gt_batch_phase.mat')['data']
print(f"================== Now we testing the {learning_Objet} ==================")
# savePath = 'result_m20_L7TL/SSN_Special_Ones'
savePath = 'result_m20/L7TA_100_sparse_3'
# savePath = 'result_m20_allNumber/SR_sparse_resize_test'
useSrSparse = False
useSparse = False
useSSN = False
fzfm=[1,5]
sparse_cj = zl_arg.sparse
SSN = zl_arg.ssn # auto
if SSN > 0:
useSSN=True
if sparse_cj > 0:
useSparse = True
ifSavePng = False
ifSaveAll = True
showImg = False # !!!!!! must close!!
startStep = 1600
endStep = 2100 # 2100
keep_size = zl_arg.size # 400
useNet = zl_arg.useNet # True
gap = zl_arg.gap # auto
maskType = 'default_0'
if useSrSparse:
addNoise = addNoise_sparse_SR_2
DC = DC_sparse_SR_2
maskType = f'fzfm_{fzfm}'
print(f"================== Now we use fzfm {fzfm}==================")
elif useSparse:
# addNoise = addNoise_sparse
# DC = DC_sparse
addNoise = addNoise_sparse_mix
DC = DC_sparse_mix
maskType = f'sparse_{sparse_cj}'
print(f"================== Now we use sparse {sparse_cj} ==================")
elif useSSN:
addNoise = addNoise_sensor
DC = DC_sensor
maskType = f'SSN_{SSN}'
print(f"================== Now we use SSN {SSN} ==================")
else:
addNoise = addNoise_king
DC = DC_king
print(f"================== Now we use nothing noise just size and gap ==================")
inIn = getInsideIndex(padding, N)
wavelength = 500 * (pow(10, -9))
range1 = 0.001 / (1200 / padding)
z = 0.0024
prop = Propagator_function(padding, z, wavelength, range1)
amp_gt = ampBatch[picNO, :, :]
phase_gt = phaseBatch[picNO, :, :]
amp_gt_b = addPaddingAmp(amp_gt)
phase_gt_b = addPaddingPhase(phase_gt)
fs_b = amp_gt_b * np.exp(1j * phase_gt_b)
U = IFT((FT(fs_b)) * prop)
holo_gt_b = abs(U)
# region else
title = 'NCSNPP' if useNet else 'SRSAA' # SRSAA NCSNPP