-
Notifications
You must be signed in to change notification settings - Fork 0
/
mylib.py
1574 lines (1271 loc) · 59.9 KB
/
mylib.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 numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import json
# from cv2 import imread, resize
from torch.nn import functional as F
# from tqdm import tqdm
# from collections import Counter
from random import seed, choice, sample
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
from DWT_IDWT.DWT_IDWT_layer import DWT_2D
from focal_frequency_loss import FocalFrequencyLoss as FFL
from args_parser import args_parser
'''
mav_value = 1023 # GF:1023 QB:2047
img = img.astype(np.float32) / mav_value # 归一化处理 最开始 mav_value = 1023 # GF:1023 QB:2047
x = (x * mav_value).astype(np.uint16)
'''
args = args_parser()
def denorm(x):
x = (x * mav_value).astype(np.uint16)
return x
def eval_img_save(x, name, k):
x = x.numpy()
x = np.transpose(x, (0, 2, 3, 1)) # [batch_size,512,512,4]
if name == 'real_images':
array2raster(join(evalsample_dir, 'real_images_{}_epoch{}.tif'.format(k + 1, total_epochs)),
[0, 0], 8, 8, denorm(x[0].transpose(2, 0, 1)), 4)
else:
array2raster(join(evalsample_dir,
'{}_v{}_eval_fused_images_{}_epoch{}.tif'.format(method, version, k + 1, total_epochs)),
[0, 0], 8, 8, denorm(x[0].transpose(2, 0, 1)), 4)
def test_img_save(x, name, epoch):
x = np.transpose(x, (0, 2, 3, 1))
x = x.numpy() # [batch_size,512,512,4]
if name == 'test_fused_images':
array2raster(join(testsample_dir, 'test_fused_images_9_epoch{}.tif'.format(epoch)),
[0, 0], 8, 8, denorm(x[0].transpose(2, 0, 1)), 4)
elif name == 'real_images':
array2raster(join(testsample_dir, 'real_images_9_epoch{}.tif'.format(epoch)),
[0, 0], 8, 8, denorm(x[0].transpose(2, 0, 1)), 4)
elif name == 'test_pan_images':
array2raster(join(testsample_dir, 'test_pan_images_9_epoch{}.tif'.format(epoch)),
[0, 0], 8, 8, denorm(x[0].reshape(x.shape[1], x.shape[2])), 1)
else:
array2raster(join(testsample_dir, 'test_lrms_images_9_epoch{}.tif'.format(epoch)),
[0, 0], 8, 8, denorm(x[0].transpose(2, 0, 1)), 4)
def array2raster(newRasterfn, rasterOrigin, pixelWidth, pixelHeight, array, bandSize):
if (bandSize == 4):
cols = array.shape[2]
rows = array.shape[1]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
driver = gdal.GetDriverByName('GTiff') # #存的数据格式
outRaster = driver.Create(newRasterfn, cols, rows, 4, gdal.GDT_UInt16)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
for i in range(1, 5):
outband = outRaster.GetRasterBand(i)
outband.WriteArray(array[i - 1, :, :])
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326)
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
elif (bandSize == 1):
cols = array.shape[1]
rows = array.shape[0]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_UInt16)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(array)
def normalized(X):
maxX = np.max(X)
# print('maxX:', maxX)
if maxX == 0:
return X
else:
minX = np.min(X)
X = (X - minX) / (maxX - minX)
return X
def setRange(X, maxX=1, minX=0):
X = (X - minX) / (maxX - minX)
return X
def get3band_of_tensor(outX, nbanch=0, nframe=[0, 1, 2]):
X = outX[:, :, :, nframe]
X = X[nbanch, :, :, :]
return X
def imshow(X):
plt.close()
X = np.maximum(X, 0)
X = np.minimum(X, 1)
plt.imshow(X[:, :, ::-1])
plt.axis('off')
plt.show()
def imwrite(X, saveload='./tempIm/1.png'): #################### zy
plt.imsave(saveload, ML.normalized(X[:, :, ::-1]))
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
print("--- new folder... ---")
print("--- " + path + " ---")
else:
print("--- There exsits folder " + path + " ! ---")
# SSRNT
def to_var(x, volatile=False):
if torch.cuda.is_available():
x = x.cuda().float()
return Variable(x, volatile=volatile)
class AverageMeter(object):
"""
Keeps track of most recent, average, sum, and count of a metric.
"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# SSRNET
def adjust_learning_rate(optimizer, shrink_factor):
"""
Shrinks learning rate by a specified factor.
:param optimizer: optimizer whose learning rate must be shrunk.
:param shrink_factor: factor in interval (0, 1) to multiply learning rate with.
"""
print("\nDECAYING learning rate.")
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * shrink_factor
print("The new learning rate is %f\n" % (optimizer.param_groups[0]['lr'],))
# wang shang
def adjust_learning_rate2(optimizer, epoch, schedule, gamma):
"""Sets the learning rate to the initial LR decayed by schedule"""
if epoch in schedule:
for param_group in optimizer.param_groups:
param_group['lr'] *= gamma
return optimizer.state_dict()['param_groups'][0]['lr']
def sobel_gradient(input):
filter_x = torch.from_numpy(
np.array([[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]], dtype='float32').reshape([1, 1, 3, 3]))
filter_y = torch.from_numpy(
np.array([[-1., -2., -1.], [0., 0., 0.], [1., 2., 1.]], dtype='float32').reshape([1, 1, 3, 3]))
conv_x = nn.Conv2d(1, 1, 3, 1, 1, bias=False)
conv_x.weight.data = filter_x.cuda()
conv_y = nn.Conv2d(1, 1, 3, 1, 1, bias=False)
conv_y.weight.data = filter_y.cuda()
n, c, h, w = input.shape
g_x = torch.from_numpy(np.zeros((n, c, h, w))).type(torch.FloatTensor)
g_y = torch.from_numpy(np.zeros((n, c, h, w))).type(torch.FloatTensor)
for i in range(c):
d1_x = conv_x(input[:, i, :, :].unsqueeze(1))
d1_y = conv_y(input[:, i, :, :].unsqueeze(1))
print('d1_x:{}______g_x[:, i, :, :]:{}'.format(d1_x.squeeze().shape, g_x[:, i, :, :].shape))
g_x[:, i, :, :] = d1_x.squeeze()
g_y[:, i, :, :] = d1_y.squeeze()
return g_x, g_y
def lpls_gradient(input):
filter = torch.from_numpy(
np.array([[1., 1., 1.], [1., -8., 1.], [1., 1., 1.]], dtype='float32').reshape([1, 1, 3, 3]))
conv = nn.Conv2d(1, 1, 3, 1, 1, bias=False)
conv.weight.data = filter
n, c, h, w = input.shape
g = torch.from_numpy(np.zeros((n, c, h, w))).type(torch.FloatTensor)
for i in range(c):
d = conv(input[:, i, :, :].unsqueeze(1))
g[:, i, :, :] = d
return g
'''input b c h w output b c h w function gaussian blur tesor'''
def Gaussian_Blur(input):
img_np = input.detach().cpu().numpy()
count = img_np.shape[0]
output = torch.ones(img_np.shape)
# print('img_np.shape: ', img_np.shape, 'count: ', count, 'output.shape', output.shape)
for i in range(count):
img_hwc = np.squeeze(img_np[i, :, :, :]).transpose(1, 2, 0)
img_hwc_blur = cv2.GaussianBlur(img_hwc, (5, 5), 2)
img_chw = img_hwc_blur.transpose(2, 0, 1)
output[i, :, :, :] = torch.from_numpy(img_chw)
# print('img_hwc.shape: ', img_hwc.shape, 'img_hwc_blur.shape: ', img_hwc_blur.shape,
# 'img_chw.shape: ', img_chw.shape)
output = Variable(output).cuda()
# print('output.shape: ', output.shape, 'output.type: ', type(output))
return output
class loss_func1(nn.Module):
def __init__(self):
super(loss_func1, self).__init__()
def forward(self, ref, pan, ms, out):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur and resize
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
# loss
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
loss_ms_out = torch.mean(torch.abs(out - ms))
loss_ref_out = torch.mean(torch.abs(out - ref))
loss_pan_out = torch.mean(torch.abs(pan_gradient_x - out2pan_gradient_x)) + torch.mean(
torch.abs(pan_gradient_y - out2pan_gradient_y))
# gai weighted loss
a = 1
b = 1
c = 1
# d = 1d*()
loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
print('loss_ms_out{}: __loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ms_out, loss_ref_out,
loss_pan_out, loss_total))
return loss_total
'''add blur part : out2ms'''
class loss_func2(nn.Module):
def __init__(self):
super(loss_func2, self).__init__()
def forward(self, ref, pan, ms, out):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
out2ms = Gaussian_Blur(out)
# loss
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
loss_ms_out = torch.mean(torch.abs(out2ms - ms))
loss_ref_out = torch.mean(torch.abs(out - ref))
loss_pan_out = torch.mean(torch.abs(pan_gradient_x - out2pan_gradient_x)) + torch.mean(
torch.abs(pan_gradient_y - out2pan_gradient_y))
# gai weighted loss
a = 1
b = 1
c = 1
# d = 1d*()
loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
print('loss_ms_out{}: __loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ms_out, loss_ref_out,
loss_pan_out, loss_total))
return loss_total
'''torch.mean(torch.abs ()) changed as nn.L1Loss()'''
class loss_func3(nn.Module):
def __init__(self):
super(loss_func3, self).__init__()
def forward(self, ref, pan, ms, out):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
out2ms = Gaussian_Blur(out)
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
print(out2ms.shape, ms.shape)
# b, _, ww, hh = out2ms.shape
# tar = torch.ones(b, 1, ww, hh).cuda()
loss_ms_out = loss(out2ms, ms) # loss2(out2ms, ms, tar)
loss_pan_out = loss(out2pan_gradient_x, pan_gradient_x) + loss(out2pan_gradient_y, pan_gradient_y)
loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
# gai weighted loss
# a = 2
# b = 2
# c = 1
# d = 1d*()
# loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
loss_total = loss_ms_out + loss_ref_out + loss_pan_out
# loss_total = loss_ref_out + loss_pan_out
print('loss_ms_out{}: __loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ms_out, loss_ref_out,
loss_pan_out, loss_total))
# print('loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ref_out, loss_pan_out, loss_total))
return loss_total
class loss_func4(nn.Module):
def __init__(self):
super(loss_func4, self).__init__()
self.triplet_margin = 12 # 5
def forward(self, ref, pan, ms, out, quary, key, value):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
out2ms = Gaussian_Blur(out)
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
loss_qkv = self.similarity_based_triple_loss(quary, key, value)
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
print(out2ms.shape, ms.shape)
# b, _, ww, hh = out2ms.shape
# tar = torch.ones(b, 1, ww, hh).cuda()
loss_ms_out = loss(out2ms, ms) # loss2(out2ms, ms, tar)
loss_pan_out = loss(out2pan_gradient_x, pan_gradient_x) + loss(out2pan_gradient_y, pan_gradient_y)
loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
# gai weighted loss
# a = 2
# b = 2
# c = 1
# d = 1d*()
# loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
loss_total = loss_ms_out + loss_ref_out + loss_pan_out + loss_qkv
# loss_total = loss_ref_out + loss_pan_out
print('loss_ms_out{}: __loss_ref_out{}: __loss_pan_out{}: __loss_qkv{}: __loss_total{}:'.format(loss_ms_out,
loss_ref_out,
loss_pan_out,
loss_qkv,
loss_total))
# print('loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ref_out, loss_pan_out, loss_total))
return loss_total
def similarity_based_triple_loss(self, anchor, positive, negative):
distance = self.scaled_dot_product(anchor, positive) - self.scaled_dot_product(anchor,
negative) + self.triplet_margin
loss = torch.mean(torch.max(distance, torch.zeros_like(distance)))
return loss
# https://www.quantumdl.com/entry/11%EC%A3%BC%EC%B0%A82-Attention-is-All-You-Need-Transformer
def scaled_dot_product(self, query, key, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
return scores
class loss_func5(nn.Module):
def __init__(self):
super(loss_func5, self).__init__()
self.triplet_margin = 12 # 5
def forward(self, ref, pan, ms, out, quary, key, value):
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
loss3 = nn.MSELoss()
loss_qkv = self.similarity_based_triple_loss(quary, key, value)
loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
# gai weighted loss
# a = 2
# b = 2
# c = 1
# d = 1d*()
# loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
loss_total = loss_ref_out + loss_qkv
# loss_total = loss_ref_out + loss_pan_out
print('loss_ref_out{}: __loss_qkv{}: __loss_total{}:'.format(loss_ref_out, loss_qkv, loss_total))
# print('loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ref_out, loss_pan_out, loss_total))
return loss_total
def similarity_based_triple_loss(self, anchor, positive, negative):
distance = self.scaled_dot_product(anchor, positive) - self.scaled_dot_product(anchor,
negative) + self.triplet_margin
loss = torch.mean(torch.max(distance, torch.zeros_like(distance)))
return loss
# https://www.quantumdl.com/entry/11%EC%A3%BC%EC%B0%A82-Attention-is-All-You-Need-Transformer
def scaled_dot_product(self, query, key, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
return scores
class loss_func6(nn.Module):
def __init__(self):
super(loss_func6, self).__init__()
self.triplet_margin = 12 # 5
def forward(self, ref, pan, ms, out, quary, key, value, quary_h1, key_h1, value_h1): # , quary_h1, key_h1, value_h1
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
loss3 = nn.MSELoss()
loss_qkv = self.similarity_based_triple_loss(quary, key, value)
# loss_qkvh2 = self.similarity_based_triple_loss(quary_h2, key_h2, value_h2)
loss_qkvh1 = self.similarity_based_triple_loss(quary_h1, key_h1, value_h1)
style_loss = loss(self.gram_matrix(out), self.gram_matrix(ref))
loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
# gai weighted loss
# a = 2
# b = 2
# c = 1
# d = 1d*()
# loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
loss_total = loss_ref_out + loss_qkv + loss_qkvh1 + style_loss # + loss_qkvh2
# loss_total = loss_ref_out + loss_pan_out
print('loss_ref_out:{} __loss_qkv:{} __loss_qkvh1:{} __style_loss:{} __loss_total:{}'
.format(loss_ref_out, loss_qkv, loss_qkvh1, style_loss, loss_total))
# with open('train_WV2.txt', 'a') as f:
# f.write('loss_ref_out:' + str(loss_ref_out) + '_' + 'loss_qkv:' + str(loss_qkv) + '_'
# + 'loss_qkvh1:' + str(loss_qkvh1) + '_' + 'style_loss:' + str(style_loss) + '_' + 'loss_total'
# + str(loss_total) + '\n')
# f.close()
# print('loss_ref_out{}: __loss_qkv{}: __loss_qkvh2{}: __loss_qkvh1{}: __style_loss{}: __loss_total{}:'
# .format(loss_ref_out, loss_qkv, loss_qkvh2, loss_qkvh1, style_loss, loss_total))
# print('loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ref_out, loss_pan_out, loss_total))
return loss_total
def similarity_based_triple_loss(self, anchor, positive, negative):
distance = self.scaled_dot_product(anchor, positive) - self.scaled_dot_product(anchor,
negative) + self.triplet_margin
loss = torch.mean(torch.max(distance, torch.zeros_like(distance)))
return loss
# https://www.quantumdl.com/entry/11%EC%A3%BC%EC%B0%A82-Attention-is-All-You-Need-Transformer
def scaled_dot_product(self, query, key, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
return scores
def gram_matrix(self, y):
(b, ch, h, w) = y.size()
features = y.view(b, ch, w * h)
features_t = features.transpose(1, 2)
gram = features.bmm(features_t) / (ch * h * w)
return gram
class loss_func7(nn.Module):
def __init__(self):
super(loss_func7, self).__init__()
self.triplet_margin = 12 # 5
def forward(self, ref, pan, ms, out, quary, key, value, quary_h2, key_h2, value_h2, quary_h1, key_h1, value_h1): #
# loss
loss = nn.L1Loss()
# loss2 = nn.CosineEmbeddingLoss(margin=0.2)
# loss3 = nn.MSELoss()
loss_qkv = self.similarity_based_triple_loss(quary, key, value)
loss_qkvh2 = self.similarity_based_triple_loss(quary_h2, key_h2, value_h2)
loss_qkvh1 = self.similarity_based_triple_loss(quary_h1, key_h1, value_h1)
style_loss = loss(self.gram_matrix(out), self.gram_matrix(ref))
loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
# gai weighted loss
# a = 2
# b = 2
# c = 1
# d = 1d*()
# loss_total = a * loss_ms_out + b * loss_ref_out + c * loss_pan_out
loss_total = loss_ref_out + loss_qkv + loss_qkvh2 + style_loss + loss_qkvh1
# loss_total = loss_ref_out + loss_pan_out
# print('loss_ref_out:{} __loss_qkv:{} __loss_qkvh2:{} __style_loss:{} __loss_total:{}'
# .format(loss_ref_out, loss_qkv, loss_qkvh2, style_loss, loss_total))
print('loss_ref_out{}: __loss_qkv{}: __loss_qkvh2{}: __loss_qkvh1{}: __style_loss{}: __loss_total{}:'
.format(loss_ref_out, loss_qkv, loss_qkvh2, loss_qkvh1, style_loss, loss_total))
# print('loss_ref_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ref_out, loss_pan_out, loss_total))
return loss_total
def similarity_based_triple_loss(self, anchor, positive, negative):
distance = self.scaled_dot_product(anchor, positive) - self.scaled_dot_product(anchor,
negative) + self.triplet_margin
loss = torch.mean(torch.max(distance, torch.zeros_like(distance)))
return loss
def scaled_dot_product(self, query, key, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
return scores
def gram_matrix(self, y):
(b, ch, h, w) = y.size()
features = y.view(b, ch, w * h)
features_t = features.transpose(1, 2)
gram = features.bmm(features_t) / (ch * h * w)
return gram
class loss_func8(nn.Module):
def __init__(self):
super(loss_func8, self).__init__()
def forward(self, pan, ms, out):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
out2ms = Gaussian_Blur(out)
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
print(out2ms.shape, ms.shape)
# b, _, ww, hh = out2ms.shape
# tar = torch.ones(b, 1, ww, hh).cuda()
loss_ms_out = loss(out2ms, ms) # loss2(out2ms, ms, tar)
loss_pan_out = loss(out2pan_gradient_x, pan_gradient_x) + loss(out2pan_gradient_y, pan_gradient_y)
# loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
loss_total = loss_ms_out + loss_pan_out
print('loss_ms_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ms_out, loss_pan_out, loss_total))
return loss_total
'''display image learn from matlab'''
class loss_func9(nn.Module):
def __init__(self):
super(loss_func9, self).__init__()
def forward(self, pan, ms, out):
# channel mean
out2pan = torch.mean(out, dim=1).unsqueeze(1)
# blur
# out2ms = F.interpolate(out, scale_factor=0.25, mode="bicubic") # ms upsampled already!
# print('out2ms:{}__ms:{}'.format(out2ms.shape,ms.shape))
out2ms = Gaussian_Blur(out)
# loss
loss = nn.L1Loss()
loss2 = nn.CosineEmbeddingLoss(margin=0.2)
pan_gradient_x, pan_gradient_y = sobel_gradient(pan)
out2pan_gradient_x, out2pan_gradient_y = sobel_gradient(out2pan)
print(out2ms.shape, ms.shape)
b, _, ww, hh = out2ms.shape
tar = torch.ones(b, 1, ww, hh).cuda()
loss_ms_out = loss2(out2ms, ms, tar) # loss2(out2ms, ms, tar)
loss_pan_out = loss(out2pan_gradient_x, pan_gradient_x) + loss(out2pan_gradient_y, pan_gradient_y)
# loss_ref_out = loss(out, ref) # loss2(out, ref, tar) +
loss_total = loss_ms_out + loss_pan_out
print('loss_ms_out{}: __loss_pan_out{}: __loss_total{}:'.format(loss_ms_out, loss_pan_out, loss_total))
return loss_total
'''display image learn from matlab'''
def display_img(img):
try:
count = img.shape[2]
for i in range(count):
m = np.min(img[:, :, i])
img[:, :, i] = img[:, :, i] - m
img[:, :, i] = img[:, :, i] / np.max(img[:, :, i])
except IndexError:
m = np.min(img[:, :])
img[:, :] = img[:, :] - m
img[:, :] = img[:, :] / np.max(img[:, :])
return img
def save_img(img, i,name):
try:
count = img.shape[2]
except IndexError:
count = 1
if count == 4:
print("多光谱")
out_red = img[:, :, 2][:, :, np.newaxis]
out_green = img[:, :, 1][:, :, np.newaxis]
out_blue = img[:, :, 0][:, :, np.newaxis]
out = np.concatenate((out_blue, out_green, out_red), axis=2)
elif count == 8:
print("多光谱")
out_red = img[:, :, 4][:, :, np.newaxis]
out_green = img[:, :, 2][:, :, np.newaxis]
out_blue = img[:, :, 1][:, :, np.newaxis]
out = np.concatenate((out_blue, out_green, out_red), axis=2)
else:
out=img
print("单通道")
out = 255 * display_img(out)
# out = 255 * out
cv2.imwrite('figs/{}_'.format(i)+name+'.jpg', out)
def save_fea(img, i,name):
try:
count = img.shape[2]
print("特征")
out = np.zeros((img.shape[0], img.shape[1]))
for j in range(count):
out += img[:, :, j]
except IndexError:
out = img
out = 255 * display_img(out)
# out = 255 * out
cv2.imwrite('figs/{}_'.format(i)+name+'.jpg', out)
class loss_func10(nn.Module):
def __init__(self):
super(loss_func10, self).__init__()
def forward(self, ref, out):
loss_total = torch.mean(torch.abs(ref - out) * torch.square(ref - out))
print('______________________________________loss_total{}:'.format(loss_total))
return loss_total
class loss_func11(nn.Module):
def __init__(self):
super(loss_func11, self).__init__()
self.dwt = DWT_2D(wavename='haar')
def forward(self, ref, out):
ref_l, ref_h1, ref_h2, ref_h3 = self.dwt(ref)
out_l, out_h1, out_h2, out_h3 = self.dwt(out)
ref_h = torch.cat((ref_h1, ref_h2, ref_h3), 1)
out_h = torch.cat((out_h1, out_h2, out_h3), 1)
loss_h = torch.mean(torch.abs(ref_h - out_h) * torch.square(ref_h - out_h))
loss_l = torch.mean(torch.abs(ref_l - out_l) * torch.square(ref_l - out_l))
loss_total = loss_h + loss_l
print('loss_h{}: __loss_l{}: __loss_total{}:'.format(loss_h, loss_l, loss_total))
return loss_total
class loss_func12(nn.Module):
def __init__(self):
super(loss_func12, self).__init__()
def forward(self, out_l, out_h, ms_l, pan_h):
loss_h = torch.mean(torch.abs(pan_h - out_h) * torch.square(pan_h - out_h))
loss_l = torch.mean(torch.abs(ms_l - out_l) * torch.square(ms_l - out_l))
loss_total = loss_h + loss_l
print('loss_h{}: __loss_l{}: __loss_total{}:'.format(loss_h, loss_l, loss_total))
return loss_total
class loss_func13(nn.Module):
def __init__(self):
super(loss_func13, self).__init__()
def forward(self, out_l, out_h, ms_l, pan_h):
loss = nn.L1Loss()
loss_h = loss(pan_h, out_h)
loss_l = loss(ms_l, out_l)
loss_total = loss_h + loss_l
print('loss_h{}: __loss_l{}: __loss_total{}:'.format(loss_h, loss_l, loss_total))
return loss_total
class loss_func14(nn.Module):
def __init__(self):
super(loss_func14, self).__init__()
def forward(self, ref, out):
loss = FFL(loss_weight=1.0, alpha=1.0)
loss_total = loss(out, ref)
print('________loss_total:{}'.format(loss_total))
return loss_total
def off_diagonal(x):
# return a flattened view of the off-diagonal elements of a square matrix
n, m = x.shape
assert n == m
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
# batch and batch similar
class FLoss(nn.Module):
# MLP to change high dimension feature to low dimension feature for CC loss calculation
def __init__(self, dv, do, lambd=1):
# dv is the M*N*C number of input feature-(B C M N)
super(FLoss, self).__init__()
self.layer1 = nn.Linear(dv, do)
self.layer2 = nn.Linear(dv, do)
self.bn = nn.BatchNorm1d(do, affine=False)
self.lambd = lambd
# self.layer3 = nn.Linear(dv, dv)
def forward(self, F1, F2):
# change the shape from (B C M N) to (B M*N*C) for nn.linear function
F1 = torch.reshape(F1, (F1.size(0), F1.size(1) * F1.size(2) * F1.size(3)))
F2 = torch.reshape(F2, (F2.size(0), F2.size(1) * F2.size(2) * F2.size(3)))
# print("F1.shape:", F1.shape, F2.shape)
# reduce dimension from (B M*N*C) to (B M*N*C)
F1_1 = self.bn(self.layer1(F1))
F2_1 = self.bn(self.layer2(F2))
# print('F1_1:', F1_1.shape)
# print('F2_1:', F2_1.shape)
# empirical cross-correlation matrix, size-(batch_size, size)
c = self.bn(F1_1).T @ self.bn(F2_1) # mean-0 variation-1
on_diag = torch.diagonal(c).add_(-1).pow_(2).sum()
off_diag = off_diagonal(c).pow_(2).sum()
loss = on_diag + self.lambd * off_diag
return loss
# only make low part similar
class loss_func15(nn.Module):
def __init__(self, dv=8192, do=64, lambd=0.005):
super(loss_func15, self).__init__()
# dv = M*N*C = 64*64*32=131072
self.cc_loss = FLoss(dv, do, lambd)
def forward(self, ref, out, pc_2, mc_2):
loss = nn.L1Loss()
loss_ref = loss(ref, out)
# print('pc_2.shape:', pc_2.shape, mc_2.shape)# torch.Size([32, 32, 16, 16]) torch.Size([32, 32, 16, 16])
loss_l = self.cc_loss(pc_2, mc_2)
loss_total = loss_ref + loss_l
print('loss_ref{}: __loss_l{}: __loss_total{}:'.format(loss_ref, loss_l, loss_total))
return loss_total
# only make low part similar
class loss_func16(nn.Module):
def __init__(self, dv=8192, do=64, lambd=0.005):
super(loss_func16, self).__init__()
# dv = M*N*C = 64*64*32=131072
self.cc_loss = FLoss(dv, do, lambd)
def forward(self, ref, out, pc_2, mc_2):
loss = nn.L1Loss()
loss_ref = loss(ref, out)
# print('pc_2.shape:', pc_2.shape, mc_2.shape)# torch.Size([32, 32, 16, 16]) torch.Size([32, 32, 16, 16])
loss_l = self.cc_loss(pc_2, mc_2) / 4096.
loss_total = 0.7 * loss_ref + 0.3 * loss_l
print('loss_ref{}: __loss_l{}: __loss_total{}:'.format(loss_ref, loss_l, loss_total))
return loss_total
# only make high part similar
class loss_func17(nn.Module):
def __init__(self, dv=8192, do=64, lambd=0.005):
super(loss_func17, self).__init__()
# dv = M*N*C = 64*64*32=131072 16*16*32=8192 16*16*32*3
self.cc_lossh2 = FLoss(3 * dv, do, lambd)
self.cc_lossh1 = FLoss(3 * 4 * dv, do, lambd)
def forward(self, ref, out, pgc_2, mgc_2, pgc_1, mgc_1):
loss = nn.L1Loss()
loss_ref = loss(ref, out)
# print('pgc_2.shape:', pgc_2.shape, mgc_2.shape)
# print('pgc_1.shape:', pgc_1.shape, mgc_1.shape)
# print('pc_2.shape:', pc_2.shape, mc_2.shape)# torch.Size([32, 32, 16, 16]) torch.Size([32, 32, 16, 16])
loss_h1 = self.cc_lossh1(pgc_1, mgc_1) / 4096.
loss_h2 = self.cc_lossh2(pgc_2, mgc_2) / 4096.
loss_total = loss_ref + loss_h1 + loss_h2
print('loss_ref{}: __loss_h1{}: __loss_h2{}: __loss_total{}:'.format(loss_ref, loss_h1, loss_h2, loss_total))
return loss_total
# only make high part similar
class loss_func18(nn.Module):
def __init__(self, dv=8192, do=64, lambd=0.005):
super(loss_func18, self).__init__()
# dv = M*N*C = 64*64*32=131072 16*16*32=8192 16*16*32*3
self.cc_lossl = FLoss(dv, do, lambd)
self.cc_lossh2 = FLoss(3 * dv, do, lambd)
self.cc_lossh1 = FLoss(3 * 4 * dv, do, lambd)
def forward(self, ref, out, pc_2, mc_2, pgc_2, mgc_2, pgc_1, mgc_1):
loss = nn.L1Loss()
loss_ref = loss(ref, out)
# print('pc_2.shape:', pc_2.shape, mc_2.shape)# torch.Size([32, 32, 16, 16]) torch.Size([32, 32, 16, 16])
loss_l = self.cc_lossl(pc_2, mc_2) / 4096.
loss_h1 = self.cc_lossh1(pgc_1, mgc_1) / 4096.
loss_h2 = self.cc_lossh2(pgc_2, mgc_2) / 4096.
loss_total = loss_ref + loss_l + loss_h1 + loss_h2
print(
'loss_ref{}: __loss_l{}: loss_h1{}: __loss_h2{}: __loss_total{}:'.format(loss_ref, loss_l, loss_h1, loss_h2,
loss_total))
return loss_total
# data and data similar
class FLoss2(nn.Module):
# MLP to change high dimension feature to low dimension feature for CC loss calculation
def __init__(self, dv, dv1, do, lambd=1):
# dv is the M*N*C number of input feature-(B C M N)
super(FLoss2, self).__init__()
self.layer1 = nn.Linear(dv, do)
self.layer2 = nn.Linear(dv1, do)
self.bn = nn.BatchNorm1d(do, affine=False)
self.lambd = lambd
# self.layer3 = nn.Linear(dv, dv)
def forward(self, F1, F2):
# change the shape from (B C M N) to (B M*N*C) for nn.linear function
F1 = torch.reshape(F1, (F1.size(0), F1.size(1) * F1.size(2) * F1.size(3)))
F2 = torch.reshape(F2, (F2.size(0), F2.size(1) * F2.size(2) * F2.size(3)))
# print("F1.shape:", F1.shape, F2.shape)
# reduce dimension from (B M*N*C) to (B M*N*C)
F1_1 = self.bn(self.layer1(F1))
F2_1 = self.bn(self.layer2(F2))
# print('F1_1:', F1_1.shape)
# print('F2_1:', F2_1.shape)
# empirical cross-correlation matrix, size-(batch_size, size)
c = self.bn(F1_1) @ self.bn(F2_1).T # mean-0 variation-1
on_diag = torch.diagonal(c).add_(-1).pow_(2).mean()
off_diag = off_diagonal(c).pow_(2).mean()
loss = on_diag + self.lambd * off_diag
return loss
class loss_func19(nn.Module):
def __init__(self, dv=4096, dv1=4096 * args.bands, do=16, lambd=0.005):
super(loss_func19, self).__init__()
self.cc_loss_pan = FLoss2(dv, dv1, do, lambd)
self.cc_loss_ms = FLoss2(dv1, dv1, do, lambd)
def forward(self, ref, out, pan, ms):
# channel mean
loss = nn.L1Loss()
loss_ref_out = loss(ref, out)
#
loss_ms_out = self.cc_loss_pan(pan, out)
loss_pan_out = self.cc_loss_ms(ms, out)
loss_total = loss_ref_out + 0.001 * loss_pan_out + 0.001 * loss_ms_out
# loss_total = loss_ref_out + loss_pan_out
print('loss_ref_out:{}_loss_ms_out:{}_loss_pan_out:{}_loss_total:{}'.format(loss_ref_out, loss_ms_out,
loss_pan_out, loss_total))
return loss_total
class loss_func20(nn.Module):
def __init__(self):
super(loss_func20, self).__init__()
def forward(self, ref, out, ms_2, out_2):
# channel mean
loss = nn.L1Loss()
loss_ref = loss(ref, out)
loss_ms2 = loss(ms_2, out_2)
loss_total = loss_ref + loss_ms2
# loss_total = loss_ref_out + loss_pan_out
print('loss_ref:{}_loss_ms2:{}_loss_total:{}'.format(loss_ref, loss_ms2, loss_total))
return loss_total
class loss_func21(nn.Module):
def __init__(self):
super(loss_func21, self).__init__()
def forward(self, ref, out, ms_2, out_2, ms_1, out_1):
# channel mean
loss = nn.L1Loss()
loss_ref = loss(ref, out)
loss_ms2 = loss(ms_2, out_2)
loss_ms1 = loss(ms_1, out_1)
loss_total = loss_ref + loss_ms2 + loss_ms1
# loss_total = loss_ref_out + loss_pan_out
print('loss_ref:{}_loss_ms2:{}_loss_ms1:{}_loss_total:{}'.format(loss_ref, loss_ms2, loss_ms1, loss_total))
return loss_total
# arccos(x) make x near to 1,then sam near to 0
class SAMLoss(nn.Module):
# MLP to change high dimension feature to low dimension feature for CC loss calculation
def __init__(self):
# dv is the M*N*C number of input feature-(B C M N)
super(SAMLoss, self).__init__()
def forward(self, t1, t2):
t1 = torch.reshape(t1, (t1.size(1) * t1.size(2), -1))
t2 = torch.reshape(t2, (t2.size(1) * t2.size(2), -1))
t11 = (torch.sum(t1 ** 2, dim=0)).sqrt()
t22 = (torch.sum(t2 ** 2, dim=0)).sqrt()
# print(e * f)
t12 = torch.sum(t1 * t2, dim=0)
result = t12 / (t11 * t22 + 0.0000000001)
print(result.shape)
loss = result.add_(-1).pow_(2).mean()
return loss
def dwt(y):
"""
DWT (Discrete Wavelet Transform) function implementation according to
"Multi-level Wavelet Convolutional Neural Networks"
by Pengju Liu, Hongzhi Zhang, Wei Lian, Wangmeng Zuo
https://arxiv.org/abs/1907.03128
x shape - BCHW (channel first)88ik.
"""
x = y.permute(0, 2, 3, 1)
x1 = x[:, 0::2, 0::2, :] # x(2i−1, 2j−1)
x2 = x[:, 1::2, 0::2, :] # x(2i, 2j-1)
x3 = x[:, 0::2, 1::2, :] # x(2i−1, 2j)
x4 = x[:, 1::2, 1::2, :] # x(2i, 2j)
x_LL = x1 + x2 + x3 + x4
x_LH = -x1 - x3 + x2 + x4
x_HL = -x1 + x3 - x2 + x4
x_HH = x1 - x3 - x2 + x4