-
Notifications
You must be signed in to change notification settings - Fork 2
/
test_sysu.py
2601 lines (2152 loc) · 127 KB
/
test_sysu.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
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
import collections
import time
from datetime import timedelta
from solver import make_optimizer, WarmupMultiStepLR
from sklearn.cluster import DBSCAN
from PIL import Image
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
import torch.nn.functional as F
from config import cfg
from clustercontrast import datasets
# from clustercontrast import models
from clustercontrast.model_vit_cmrefine import make_model
from torch import einsum
\
from clustercontrast.models.cm import ClusterMemory,ClusterMemory_all,Memory_wise_v3
from clustercontrast.evaluators import Evaluator, extract_features
from clustercontrast.utils.data import IterLoader
from clustercontrast.utils.data import transforms as T
from clustercontrast.utils.data.preprocessor import Preprocessor,Preprocessor_color
from clustercontrast.utils.logging import Logger
from clustercontrast.utils.serialization import load_checkpoint, save_checkpoint
from clustercontrast.utils.faiss_rerank import compute_jaccard_distance,compute_ranked_list,compute_ranked_list_cm
from clustercontrast.utils.data.sampler import RandomMultipleGallerySampler, RandomMultipleGallerySamplerNoCam,MoreCameraSampler
import os
import torch.utils.data as data
from torch.autograd import Variable
import math
from ChannelAug import ChannelAdap, ChannelAdapGray, ChannelRandomErasing,ChannelExchange,Gray
from collections import Counter
from solver.scheduler_factory import create_scheduler
from typing import Tuple, List, Optional
from torch import Tensor
import numbers
from typing import Any, BinaryIO, List, Optional, Tuple, Union
import cv2
import copy
import os.path as osp
import errno
import shutil
start_epoch = best_mAP = 0
def mkdir_if_missing(dir_path):
try:
os.makedirs(dir_path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
part=1
torch.backends.cudnn.enable =True,
torch.backends.cudnn.benchmark = True
# l2norm = Normalize(2)
class channel_jitter(object):
def __init__(self,channel=0):
self.jitter = T.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
self.trans = T.Compose([
self.jitter
])
def __call__(self, img):
img_np=np.array(self.trans(img))
# idx = random.randint(0, 21)
channel_1 = cv2.applyColorMap(img_np, random.randint(0, 21))
channel_2 = cv2.applyColorMap(img_np, random.randint(0, 21))
channel_3 = cv2.applyColorMap(img_np, random.randint(0, 21))
img_np[0, :,:] = channel_1[0,:,:]
img_np[1, :,:] = channel_2[1,:,:]
img_np[2, :,:] = channel_3[2,:,:]
img = Image.fromarray(img_np, 'RGB')
idx = random.randint(0, 100)
img.save('figs/channel_jitter_'+str(idx)+'.jpg')
print(img)
return img
def get_data(name, data_dir):
root = osp.join(data_dir, name)
dataset = datasets.create(name, root)
return dataset
class channel_select(object):
def __init__(self,channel=0):
self.channel = channel
def __call__(self, img):
if self.channel == 3:
img_gray = img.convert('L')
np_img = np.array(img_gray, dtype=np.uint8)
img_aug = np.dstack([np_img, np_img, np_img])
img_PIL=Image.fromarray(img_aug, 'RGB')
else:
np_img = np.array(img, dtype=np.uint8)
np_img = np_img[:,:,self.channel]
img_aug = np.dstack([np_img, np_img, np_img])
img_PIL=Image.fromarray(img_aug, 'RGB')
return img_PIL
def get_train_loader_ir(args, dataset, height, width, batch_size, workers,
num_instances, iters, trainset=None, no_cam=False,train_transformer=None):
# train_transformer = T.Compose([
# T.Resize((height, width), interpolation=3),
# T.RandomHorizontalFlip(p=0.5),
# T.Pad(10),
# T.RandomCrop((height, width)),
# T.ToTensor(),
# normalizer,
# T.RandomErasing(probability=0.5, mean=[0.485, 0.456, 0.406])
# ])
train_set = sorted(dataset.train) if trainset is None else sorted(trainset)
rmgs_flag = num_instances > 0
if rmgs_flag:
if no_cam:
sampler = RandomMultipleGallerySamplerNoCam(train_set, num_instances)
else:
# sampler = MoreCameraSampler(train_set, num_instances)
sampler = RandomMultipleGallerySampler(train_set, num_instances)
else:
sampler = None
train_loader = IterLoader(
DataLoader(Preprocessor(train_set, root=dataset.images_dir, transform=train_transformer),
batch_size=batch_size, num_workers=workers, sampler=sampler,
shuffle=not rmgs_flag, pin_memory=True, drop_last=True), length=iters)
return train_loader
def get_train_loader_color(args, dataset, height, width, batch_size, workers,
num_instances, iters, trainset=None, no_cam=False,train_transformer=None,train_transformer1=None):
# train_transformer = T.Compose([
# T.Resize((height, width), interpolation=3),
# T.RandomHorizontalFlip(p=0.5),
# T.Pad(10),
# T.RandomCrop((height, width)),
# T.ToTensor(),
# normalizer,
# T.RandomErasing(probability=0.5, mean=[0.485, 0.456, 0.406])
# ])
train_set = sorted(dataset.train) if trainset is None else sorted(trainset)
rmgs_flag = num_instances > 0
if rmgs_flag:
if no_cam:
sampler = RandomMultipleGallerySamplerNoCam(train_set, num_instances)
else:
# sampler = MoreCameraSampler(train_set, num_instances)
sampler = RandomMultipleGallerySampler(train_set, num_instances)
else:
sampler = None
if train_transformer1 is None:
train_loader = IterLoader(
DataLoader(Preprocessor(train_set, root=dataset.images_dir, transform=train_transformer),
batch_size=batch_size, num_workers=workers, sampler=sampler,
shuffle=not rmgs_flag, pin_memory=True, drop_last=True), length=iters)
else:
train_loader = IterLoader(
DataLoader(Preprocessor_color(train_set, root=dataset.images_dir, transform=train_transformer,transform1=train_transformer1),
batch_size=batch_size, num_workers=workers, sampler=sampler,
shuffle=not rmgs_flag, pin_memory=True, drop_last=True), length=iters)
return train_loader
def get_test_loader(dataset, height, width, batch_size, workers, testset=None,test_transformer=None):
normalizer = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
if test_transformer is None:
test_transformer = T.Compose([
T.Resize((height, width), interpolation=3),
T.ToTensor(),
normalizer
])
if testset is None:
testset = list(set(dataset.query) | set(dataset.gallery))
test_loader = DataLoader(
Preprocessor(testset, root=dataset.images_dir, transform=test_transformer),
batch_size=batch_size, num_workers=workers,
shuffle=False, pin_memory=True)
return test_loader
def create_model(args):
model = models.create(args.arch, num_features=args.features, norm=True, dropout=args.dropout,
num_classes=0, pooling_type=args.pooling_type)
# use CUDA
model.cuda()
model = nn.DataParallel(model)#,output_device=1)
return model
class TestData(data.Dataset):
def __init__(self, test_img_file, test_label, transform=None, img_size = (144,288)):
test_image = []
for i in range(len(test_img_file)):
img = Image.open(test_img_file[i])
img = img.resize((img_size[0], img_size[1]), Image.ANTIALIAS)
pix_array = np.array(img)
test_image.append(pix_array)
test_image = np.array(test_image)
self.test_image = test_image
self.test_label = test_label
self.transform = transform
def __getitem__(self, index):
img1, target1 = self.test_image[index], self.test_label[index]
img1 = self.transform(img1)
return img1, target1
def __len__(self):
return len(self.test_image)
def process_query_sysu(data_path, mode = 'all', relabel=False):
if mode== 'all':
ir_cameras = ['cam3','cam6']
elif mode =='indoor':
ir_cameras = ['cam3','cam6']
file_path = os.path.join(data_path,'exp/test_id.txt')
files_rgb = []
files_ir = []
with open(file_path, 'r') as file:
ids = file.read().splitlines()
ids = [int(y) for y in ids[0].split(',')]
ids = ["%04d" % x for x in ids]
for id in sorted(ids):
for cam in ir_cameras:
img_dir = os.path.join(data_path,cam,id)
if os.path.isdir(img_dir):
new_files = sorted([img_dir+'/'+i for i in os.listdir(img_dir)])
files_ir.extend(new_files)
query_img = []
query_id = []
query_cam = []
for img_path in files_ir:
camid, pid = int(img_path[-15]), int(img_path[-13:-9])
query_img.append(img_path)
query_id.append(pid)
query_cam.append(camid)
return query_img, np.array(query_id), np.array(query_cam)
def process_gallery_sysu(data_path, mode = 'all', trial = 0, relabel=False):
random.seed(trial)
if mode== 'all':
rgb_cameras = ['cam1','cam2','cam4','cam5']
elif mode =='indoor':
rgb_cameras = ['cam1','cam2']
file_path = os.path.join(data_path,'exp/test_id.txt')
files_rgb = []
with open(file_path, 'r') as file:
ids = file.read().splitlines()
ids = [int(y) for y in ids[0].split(',')]
ids = ["%04d" % x for x in ids]
for id in sorted(ids):
for cam in rgb_cameras:
img_dir = os.path.join(data_path,cam,id)
if os.path.isdir(img_dir):
new_files = sorted([img_dir+'/'+i for i in os.listdir(img_dir)])
files_rgb.append(random.choice(new_files))
gall_img = []
gall_id = []
gall_cam = []
for img_path in files_rgb:
camid, pid = int(img_path[-15]), int(img_path[-13:-9])
gall_img.append(img_path)
gall_id.append(pid)
gall_cam.append(camid)
return gall_img, np.array(gall_id), np.array(gall_cam)
def fliplr(img):
'''flip horizontal'''
inv_idx = torch.arange(img.size(3)-1,-1,-1).long() # N x C x H x W
img_flip = img.index_select(3,inv_idx)
return img_flip
def extract_gall_feat(model,gall_loader,ngall):
pool_dim=768*2
net = model
net.eval()
print ('Extracting Gallery Feature...')
start = time.time()
ptr = 0
gall_feat_pool = np.zeros((ngall, pool_dim))
gall_feat_fc = np.zeros((ngall, pool_dim))
with torch.no_grad():
for batch_idx, (input, label ) in enumerate(gall_loader):
batch_num = input.size(0)
flip_input = fliplr(input)
input = Variable(input.cuda())
feat_fc,feat_fc_s = net( input,input, 1)
# feat_fc = torch.cat((feat_fc,feat_fc_s),dim=1)
flip_input = Variable(flip_input.cuda())
feat_fc_1,feat_fc_1_s = net( flip_input,flip_input, 1)
# feat_fc_1 = torch.cat((feat_fc_1,feat_fc_1_s),dim=1)
feature_fc = (feat_fc.detach() + feat_fc_1.detach())/2
feature_fc_s = (feat_fc_s.detach() + feat_fc_1_s.detach())/2
fnorm_fc = torch.norm(feature_fc, p=2, dim=1, keepdim=True)
feature_fc = feature_fc.div(fnorm_fc.expand_as(feature_fc))
fnorm_fc_s = torch.norm(feature_fc_s, p=2, dim=1, keepdim=True)
feature_fc_s = feature_fc_s.div(fnorm_fc_s.expand_as(feature_fc))
feature_fc = torch.cat((feature_fc,feature_fc_s),dim=1)
gall_feat_fc[ptr:ptr+batch_num,: ] = feature_fc.cpu().numpy()
ptr = ptr + batch_num
print('Extracting Time:\t {:.3f}'.format(time.time()-start))
return gall_feat_fc
def extract_query_feat(model,query_loader,nquery):
pool_dim=768*2
net = model
net.eval()
print ('Extracting Query Feature...')
start = time.time()
ptr = 0
query_feat_pool = np.zeros((nquery, pool_dim))
query_feat_fc = np.zeros((nquery, pool_dim))
with torch.no_grad():
for batch_idx, (input, label ) in enumerate(query_loader):
batch_num = input.size(0)
flip_input = fliplr(input)
input = Variable(input.cuda())
feat_fc,feat_fc_s = net( input, input,2)
# feat_fc = torch.cat((feat_fc,feat_fc_s),dim=1)
flip_input = Variable(flip_input.cuda())
feat_fc_1,feat_fc_1_s= net( flip_input,flip_input, 2)
# feat_fc_1 = torch.cat((feat_fc_1,feat_fc_1_s),dim=1)
feature_fc = (feat_fc.detach() + feat_fc_1.detach())/2
feature_fc_s = (feat_fc_s.detach() + feat_fc_1_s.detach())/2
fnorm_fc = torch.norm(feature_fc, p=2, dim=1, keepdim=True)
feature_fc = feature_fc.div(fnorm_fc.expand_as(feature_fc))
fnorm_fc_s = torch.norm(feature_fc_s, p=2, dim=1, keepdim=True)
feature_fc_s = feature_fc_s.div(fnorm_fc_s.expand_as(feature_fc))
feature_fc = torch.cat((feature_fc,feature_fc_s),dim=1)
query_feat_fc[ptr:ptr+batch_num,: ] = feature_fc.cpu().numpy()
ptr = ptr + batch_num
print('Extracting Time:\t {:.3f}'.format(time.time()-start))
return query_feat_fc
def eval_sysu(distmat, q_pids, g_pids, q_camids, g_camids, max_rank = 20):
"""Evaluation with sysu metric
Key: for each query identity, its gallery images from the same camera view are discarded. "Following the original setting in ite dataset"
"""
num_q, num_g = distmat.shape
if num_g < max_rank:
max_rank = num_g
print("Note: number of gallery samples is quite small, got {}".format(num_g))
indices = np.argsort(distmat, axis=1)
pred_label = g_pids[indices]
matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32)
# compute cmc curve for each query
new_all_cmc = []
all_cmc = []
all_AP = []
all_INP = []
num_valid_q = 0. # number of valid query
for q_idx in range(num_q):
# get query pid and camid
q_pid = q_pids[q_idx]
q_camid = q_camids[q_idx]
# remove gallery samples that have the same pid and camid with query
order = indices[q_idx]
remove = (q_camid == 3) & (g_camids[order] == 2)
keep = np.invert(remove)
# compute cmc curve
# the cmc calculation is different from standard protocol
# we follow the protocol of the author's released code
new_cmc = pred_label[q_idx][keep]
new_index = np.unique(new_cmc, return_index=True)[1]
new_cmc = [new_cmc[index] for index in sorted(new_index)]
new_match = (new_cmc == q_pid).astype(np.int32)
new_cmc = new_match.cumsum()
new_all_cmc.append(new_cmc[:max_rank])
orig_cmc = matches[q_idx][keep] # binary vector, positions with value 1 are correct matches
if not np.any(orig_cmc):
# this condition is true when query identity does not appear in gallery
continue
cmc = orig_cmc.cumsum()
# compute mINP
# refernece Deep Learning for Person Re-identification: A Survey and Outlook
pos_idx = np.where(orig_cmc == 1)
pos_max_idx = np.max(pos_idx)
inp = cmc[pos_max_idx]/ (pos_max_idx + 1.0)
all_INP.append(inp)
cmc[cmc > 1] = 1
all_cmc.append(cmc[:max_rank])
num_valid_q += 1.
# compute average precision
# reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision
num_rel = orig_cmc.sum()
tmp_cmc = orig_cmc.cumsum()
tmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)]
tmp_cmc = np.asarray(tmp_cmc) * orig_cmc
AP = tmp_cmc.sum() / num_rel
all_AP.append(AP)
assert num_valid_q > 0, "Error: all query identities do not appear in gallery"
all_cmc = np.asarray(all_cmc).astype(np.float32)
all_cmc = all_cmc.sum(0) / num_valid_q # standard CMC
new_all_cmc = np.asarray(new_all_cmc).astype(np.float32)
new_all_cmc = new_all_cmc.sum(0) / num_valid_q
mAP = np.mean(all_AP)
mINP = np.mean(all_INP)
return new_all_cmc, mAP, mINP
def pairwise_distance(features_q, features_g):
x = torch.from_numpy(features_q)
y = torch.from_numpy(features_g)
m, n = x.size(0), y.size(0)
x = x.view(m, -1)
y = y.view(n, -1)
dist_m = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(m, n) + \
torch.pow(y, 2).sum(dim=1, keepdim=True).expand(n, m).t()
dist_m.addmm_(1, -2, x, y.t())
return dist_m.numpy()
def select_merge_data(u_feas, label, label_to_images, ratio_n, dists,rgb_num,ir_num):
dists = torch.from_numpy(dists)
# homo_mask = torch.zeros(len(u_feas), len(u_feas))
# homo_mask[:rgb_num,:rgb_num] = 9900000 #100000
# homo_mask[rgb_num:,rgb_num:] = 9900000
# homo_mask[rgb_num:,:rgb_num] = 9900000
print(dists.size())
# dists.add_(torch.tril(900000 * torch.ones(len(u_feas), len(u_feas))))
# print(dists.size())
# dists.add_(homo_mask)
# cnt = torch.FloatTensor([ len(label_to_images[label[idx]]) for idx in range(len(u_feas))])
# dists += ratio_n * (cnt.view(1, len(cnt)) + cnt.view(len(cnt), 1))
# for idx in range(len(u_feas)):
# for j in range(idx + 1, len(u_feas)):
# if label[idx] == label[j]:
# dists[idx, j] = 900000
# print('rgb_num',rgb_num)
# print('ir_num',ir_num)
dists = dists.numpy()
# dists=dists[:rgb_num,rgb_num:]
ind = np.unravel_index(np.argsort(dists, axis=None)[::-1], dists.shape) #np.argsort(dists, axis=1)#
idx1 = ind[0]
idx2 = ind[1]
dist_list = dists[idx1,idx2] #[dists[i,j] for i,j in zip(idx1,idx2)]
# print(ind.shape)
# print(ind)
return idx1, idx2, dist_list
def select_merge_data_jacard(u_feas, label, label_to_images, ratio_n, dists,rgb_num,ir_num):
dists = torch.from_numpy(dists)
print(dists.size())
dists = dists.numpy()
ind = np.unravel_index(np.argsort(dists, axis=None), dists.shape)
idx1 = ind[0]
idx2 = ind[1]
dist_list = dists[idx1,idx2]
return idx1, idx2, dist_list
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(
self,
optimizer,
milestones,
gamma=0.1,
warmup_factor=1.0 / 3,
warmup_iters=500,
warmup_method="linear",
last_epoch=-1,
):
if not list(milestones) == sorted(milestones):
raise ValueError(
"Milestones should be a list of" " increasing integers. Got {}",
milestones,
)
if warmup_method not in ("constant", "linear"):
raise ValueError(
"Only 'constant' or 'linear' warmup_method accepted"
"got {}".format(warmup_method)
)
self.milestones = milestones
self.gamma = gamma
self.warmup_factor = warmup_factor
self.warmup_iters = warmup_iters
self.warmup_method = warmup_method
super(WarmupMultiStepLR, self).__init__(optimizer, last_epoch)
def get_lr(self):
warmup_factor = 1
if self.last_epoch < self.warmup_iters:
if self.warmup_method == "constant":
warmup_factor = self.warmup_factor
elif self.warmup_method == "linear":
alpha = float(self.last_epoch) / float(self.warmup_iters)
warmup_factor = self.warmup_factor * (1 - alpha) + alpha
return [
base_lr
* warmup_factor
* self.gamma ** bisect_right(self.milestones, self.last_epoch)
for base_lr in self.base_lrs
]
def camera(cams,features,labels):
cf = features
intra_id_features = []
intra_id_labels = []
for cc in np.unique(cams):
percam_ind = np.where(cams == cc)[0]
percam_feature = cf[percam_ind].numpy()
percam_label = labels[percam_ind]
percam_class_num = len(np.unique(percam_label[percam_label >= 0]))
percam_id_feature = np.zeros((percam_class_num, percam_feature.shape[1]), dtype=np.float32)
cnt = 0
for lbl in np.unique(percam_label):
if lbl >= 0:
ind = np.where(percam_label == lbl)[0]
id_feat = np.mean(percam_feature[ind], axis=0)
percam_id_feature[cnt, :] = id_feat
intra_id_labels.append(lbl)
cnt += 1
percam_id_feature = percam_id_feature / np.linalg.norm(percam_id_feature, axis=1, keepdims=True)
intra_id_features.append(torch.from_numpy(percam_id_feature))
return intra_id_features, intra_id_labels
def pairwise_distance_matcher(matcher, prob_fea, gal_fea, gal_batch_size=4, prob_batch_size=4096):
with torch.no_grad():
num_gals = gal_fea.size(0)
num_probs = prob_fea.size(0)
score = torch.zeros(num_probs, num_gals, device=prob_fea.device)
score_2 = torch.zeros(num_probs, num_gals, device=prob_fea.device)
matcher.eval()
for i in range(0, num_probs, prob_batch_size):
j = min(i + prob_batch_size, num_probs)
# matcher.make_kernel(prob_fea[i: j, :].cuda())
# matcher.make_kernel(prob_fea[i: j, :, :, :].cuda())
for k in range(0, num_gals, gal_batch_size):
k2 = min(k + gal_batch_size, num_gals)
score[i: j, k: k2],score_2[i: j, k: k2] = matcher(prob_fea[i: j, :].cuda(),gal_fea[k: k2, :].cuda())
# print(score[i: j, k: k2])
# print(torch.sigmoid(score[i: j, k: k2]/10 ))
# scale matching scores to make them visually more recognizable
# score = torch.sigmoid(score/10 )#F.softmax(torch.sigmoid(score / 10),dim=1)
return score.cpu(), score_2.cpu() # [p, g]
# score = torch.sigmoid(score / 10)
# return (1. - score).cpu()
def pairwise_part(prob_fea, gal_fea,percam_memory_all, gal_batch_size=4, prob_batch_size=4096):
num_gals = gal_fea.size(0)
num_probs = prob_fea.size(0)
score = torch.zeros(num_probs, num_gals, device=prob_fea.device)
for i in range(0, num_probs, prob_batch_size):
j = min(i + prob_batch_size, num_probs)
# matcher.make_kernel(prob_fea[i: j, :].cuda())
# matcher.make_kernel(prob_fea[i: j, :, :, :].cuda())
for k in range(0, num_gals, gal_batch_size):
k2 = min(k + gal_batch_size, num_gals)
score[i: j, k: k2],score_2[i: j, k: k2] = matcher(prob_fea[i: j, :].cuda(),gal_fea[k: k2, :].cuda())
return score.cpu()
def part_sim(query_t, key_m):
seq_len=part
q, d_5 = query_t.size() # b d*5,
k, d_5 = key_m.size()
z= int(d_5/seq_len)
d = int(d_5/seq_len)
# query_t = query_t.detach().view(q, -1, z)#self.bn3(tgt.view(q, -1, z)) #B N C
# key_m = key_m.detach().view(k, -1, d)#self.bn3(memory.view(k, -1, d)) #B N C
query_t = F.normalize(query_t.view(q, -1, z), dim=-1) #B N C tgt.view(q, -1, z)#
key_m = F.normalize(key_m.view(k, -1, d), dim=-1) #Q N C memory.view(k, -1, d)#
# score = einsum('q t d, k s d -> q k s t', query_t, key_m)#F.softmax(einsum('q t d, k s d -> q k s t', query_t, key_m),dim=-1).view(q,-1) # B Q N N
score = einsum('q t d, k s d -> q k t s', query_t, key_m)
score = torch.cat((score.max(dim=2)[0], score.max(dim=3)[0]), dim=-1) #####score.max(dim=3)[0]#q k 10
score = F.softmax(score.permute(0,2,1)/0.01,dim=-1).reshape(q,-1)
return score
def init_camera_proxy(all_img_cams,all_pseudo_label,intra_id_features):
all_img_cams = torch.tensor(all_img_cams).cuda()
unique_cams = torch.unique(all_img_cams)
# print(self.unique_cams)
all_pseudo_label = torch.tensor(all_pseudo_label).cuda()
init_intra_id_feat = intra_id_features
# print(len(self.init_intra_id_feat))
# initialize proxy memory
percam_memory = []
memory_class_mapper = []
concate_intra_class = []
for cc in unique_cams:
percam_ind = torch.nonzero(all_img_cams == cc).squeeze(-1)
uniq_class = torch.unique(all_pseudo_label[percam_ind])
uniq_class = uniq_class[uniq_class >= 0]
concate_intra_class.append(uniq_class)
cls_mapper = {int(uniq_class[j]): j for j in range(len(uniq_class))}
memory_class_mapper.append(cls_mapper) # from pseudo label to index under each camera
if len(init_intra_id_feat) > 0:
# print('initializing ID memory from updated embedding features...')
proto_memory = init_intra_id_feat[cc]
proto_memory = proto_memory.cuda()
percam_memory.append(proto_memory.detach())
print(cc,proto_memory.size())
concate_intra_class = torch.cat(concate_intra_class)
percam_tempV = []
for ii in unique_cams:
percam_tempV.append(percam_memory[ii].detach().clone())
percam_tempV_ = torch.cat(percam_tempV, dim=0).cuda()
return concate_intra_class,percam_tempV_,percam_memory#memory_class_mapper,
def save_checkpoint_match(state, is_best, fpath='checkpoint.pth.tar',match=''):
mkdir_if_missing(osp.dirname(fpath))
torch.save(state, fpath)
if is_best:
shutil.copy(fpath, osp.join(osp.dirname(fpath), match+'match_best.pkl'))
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1. / self.power)
out = x.div(norm)
return out
def select_merge_data(dists):
dists = torch.from_numpy(dists)
print(dists.size())
dists = dists.numpy()
ind = np.unravel_index(np.argsort(dists, axis=None)[::-1], dists.shape) #np.argsort(dists, axis=1)#
idx1 = ind[0]
idx2 = ind[1]
dist_list = dists[idx1,idx2]
return idx1, idx2, dist_list
def compute_cross_agreement(features_g, features_p, k, search_option=3):
print("Compute cross agreement score...")
N, D = features_p.size()
score = torch.FloatTensor()
end = time.time()
ranked_list_g = compute_ranked_list(features_g, k=k, search_option=search_option, verbose=False)
# for i in range(P):
ranked_list_p_i = compute_ranked_list(features_p, k=k, search_option=search_option, verbose=False)
intersect_i = torch.FloatTensor(
[len(np.intersect1d(ranked_list_g[j], ranked_list_p_i[j])) for j in range(N)])
union_i = torch.FloatTensor(
[len(np.union1d(ranked_list_g[j], ranked_list_p_i[j])) for j in range(N)])
score_i = intersect_i / union_i
# score_i = score_i.unsqueeze(1)
print(score_i.size())
# score = torch.cat([score, score_i.unsqueeze(1)], dim=1)
print("Cross agreement score time cost: {}".format(time.time() - end))
return score_i
def compute_cross_agreement_cm(features_g, features_p,features_g_s, features_p_s, k, search_option=3):
print("CM Compute cross agreement score...")
N, D = features_g.size()
M, D = features_p.size()
score = torch.FloatTensor()
end = time.time()
# feat_all = torch.cat((features_g,features_p),dim=0)
ranked_list_g_p = compute_ranked_list_cm(features_g,features_p, k=k, search_option=search_option, verbose=False)
# ranked_list_g_p=ranked_list_g[:N,N:]
# ranked_list_p_g=ranked_list_g[N:,:N]
# feat_all_s = torch.cat((features_g_s,features_p_s),dim=0)
ranked_list_g_p_s = compute_ranked_list_cm(features_g_s,features_p_s, k=k, search_option=search_option, verbose=False)
# ranked_list_g_p_s=ranked_list_g_s[:N,N:]
# ranked_list_p_g_s=ranked_list_g_s[N:,:N]
ranked_list_p_g = compute_ranked_list_cm(features_p,features_g, k=k, search_option=search_option, verbose=False)
# ranked_list_g_p=ranked_list_g[:N,N:]
# ranked_list_p_g=ranked_list_g[N:,:N]
# feat_all_s = torch.cat((features_g_s,features_p_s),dim=0)
ranked_list_p_g_s = compute_ranked_list_cm(features_p_s,features_g_s, k=k, search_option=search_option, verbose=False)
# ranked_list_g_p_s=ranked_list_g_s[:N,N:]
# ranked_list_p_g_s=ranked_list_g_s[N:,:N]
intersect_i = torch.FloatTensor(
[len(np.intersect1d(ranked_list_g_p[j], ranked_list_g_p_s[j])) for j in range(N)])
union_i = torch.FloatTensor(
[len(np.union1d(ranked_list_g_p[j], ranked_list_g_p_s[j])) for j in range(N)])
score_i = intersect_i / union_i
intersect_i_1 = torch.FloatTensor(
[len(np.intersect1d(ranked_list_p_g[j], ranked_list_p_g_s[j])) for j in range(M)])
union_i_1 = torch.FloatTensor(
[len(np.union1d(ranked_list_p_g[j], ranked_list_p_g_s[j])) for j in range(M)])
score_i_1 = intersect_i_1 / (union_i_1)
# score_i = score_i.unsqueeze(1)
# score = torch.cat([score, score_i.unsqueeze(1)], dim=1)
print("Cross agreement score time cost: {}".format(time.time() - end))
return score_i,score_i_1
def main():
args = parser.parse_args()
if args.config_file != "":
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
if args.seed is not None:
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
# main_worker(args,cfg)
log_s1_name = 'sysu_train'
test(args,log_s1_name) #add CMA
def test(args,log_s1_name):
# def main_worker_stage2(args,log_s1_name):
# def main_worker(args,cfg):
l2norm = Normalize(2)
ir_batch=180
rgb_batch=128
global start_epoch, best_mAP
args.logs_dir = osp.join('logs'+'/'+log_s1_name)
# args.logs_dir = osp.join(args.logs_dir+'/'+log_name)
start_time = time.monotonic()
cudnn.benchmark = True
sys.stdout = Logger(osp.join(args.logs_dir, 'test_log.txt'))
print("==========\nArgs:{}\n==========".format(args))
print("Loaded configuration file {}".format(args.config_file))
with open(args.config_file, 'r') as cf:
config_str = "\n" + cf.read()
print(config_str)
# Create datasets
iters = args.iters if (args.iters > 0) else None
print("==> Load unlabeled dataset")
# dataset_ir = get_data('sysu_ir', args.data_dir)
# dataset_rgb = get_data('sysu_rgb', args.data_dir)
# Create model
# model = create_model(args)
model = make_model(cfg, num_class=0, camera_num=0, view_num = 0)
model.cuda()
model = nn.DataParallel(model)#,output_device=1)
params = [{"params": [value]} for _, value in model.named_parameters() if value.requires_grad]
optimizer = torch.optim.SGD(params, lr=args.lr, momentum=0.9, weight_decay=args.weight_decay)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=0.1)
args.test_batch=128
args.img_w=args.width
args.img_h=args.height
# color_aug_ir = T.ColorJitter(brightness=0.7, contrast=0.7, saturation=0.7, hue=0.5)#T.
normalizer = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
height=args.height
width=args.width
transform_test = T.Compose([
T.ToPILImage(),
T.Resize((args.img_h,args.img_w)),
T.ToTensor(),
normalizer,
])
print('==> Test with the best model:')
checkpoint = load_checkpoint(osp.join(args.logs_dir, 'model_best.pth.tar'))
model.load_state_dict(checkpoint['state_dict'])
# _,mAP_homo = evaluator.evaluate(test_loader_ir, dataset_ir.query, dataset_ir.gallery, cmc_flag=True,modal=2)
# _,mAP_homo = evaluator.evaluate(test_loader_rgb, dataset_rgb.query, dataset_rgb.gallery, cmc_flag=True,modal=1)
mode='all'
data_path='/home/yangbin/scratch/data/sysu'
query_img, query_label, query_cam = process_query_sysu(data_path, mode=mode)
nquery = len(query_label)
queryset = TestData(query_img, query_label, transform=transform_test, img_size=(args.img_w, args.img_h))
query_loader = data.DataLoader(queryset, batch_size=args.test_batch, shuffle=False, num_workers=4)
query_feat_fc = extract_query_feat(model,query_loader,nquery)
for trial in range(10):
gall_img, gall_label, gall_cam = process_gallery_sysu(data_path, mode=mode, trial=trial)
ngall = len(gall_label)
trial_gallset = TestData(gall_img, gall_label, transform=transform_test, img_size=(args.img_w, args.img_h))
trial_gall_loader = data.DataLoader(trial_gallset, batch_size=args.test_batch, shuffle=False, num_workers=4)
gall_feat_fc = extract_gall_feat(model,trial_gall_loader,ngall)
# fc feature
distmat = np.matmul(query_feat_fc, np.transpose(gall_feat_fc))
cmc, mAP, mINP = eval_sysu(-distmat, query_label, gall_label, query_cam, gall_cam)
if trial == 0:
all_cmc = cmc
all_mAP = mAP
all_mINP = mINP
else:
all_cmc = all_cmc + cmc
all_mAP = all_mAP + mAP
all_mINP = all_mINP + mINP
print('Test Trial: {}'.format(trial))
print(
'FC: Rank-1: {:.2%} | Rank-5: {:.2%} | Rank-10: {:.2%}| Rank-20: {:.2%}| mAP: {:.2%}| mINP: {:.2%}'.format(
cmc[0], cmc[4], cmc[9], cmc[19], mAP, mINP))
cmc = all_cmc / 10
mAP = all_mAP / 10
mINP = all_mINP / 10
print('all search All Average:')
print('FC: Rank-1: {:.2%} | Rank-5: {:.2%} | Rank-10: {:.2%}| Rank-20: {:.2%}| mAP: {:.2%}| mINP: {:.2%}'.format(
cmc[0], cmc[4], cmc[9], cmc[19], mAP, mINP))
mode='indoor'
query_img, query_label, query_cam = process_query_sysu(data_path, mode=mode)
nquery = len(query_label)
queryset = TestData(query_img, query_label, transform=transform_test, img_size=(args.img_w, args.img_h))
query_loader = data.DataLoader(queryset, batch_size=args.test_batch, shuffle=False, num_workers=4)
query_feat_fc = extract_query_feat(model,query_loader,nquery)
for trial in range(10):
gall_img, gall_label, gall_cam = process_gallery_sysu(data_path, mode=mode, trial=trial)
ngall = len(gall_label)
trial_gallset = TestData(gall_img, gall_label, transform=transform_test, img_size=(args.img_w, args.img_h))
trial_gall_loader = data.DataLoader(trial_gallset, batch_size=args.test_batch, shuffle=False, num_workers=4)
gall_feat_fc = extract_gall_feat(model,trial_gall_loader,ngall)
# fc feature
distmat = np.matmul(query_feat_fc, np.transpose(gall_feat_fc))
cmc, mAP, mINP = eval_sysu(-distmat, query_label, gall_label, query_cam, gall_cam)
if trial == 0:
all_cmc = cmc
all_mAP = mAP
all_mINP = mINP
else:
all_cmc = all_cmc + cmc
all_mAP = all_mAP + mAP
all_mINP = all_mINP + mINP
print('Test Trial: {}'.format(trial))
print(
'FC: Rank-1: {:.2%} | Rank-5: {:.2%} | Rank-10: {:.2%}| Rank-20: {:.2%}| mAP: {:.2%}| mINP: {:.2%}'.format(
cmc[0], cmc[4], cmc[9], cmc[19], mAP, mINP))
cmc = all_cmc / 10
mAP = all_mAP / 10
mINP = all_mINP / 10
print('indoor All Average:')
print('FC: Rank-1: {:.2%} | Rank-5: {:.2%} | Rank-10: {:.2%}| Rank-20: {:.2%}| mAP: {:.2%}| mINP: {:.2%}'.format(
cmc[0], cmc[4], cmc[9], cmc[19], mAP, mINP))
#################################
# is_best = (mAP > best_mAP)
# best_mAP = max(mAP, best_mAP)
# save_checkpoint({
# 'state_dict': model.state_dict(),
# 'epoch': epoch + 1,
# 'best_mAP': best_mAP,
# }, is_best, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar'))
# print('\n * Finished epoch {:3d} model mAP: {:5.1%} best: {:5.1%}{}\n'.
# format(epoch, mAP, best_mAP, ' *' if is_best else ''))
end_time = time.monotonic()
print('Total running time: ', timedelta(seconds=end_time - start_time))
def main_worker_stage1(args,log_s1_name,log_s2_name):
# def main_worker_stage2(args,log_s1_name):
# def main_worker(args,cfg):
l2norm = Normalize(2)
ir_batch=180
rgb_batch=128
global start_epoch, best_mAP
# log_name='sysu_2p_288_5glpart_10cps_cmav2_v100' # _0.8cmrefinehthm0
# log_name='sysu_2p_288_5glpart_confusionwrtv1_cmav3_a100' # _0.8cmrefinehthm0
# log_name='sysu_2p_288_3lpart_cmav2_s23_a100' # _0.8cmrefinehthm0
# log_name='sysu_2p_288_5glpartgem_cmav2_s23_a100'
# log_name='sysu_2p_384_5glpartv2_cmpl_7camcmav1_10cmav1_15cmcmav2_a100'
args.logs_dir = osp.join('logs'+'/'+log_s2_name)
# args.logs_dir = osp.join(args.logs_dir+'/'+log_name)
start_time = time.monotonic()
cudnn.benchmark = True
sys.stdout = Logger(osp.join(args.logs_dir, 'log.txt'))
print("==========\nArgs:{}\n==========".format(args))
print("Loaded configuration file {}".format(args.config_file))
with open(args.config_file, 'r') as cf:
config_str = "\n" + cf.read()
print(config_str)
# Create datasets
iters = args.iters if (args.iters > 0) else None
print("==> Load unlabeled dataset")
dataset_ir = get_data('sysu_ir', args.data_dir)
dataset_rgb = get_data('sysu_rgb', args.data_dir)
test_loader_ir = get_test_loader(dataset_ir, args.height, args.width, args.batch_size, args.workers)
test_loader_rgb = get_test_loader(dataset_rgb, args.height, args.width, args.batch_size, args.workers)
# Create model
# model = create_model(args)
model = make_model(cfg, num_class=0, camera_num=0, view_num = 0)
model.cuda()
model = nn.DataParallel(model)#,output_device=1)
trainer_intrac = ClusterContrastTrainer_pretrain_joint(model)
trainer = ClusterContrastTrainer_pretrain_camera_confusionrefine(model)
trainer.cmlabel=3000#30#30#1000
trainer_interm = ClusterContrastTrainer_pretrain_camera_wise_3_cmrefine(model)
cam_cma = 10#10
trainer.hm = 0#20
trainer.ht = 0#20
# s3_cma = 30