forked from guojiajeremy/Dinomaly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
792 lines (617 loc) · 29.4 KB
/
Copy pathutils.py
File metadata and controls
792 lines (617 loc) · 29.4 KB
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
import torch
from dataset import get_data_transforms
from torchvision.datasets import ImageFolder
import numpy as np
from torch.utils.data import DataLoader
from dataset import MVTecDataset
from torch.nn import functional as F
from sklearn.metrics import roc_auc_score, f1_score, recall_score, accuracy_score, precision_recall_curve, \
average_precision_score
import cv2
import matplotlib.pyplot as plt
from sklearn.metrics import auc
from skimage import measure
import pandas as pd
from numpy import ndarray
from statistics import mean
from scipy.ndimage import gaussian_filter, binary_dilation
import os
from functools import partial
import math
import pickle
def modify_grad(x, inds, factor=0.):
inds = inds.expand_as(x)
x[inds] *= factor
return x
def modify_grad_v2(x, factor):
factor = factor.expand_as(x)
x *= factor
return x
def global_cosine(a, b, stop_grad=True):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
if stop_grad:
loss += torch.mean(1 - cos_loss(a[item].view(a[item].shape[0], -1).detach(),
b[item].view(b[item].shape[0], -1)))
else:
loss += torch.mean(1 - cos_loss(a[item].view(a[item].shape[0], -1),
b[item].view(b[item].shape[0], -1)))
loss = loss / len(a)
return loss
def global_cosine_hm(a, b, alpha=1., factor=0.):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
with torch.no_grad():
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1)
mean_dist = point_dist.mean()
std_dist = point_dist.reshape(-1).std()
loss += torch.mean(1 - cos_loss(a_.reshape(a_.shape[0], -1),
b_.reshape(b_.shape[0], -1)))
thresh = mean_dist + alpha * std_dist
partial_func = partial(modify_grad, inds=point_dist < thresh, factor=factor)
b_.register_hook(partial_func)
# loss = loss / len(a)
return loss
def global_cosine_hm_percent(a, b, p=0.9, factor=0.):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
with torch.no_grad():
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1)
# mean_dist = point_dist.mean()
# std_dist = point_dist.reshape(-1).std()
thresh = torch.topk(point_dist.reshape(-1), k=int(point_dist.numel() * (1 - p)))[0][-1]
loss += torch.mean(1 - cos_loss(a_.reshape(a_.shape[0], -1),
b_.reshape(b_.shape[0], -1)))
partial_func = partial(modify_grad, inds=point_dist < thresh, factor=factor)
b_.register_hook(partial_func)
loss = loss / len(a)
return loss
def regional_cosine_hm_percent(a, b, p=0.9, factor=0.):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1)
# mean_dist = point_dist.mean()
# std_dist = point_dist.reshape(-1).std()
thresh = torch.topk(point_dist.reshape(-1), k=int(point_dist.numel() * (1 - p)))[0][-1]
loss += point_dist.mean()
partial_func = partial(modify_grad, inds=point_dist < thresh, factor=factor)
b_.register_hook(partial_func)
loss = loss / len(a)
return loss
def global_cosine_focal(a, b, p=0.9, alpha=2., min_grad=0.):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
with torch.no_grad():
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1).detach()
if p < 1.:
thresh = torch.topk(point_dist.reshape(-1), k=int(point_dist.numel() * (1 - p)))[0][-1]
else:
thresh = point_dist.max()
focal_factor = torch.clip(point_dist, max=thresh) / thresh
focal_factor = focal_factor ** alpha
focal_factor = torch.clip(focal_factor, min=min_grad)
loss += torch.mean(1 - cos_loss(a_.reshape(a_.shape[0], -1),
b_.reshape(b_.shape[0], -1)))
partial_func = partial(modify_grad_v2, factor=focal_factor)
b_.register_hook(partial_func)
return loss
def regional_cosine_focal(a, b, p=0.9, alpha=2.):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1)
if p < 1.:
thresh = torch.topk(point_dist.reshape(-1), k=int(point_dist.numel() * (1 - p)))[0][-1]
else:
thresh = point_dist.max()
focal_factor = torch.clip(point_dist, max=thresh) / thresh
focal_factor = focal_factor ** alpha
loss += (point_dist * focal_factor.detach()).mean()
return loss
def regional_cosine_hm(a, b, p=0.9):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
a_ = a[item].detach()
b_ = b[item]
point_dist = 1 - cos_loss(a_, b_).unsqueeze(1)
thresh = torch.topk(point_dist.reshape(-1), k=int(point_dist.numel() * (1 - p)))[0][-1]
L = point_dist[point_dist >= thresh]
loss += L.mean()
return loss
def region_cosine(a, b, stop_grad=True):
cos_loss = torch.nn.CosineSimilarity()
loss = 0
for item in range(len(a)):
loss += 1 - cos_loss(a[item].detach(), b[item]).mean()
return loss
def cal_anomaly_map(fs_list, ft_list, out_size=224, amap_mode='add', norm_factor=None):
if not isinstance(out_size, tuple):
out_size = (out_size, out_size)
if amap_mode == 'mul':
anomaly_map = np.ones(out_size)
else:
anomaly_map = np.zeros(out_size)
a_map_list = []
for i in range(len(ft_list)):
fs = fs_list[i]
ft = ft_list[i]
a_map = 1 - F.cosine_similarity(fs, ft)
a_map = torch.unsqueeze(a_map, dim=1)
a_map = F.interpolate(a_map, size=out_size, mode='bilinear', align_corners=True)
if norm_factor is not None:
a_map = 0.1 * (a_map - norm_factor[0][i]) / (norm_factor[1][i] - norm_factor[0][i])
a_map = a_map[0, 0, :, :].to('cpu').detach().numpy()
a_map_list.append(a_map)
if amap_mode == 'mul':
anomaly_map *= a_map
else:
anomaly_map += a_map
return anomaly_map, a_map_list
def cal_anomaly_maps(fs_list, ft_list, out_size=224):
if not isinstance(out_size, tuple):
out_size = (out_size, out_size)
a_map_list = []
for i in range(len(ft_list)):
fs = fs_list[i]
ft = ft_list[i]
a_map = 1 - F.cosine_similarity(fs, ft)
a_map = torch.unsqueeze(a_map, dim=1)
a_map = F.interpolate(a_map, size=out_size, mode='bilinear', align_corners=True)
a_map_list.append(a_map)
anomaly_map = torch.cat(a_map_list, dim=1).mean(dim=1, keepdim=True)
return anomaly_map, a_map_list
def map_normalization(fs_list, ft_list, start=0.5, end=0.95):
start_list = []
end_list = []
with torch.no_grad():
for i in range(len(ft_list)):
fs = fs_list[i]
ft = ft_list[i]
a_map = 1 - F.cosine_similarity(fs, ft)
start_list.append(torch.quantile(a_map, q=start).item())
end_list.append(torch.quantile(a_map, q=end).item())
return [start_list, end_list]
def cal_anomaly_map_v2(fs_list, ft_list, out_size=224, amap_mode='add'):
a_map_list = []
for i in range(len(ft_list)):
fs = fs_list[i]
ft = ft_list[i]
a_map = 1 - F.cosine_similarity(fs, ft)
a_map = torch.unsqueeze(a_map, dim=1)
a_map = F.interpolate(a_map, size=out_size // 4, mode='bilinear', align_corners=False)
a_map_list.append(a_map)
anomaly_map = torch.stack(a_map_list, dim=-1).sum(-1)
anomaly_map = F.interpolate(anomaly_map, size=out_size, mode='bilinear', align_corners=False)
anomaly_map = anomaly_map[0, 0, :, :].to('cpu').detach().numpy()
return anomaly_map, a_map_list
def show_cam_on_image(img, anomaly_map):
cam = np.float32(anomaly_map) / 255 + np.float32(img) / 255
cam = cam / np.max(cam)
return np.uint8(255 * cam)
def min_max_norm(image):
a_min, a_max = image.min(), image.max()
return (image - a_min) / (a_max - a_min)
def cvt2heatmap(gray):
heatmap = cv2.applyColorMap(np.uint8(gray), cv2.COLORMAP_JET)
return heatmap
def return_best_thr(y_true, y_score):
precs, recs, thrs = precision_recall_curve(y_true, y_score)
f1s = 2 * precs * recs / (precs + recs + 1e-7)
f1s = f1s[:-1]
thrs = thrs[~np.isnan(f1s)]
f1s = f1s[~np.isnan(f1s)]
best_thr = thrs[np.argmax(f1s)]
return best_thr
def f1_score_max(y_true, y_score):
precs, recs, thrs = precision_recall_curve(y_true, y_score)
f1s = 2 * precs * recs / (precs + recs + 1e-7)
f1s = f1s[:-1]
return f1s.max()
def specificity_score(y_true, y_score):
y_true = np.array(y_true)
y_score = np.array(y_score)
TN = (y_true[y_score == 0] == 0).sum()
N = (y_true == 0).sum()
return TN / N
def evaluation(model, dataloader, device, _class_=None, calc_pro=True, norm_factor=None, feature_used='all',
max_ratio=0):
model.eval()
gt_list_px = []
pr_list_px = []
gt_list_sp = []
pr_list_sp = []
aupro_list = []
with torch.no_grad():
for img, gt, label, _ in dataloader:
img = img.to(device)
en, de = model(img)
if feature_used == 'trained':
anomaly_map, _ = cal_anomaly_map(en[3:], de[3:], img.shape[-1], amap_mode='a', norm_factor=norm_factor)
elif feature_used == 'freezed':
anomaly_map, _ = cal_anomaly_map(en[:3], de[:3], img.shape[-1], amap_mode='a', norm_factor=norm_factor)
else:
anomaly_map, _ = cal_anomaly_map(en, de, img.shape[-1], amap_mode='a', norm_factor=norm_factor)
anomaly_map = gaussian_filter(anomaly_map, sigma=4)
# gt[gt > 0.5] = 1
# gt[gt <= 0.5] = 0
gt = gt.bool()
if calc_pro:
if label.item() != 0:
aupro_list.append(compute_pro(gt.squeeze(0).cpu().numpy().astype(int),
anomaly_map[np.newaxis, :, :]))
gt_list_px.extend(gt.cpu().numpy().astype(int).ravel())
pr_list_px.extend(anomaly_map.ravel())
gt_list_sp.append(np.max(gt.cpu().numpy().astype(int)))
if max_ratio <= 0:
sp_score = anomaly_map.max()
else:
anomaly_map = anomaly_map.ravel()
sp_score = np.sort(anomaly_map)[-int(anomaly_map.shape[0] * max_ratio):]
sp_score = sp_score.mean()
pr_list_sp.append(sp_score)
auroc_px = round(roc_auc_score(gt_list_px, pr_list_px), 4)
auroc_sp = round(roc_auc_score(gt_list_sp, pr_list_sp), 4)
return auroc_px, auroc_sp, round(np.mean(aupro_list), 4)
def evaluation_batch(model, dataloader, device, _class_=None, max_ratio=0, resize_mask=None):
model.eval()
gt_list_px = []
pr_list_px = []
gt_list_sp = []
pr_list_sp = []
gaussian_kernel = get_gaussian_kernel(kernel_size=5, sigma=4).to(device)
starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
with torch.no_grad():
for img, gt, label, img_path in dataloader:
img = img.to(device)
# starter.record()
output = model(img)
# ender.record()
# torch.cuda.synchronize()
# curr_time = starter.elapsed_time(ender)
en, de = output[0], output[1]
anomaly_map, _ = cal_anomaly_maps(en, de, img.shape[-1])
# anomaly_map = anomaly_map - anomaly_map.mean(dim=[1, 2, 3]).view(-1, 1, 1, 1)
if resize_mask is not None:
anomaly_map = F.interpolate(anomaly_map, size=resize_mask, mode='bilinear', align_corners=False)
gt = F.interpolate(gt, size=resize_mask, mode='nearest')
anomaly_map = gaussian_kernel(anomaly_map)
gt = gt.bool()
if gt.shape[1] > 1:
gt = torch.max(gt, dim=1, keepdim=True)[0]
gt_list_px.append(gt)
pr_list_px.append(anomaly_map)
gt_list_sp.append(label)
if max_ratio == 0:
sp_score = torch.max(anomaly_map.flatten(1), dim=1)[0]
else:
anomaly_map = anomaly_map.flatten(1)
sp_score = torch.sort(anomaly_map, dim=1, descending=True)[0][:, :int(anomaly_map.shape[1] * max_ratio)]
sp_score = sp_score.mean(dim=1)
pr_list_sp.append(sp_score)
gt_list_px = torch.cat(gt_list_px, dim=0)[:, 0].cpu().numpy()
pr_list_px = torch.cat(pr_list_px, dim=0)[:, 0].cpu().numpy()
gt_list_sp = torch.cat(gt_list_sp).flatten().cpu().numpy()
pr_list_sp = torch.cat(pr_list_sp).flatten().cpu().numpy()
aupro_px = compute_pro(gt_list_px, pr_list_px)
gt_list_px, pr_list_px = gt_list_px.ravel(), pr_list_px.ravel()
auroc_px = roc_auc_score(gt_list_px, pr_list_px)
auroc_sp = roc_auc_score(gt_list_sp, pr_list_sp)
ap_px = average_precision_score(gt_list_px, pr_list_px)
ap_sp = average_precision_score(gt_list_sp, pr_list_sp)
f1_sp = f1_score_max(gt_list_sp, pr_list_sp)
f1_px = f1_score_max(gt_list_px, pr_list_px)
return [auroc_sp, ap_sp, f1_sp, auroc_px, ap_px, f1_px, aupro_px]
def evaluation_batch_loco(model, dataloader, device, _class_=None, max_ratio=0):
model.eval()
gt_list_px = []
pr_list_px = []
gt_list_sp = []
pr_list_sp = []
defect_type_list = []
gaussian_kernel = get_gaussian_kernel(kernel_size=5, sigma=4).to(device)
with torch.no_grad():
for img, gt, label, path, defect_type, size in dataloader:
img = img.to(device)
output = model(img)
en, de = output[0], output[1]
anomaly_map, _ = cal_anomaly_maps(en, de, img.shape[-1])
anomaly_map = gaussian_kernel(anomaly_map)
gt = gt.bool()
gt_list_px.extend(gt.cpu().numpy().astype(int).ravel())
pr_list_px.extend(anomaly_map.cpu().numpy().ravel())
gt_list_sp.extend(label.cpu().numpy().astype(int))
if max_ratio == 0:
sp_score = torch.max(anomaly_map.flatten(1), dim=1)[0].cpu().numpy()
else:
anomaly_map = anomaly_map.flatten(1)
sp_score = torch.sort(anomaly_map, dim=1, descending=True)[0][:, :int(anomaly_map.shape[1] * max_ratio)]
sp_score = sp_score.mean(dim=1).cpu().numpy()
pr_list_sp.extend(sp_score)
defect_type_list.extend(defect_type)
auroc_px = round(roc_auc_score(gt_list_px, pr_list_px), 4)
auroc_sp = round(roc_auc_score(gt_list_sp, pr_list_sp), 4)
ap_px = round(average_precision_score(gt_list_px, pr_list_px), 4)
ap_sp = round(average_precision_score(gt_list_sp, pr_list_sp), 4)
defect_type_list = np.array(defect_type_list)
auroc_logic = roc_auc_score(
np.array(gt_list_sp)[np.logical_or(defect_type_list == 'good', defect_type_list == 'logical_anomalies')],
np.array(pr_list_sp)[np.logical_or(defect_type_list == 'good', defect_type_list == 'logical_anomalies')])
auroc_struct = roc_auc_score(
np.array(gt_list_sp)[np.logical_or(defect_type_list == 'good', defect_type_list == 'structural_anomalies')],
np.array(pr_list_sp)[np.logical_or(defect_type_list == 'good', defect_type_list == 'structural_anomalies')])
auroc_both = (auroc_logic + auroc_struct) / 2
return auroc_sp, auroc_logic, auroc_struct, auroc_both
def evaluation_uniad(model, dataloader, device, _class_=None, reg_calib=False, max_ratio=0):
model.eval()
gt_list_px = []
pr_list_px = []
gt_list_sp = []
pr_list_sp = []
aupro_list = []
gaussian_kernel = get_gaussian_kernel(kernel_size=5, sigma=4).to(device)
with torch.no_grad():
for img, gt, label, _ in dataloader:
img = img.to(device)
if reg_calib:
en, de, reg = model({'image': img})
else:
en, de = model({'image': img})
anomaly_map = torch.mean(F.mse_loss(de, en, reduction='none'), dim=1, keepdim=True)
anomaly_map = F.interpolate(anomaly_map, size=(img.shape[-1], img.shape[-1]), mode='bilinear',
align_corners=False)
if reg_calib:
if reg.shape[1] == 2:
reg_mean = reg[:, 0].view(-1, 1, 1, 1)
reg_max = reg[:, 1].view(-1, 1, 1, 1)
anomaly_map = (anomaly_map - reg_mean) / (reg_max - reg_mean)
# anomaly_map = anomaly_map - reg_max
else:
reg = F.interpolate(reg, size=img.shape[-1], mode='bilinear', align_corners=True)
anomaly_map = anomaly_map - reg
anomaly_map = gaussian_kernel(anomaly_map)
gt = gt.bool()
gt_list_px.extend(gt.cpu().numpy().astype(int).ravel())
pr_list_px.extend(anomaly_map.cpu().numpy().ravel())
gt_list_sp.extend(label.cpu().numpy().astype(int))
if max_ratio == 0:
sp_score = torch.max(anomaly_map.flatten(1), dim=1)[0].cpu().numpy()
else:
anomaly_map = anomaly_map.flatten(1)
sp_score = torch.sort(anomaly_map, dim=1, descending=True)[0][:, :int(anomaly_map.shape[1] * max_ratio)]
sp_score = sp_score.mean(dim=1).cpu().numpy()
pr_list_sp.extend(sp_score)
auroc_px = round(roc_auc_score(gt_list_px, pr_list_px), 4)
auroc_sp = round(roc_auc_score(gt_list_sp, pr_list_sp), 4)
ap_px = round(average_precision_score(gt_list_px, pr_list_px), 4)
ap_sp = round(average_precision_score(gt_list_sp, pr_list_sp), 4)
return auroc_px, auroc_sp, ap_px, ap_sp, [gt_list_px, pr_list_px, gt_list_sp, pr_list_sp]
def visualize(model, dataloader, device, _class_='None', save_name='save'):
model.eval()
save_dir = os.path.join('./visualize', save_name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
gaussian_kernel = get_gaussian_kernel(kernel_size=5, sigma=4).to(device)
with torch.no_grad():
for img, gt, label, img_path in dataloader:
img = img.to(device)
output = model(img)
en, de = output[0], output[1]
anomaly_map, _ = cal_anomaly_maps(en, de, img.shape[-1])
anomaly_map = gaussian_kernel(anomaly_map)
for i in range(0, anomaly_map.shape[0], 8):
heatmap = min_max_norm(anomaly_map[i, 0].cpu().numpy())
heatmap = cvt2heatmap(heatmap * 255)
im = img[i].permute(1, 2, 0).cpu().numpy()
im = im * np.array([0.229, 0.224, 0.225]) + np.array([0.485, 0.456, 0.406])
im = (im * 255).astype('uint8')
im = im[:, :, ::-1]
hm_on_img = show_cam_on_image(im, heatmap)
mask = (gt[i][0].numpy() * 255).astype('uint8')
save_dir_class = os.path.join(save_dir, str(_class_))
if not os.path.exists(save_dir_class):
os.mkdir(save_dir_class)
name = img_path[i].split('/')[-2] + '_' + img_path[i].split('/')[-1].replace('.png', '')
cv2.imwrite(save_dir_class + '/' + name + '_img.png', im)
cv2.imwrite(save_dir_class + '/' + name + '_cam.png', hm_on_img)
cv2.imwrite(save_dir_class + '/' + name + '_gt.png', mask)
return
def save_feature(model, dataloader, device, _class_='None', save_name='save'):
model.eval()
save_dir = os.path.join('./feature', save_name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
with torch.no_grad():
for img, gt, label, img_path in dataloader:
img = img.to(device)
en, de = model(img)
en_abnorm_list = []
en_normal_list = []
de_abnorm_list = []
de_normal_list = []
for i in range(3):
en_feat = en[0 + i]
de_feat = de[0 + i]
gt_resize = F.interpolate(gt, size=en_feat.shape[2], mode='bilinear') > 0
en_abnorm = en_feat.permute(0, 2, 3, 1)[gt_resize.permute(0, 2, 3, 1)[:, :, :, 0]]
en_normal = en_feat.permute(0, 2, 3, 1)[gt_resize.permute(0, 2, 3, 1)[:, :, :, 0] == 0]
de_abnorm = de_feat.permute(0, 2, 3, 1)[gt_resize.permute(0, 2, 3, 1)[:, :, :, 0]]
de_normal = de_feat.permute(0, 2, 3, 1)[gt_resize.permute(0, 2, 3, 1)[:, :, :, 0] == 0]
en_abnorm_list.append(F.normalize(en_abnorm, dim=1).cpu().numpy())
en_normal_list.append(F.normalize(en_normal, dim=1).cpu().numpy())
de_abnorm_list.append(F.normalize(de_abnorm, dim=1).cpu().numpy())
de_normal_list.append(F.normalize(de_normal, dim=1).cpu().numpy())
save_dir_class = os.path.join(save_dir, str(_class_))
if not os.path.exists(save_dir_class):
os.mkdir(save_dir_class)
name = img_path[0].split('/')[-2] + '_' + img_path[0].split('/')[-1].replace('.png', '')
saved_dict = {'en_abnorm_list': en_abnorm_list, 'en_normal_list': en_normal_list,
'de_abnorm_list': de_abnorm_list, 'de_normal_list': de_normal_list}
with open(save_dir_class + '/' + name + '.pkl', 'wb') as f:
pickle.dump(saved_dict, f)
return
def visualize_noseg(model, dataloader, device, _class_='None', save_name='save'):
model.eval()
save_dir = os.path.join('./visualize', save_name)
if not os.path.exists(save_dir):
os.mkdir(save_dir)
with torch.no_grad():
for img, label, img_path in dataloader:
img = img.to(device)
en, de = model(img)
anomaly_map, _ = cal_anomaly_map(en, de, img.shape[-1], amap_mode='a')
anomaly_map = gaussian_filter(anomaly_map, sigma=4)
heatmap = min_max_norm(anomaly_map)
heatmap = cvt2heatmap(heatmap * 255)
img = img.permute(0, 2, 3, 1).cpu().numpy()[0]
img = img * np.array([0.229, 0.224, 0.225]) + np.array([0.485, 0.456, 0.406])
img = (img * 255).astype('uint8')
hm_on_img = show_cam_on_image(img, heatmap)
save_dir_class = os.path.join(save_dir, str(_class_))
if not os.path.exists(save_dir_class):
os.mkdir(save_dir_class)
name = img_path[0].split('/')[-2] + '_' + img_path[0].split('/')[-1].replace('.png', '')
cv2.imwrite(save_dir_class + '/' + name + '_seg.png', heatmap)
cv2.imwrite(save_dir_class + '/' + name + '_cam.png', hm_on_img)
return
def visualize_loco(model, dataloader, device, _class_='None', save_name='save'):
model.eval()
save_dir = os.path.join('./visualize', save_name)
with torch.no_grad():
for img, gt, label, img_path, defect_type, size in dataloader:
img = img.to(device)
en, de = model(img)
anomaly_map, _ = cal_anomaly_map(en, de, img.shape[-1], amap_mode='a')
anomaly_map = gaussian_filter(anomaly_map, sigma=4)
anomaly_map = cv2.resize(anomaly_map, dsize=(size[0].item(), size[1].item()),
interpolation=cv2.INTER_NEAREST)
save_dir_class = os.path.join(save_dir, str(_class_), 'test', defect_type[0])
if not os.path.exists(save_dir_class):
os.makedirs(save_dir_class)
name = img_path[0].split('/')[-1].replace('.png', '')
cv2.imwrite(save_dir_class + '/' + name + '.tiff', anomaly_map)
return
def compute_pro(masks: ndarray, amaps: ndarray, num_th: int = 200) -> None:
"""Compute the area under the curve of per-region overlaping (PRO) and 0 to 0.3 FPR
Args:
category (str): Category of product
masks (ndarray): All binary masks in test. masks.shape -> (num_test_data, h, w)
amaps (ndarray): All anomaly maps in test. amaps.shape -> (num_test_data, h, w)
num_th (int, optional): Number of thresholds
"""
assert isinstance(amaps, ndarray), "type(amaps) must be ndarray"
assert isinstance(masks, ndarray), "type(masks) must be ndarray"
assert amaps.ndim == 3, "amaps.ndim must be 3 (num_test_data, h, w)"
assert masks.ndim == 3, "masks.ndim must be 3 (num_test_data, h, w)"
assert amaps.shape == masks.shape, "amaps.shape and masks.shape must be same"
assert set(masks.flatten()) == {0, 1}, "set(masks.flatten()) must be {0, 1}"
assert isinstance(num_th, int), "type(num_th) must be int"
df = pd.DataFrame([], columns=["pro", "fpr", "threshold"])
binary_amaps = np.zeros_like(amaps, dtype=np.bool)
min_th = amaps.min()
max_th = amaps.max()
delta = (max_th - min_th) / num_th
for th in np.arange(min_th, max_th, delta):
binary_amaps[amaps <= th] = 0
binary_amaps[amaps > th] = 1
pros = []
for binary_amap, mask in zip(binary_amaps, masks):
for region in measure.regionprops(measure.label(mask)):
axes0_ids = region.coords[:, 0]
axes1_ids = region.coords[:, 1]
tp_pixels = binary_amap[axes0_ids, axes1_ids].sum()
pros.append(tp_pixels / region.area)
inverse_masks = 1 - masks
fp_pixels = np.logical_and(inverse_masks, binary_amaps).sum()
fpr = fp_pixels / inverse_masks.sum()
df = df.append({"pro": mean(pros), "fpr": fpr, "threshold": th}, ignore_index=True)
# Normalize FPR from 0 ~ 1 to 0 ~ 0.3
df = df[df["fpr"] < 0.3]
df["fpr"] = df["fpr"] / df["fpr"].max()
pro_auc = auc(df["fpr"], df["pro"])
return pro_auc
def get_gaussian_kernel(kernel_size=3, sigma=2, channels=1):
# Create a x, y coordinate grid of shape (kernel_size, kernel_size, 2)
x_coord = torch.arange(kernel_size)
x_grid = x_coord.repeat(kernel_size).view(kernel_size, kernel_size)
y_grid = x_grid.t()
xy_grid = torch.stack([x_grid, y_grid], dim=-1).float()
mean = (kernel_size - 1) / 2.
variance = sigma ** 2.
# Calculate the 2-dimensional gaussian kernel which is
# the product of two gaussian distributions for two different
# variables (in this case called x and y)
gaussian_kernel = (1. / (2. * math.pi * variance)) * \
torch.exp(
-torch.sum((xy_grid - mean) ** 2., dim=-1) / \
(2 * variance)
)
# Make sure sum of values in gaussian kernel equals 1.
gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel)
# Reshape to 2d depthwise convolutional weight
gaussian_kernel = gaussian_kernel.view(1, 1, kernel_size, kernel_size)
gaussian_kernel = gaussian_kernel.repeat(channels, 1, 1, 1)
gaussian_filter = torch.nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=kernel_size,
groups=channels,
bias=False, padding=kernel_size // 2)
gaussian_filter.weight.data = gaussian_kernel
gaussian_filter.weight.requires_grad = False
return gaussian_filter
class FeatureJitter(torch.nn.Module):
def __init__(self, scale=1., p=0.25) -> None:
super(FeatureJitter, self).__init__()
self.scale = scale
self.p = p
def add_jitter(self, feature):
if self.scale > 0:
B, C, H, W = feature.shape
feature_norms = feature.norm(dim=1).unsqueeze(1) / C # B*1*H*W
jitter = torch.randn((B, C, H, W), device=feature.device)
jitter = F.normalize(jitter, dim=1)
jitter = jitter * feature_norms * self.scale
mask = torch.rand((B, 1, H, W), device=feature.device) < self.p
feature = feature + jitter * mask
return feature
def forward(self, x):
if self.training:
x = self.add_jitter(x)
return x
def replace_layers(model, old, new):
for n, module in model.named_children():
if len(list(module.children())) > 0:
## compound module, go inside it
replace_layers(module, old, new)
if isinstance(module, old):
## simple module
setattr(model, n, new)
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class WarmCosineScheduler(_LRScheduler):
def __init__(self, optimizer, base_value, final_value, total_iters, warmup_iters=0, start_warmup_value=0, ):
self.final_value = final_value
self.total_iters = total_iters
warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
iters = np.arange(total_iters - warmup_iters)
schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters)))
self.schedule = np.concatenate((warmup_schedule, schedule))
super(WarmCosineScheduler, self).__init__(optimizer)
def get_lr(self):
if self.last_epoch >= self.total_iters:
return [self.final_value for base_lr in self.base_lrs]
else:
return [self.schedule[self.last_epoch] for base_lr in self.base_lrs]