-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathregdb_test.py
793 lines (682 loc) · 31.7 KB
/
regdb_test.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
# -*- 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 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 clustercontrast import datasets
from clustercontrast import models
from clustercontrast.models.cm import ClusterMemory
# from clustercontrast.trainers import ClusterContrastTrainer,ClusterContrastTrainer_pretrain,ClusterContrastTrainer_pretrain_joint,ClusterContrastTrainer_pretrain_joint_consistence
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
from clustercontrast.utils.data.sampler import RandomMultipleGallerySampler, RandomMultipleGallerySamplerNoCam
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
start_epoch = best_mAP = 0
def get_data(name, data_dir,trial=0):
root = osp.join(data_dir, name)
dataset = datasets.create(name, root,trial=trial)
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 = 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 = 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
def main():
args = parser.parse_args()
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)
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 extract_gall_feat(model,gall_loader,ngall):
# pool_dim=2048
# model.eval()
# print ('Extracting Gallery Feature...')
# start = time.time()
# ptr = 0
# 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)
# input = Variable(input.cuda())
# feat_fc = model(input)
# gall_feat_fc[ptr:ptr+batch_num,: ] = feat_fc.detach().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=2048
# model.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)
# input = Variable(input.cuda())
# feat_fc = model(input)
# query_feat_fc[ptr:ptr+batch_num,: ] = feat_fc.detach().cpu().numpy()
# ptr = ptr + batch_num
# print('Extracting Time:\t {:.3f}'.format(time.time()-start))
# return query_feat_fc
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=2048
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 = net( input,input, 2)
flip_input = Variable(flip_input.cuda())
feat_fc_1 = net( flip_input,flip_input, 2)
feature_fc = (feat_fc.detach() + feat_fc_1.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))
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=2048
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 = net( input, input,1)
flip_input = Variable(flip_input.cuda())
feat_fc_1 = net( flip_input,flip_input, 1)
feature_fc = (feat_fc.detach() + feat_fc_1.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))
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)
# 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), 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 process_test_regdb(img_dir, trial = 1, modal = 'visible'):
if modal=='visible':
input_data_path = img_dir + 'idx/test_visible_{}'.format(trial) + '.txt'
elif modal=='thermal':
input_data_path = img_dir + 'idx/test_thermal_{}'.format(trial) + '.txt'
with open(input_data_path) as f:
data_file_list = open(input_data_path, 'rt').read().splitlines()
# Get full list of image and labels
file_image = [img_dir + '/' + s.split(' ')[0] for s in data_file_list]
file_label = [int(s.split(' ')[1]) for s in data_file_list]
return file_image, np.array(file_label)
def eval_regdb(distmat, q_pids, g_pids, max_rank = 20):
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)
matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32)
# compute cmc curve for each query
all_cmc = []
all_AP = []
all_INP = []
num_valid_q = 0. # number of valid query
# only two cameras
q_camids = np.ones(num_q).astype(np.int32)
g_camids = 2* np.ones(num_g).astype(np.int32)
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 = (g_pids[order] == q_pid) & (g_camids[order] == q_camid)
keep = np.invert(remove)
# compute cmc curve
raw_cmc = matches[q_idx][keep] # binary vector, positions with value 1 are correct matches
if not np.any(raw_cmc):
# this condition is true when query identity does not appear in gallery
continue
cmc = raw_cmc.cumsum()
# compute mINP
# refernece Deep Learning for Person Re-identification: A Survey and Outlook
pos_idx = np.where(raw_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 = raw_cmc.sum()
tmp_cmc = raw_cmc.cumsum()
tmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)]
tmp_cmc = np.asarray(tmp_cmc) * raw_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
mAP = np.mean(all_AP)
mINP = np.mean(all_INP)
return all_cmc, mAP, mINP
def main_worker(args):
for trial in range(1,11):#(1,11):
args.test_batch=64
args.img_w=args.width
args.img_h=args.height
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform_test = T.Compose([
T.ToPILImage(),
T.Resize((args.img_h,args.img_w)),
T.ToTensor(),
normalize,
])
# logs_dir_root = osp.join(args.logs_dir+'/'+args.dataset+"_resnet_pretrain_s1_0.3_s2_0.3_s3_0.3_s2t20_s3t20v3_finetune_s2_lpv3_with20smstru20_ca_nocolorjitter_nocameraloss_2stage")
logs_dir_root = osp.join(args.logs_dir+'/'+'regdb_val')#args.dataset+"_resnet_mape_clu")
# args.logs_dir = osp.join(logs_dir_root,str(trial))
print('==> Test with the best model:')
model = create_model(args)
# checkpoint = load_checkpoint(osp.join(logs_dir_root+'/'+str(trial), 'model_best.pth.tar'))
trial_fix=trial
checkpoint = load_checkpoint(osp.join(logs_dir_root+'/'+str(trial_fix), 'model_best.pth.tar'))
size_ir = checkpoint['state_dict']['module.classifier_ir.weight'].size(0)
size_rgb = checkpoint['state_dict']['module.classifier_rgb.weight'].size(0)
model.module.classifier_ir = nn.Linear(2048, size_ir, bias=False).cuda()
model.module.classifier_rgb = nn.Linear(2048, size_rgb, bias=False).cuda()
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='visible to thermal'
print(mode)
data_path='/dat01/chenjun3/data/RegDB/'
query_img, query_label = process_test_regdb(data_path, trial=trial, modal='visible')
gall_img, gall_label = process_test_regdb(data_path, trial=trial, modal='thermal')
gallset = TestData(gall_img, gall_label, transform=transform_test, img_size=(args.img_w, args.img_h))
gall_loader = data.DataLoader(gallset, batch_size=args.test_batch, shuffle=False, num_workers=args.workers)
nquery = len(query_label)
ngall = len(gall_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(1):
ngall = len(gall_label)
gall_feat_fc = extract_gall_feat(model,gall_loader,ngall)
# fc feature
distmat = np.matmul(query_feat_fc, np.transpose(gall_feat_fc))
cmc, mAP, mINP = eval_regdb(-distmat, query_label, gall_label)
if trial == 1:
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 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))
#################################
for trial in range(1,11):
args.test_batch=64
args.img_w=args.width
args.img_h=args.height
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform_test = T.Compose([
T.ToPILImage(),
T.Resize((args.img_h,args.img_w)),
T.ToTensor(),
normalize,
])
# logs_dir_root = osp.join(args.logs_dir+'/'+args.dataset+"_resnet_pretrain_s1_0.3_s2_0.3_s3_0.3_s2t20_s3t20v3_finetune_s2_lpv3_with20smstru20_nocameraloss")
# args.logs_dir = osp.join(logs_dir_root,str(trial))
print('==> Test with the best model:')
model = create_model(args)
# checkpoint = load_checkpoint(osp.join(logs_dir_root+'/'+str(trial), 'model_best.pth.tar'))
trial_fix=trial
checkpoint = load_checkpoint(osp.join(logs_dir_root+'/'+str(trial_fix), 'model_best.pth.tar'))
size_ir = checkpoint['state_dict']['module.classifier_ir.weight'].size(0)
size_rgb = checkpoint['state_dict']['module.classifier_rgb.weight'].size(0)
model.module.classifier_ir = nn.Linear(2048, size_ir, bias=False).cuda()
model.module.classifier_rgb = nn.Linear(2048, size_rgb, bias=False).cuda()
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='thermal to visible'
print(mode)
data_path='/dat01/chenjun3/data/RegDB/'
query_img, query_label = process_test_regdb(data_path, trial=trial, modal='thermal')
gall_img, gall_label = process_test_regdb(data_path, trial=trial, modal='visible')
gallset = TestData(gall_img, gall_label, transform=transform_test, img_size=(args.img_w, args.img_h))
gall_loader = data.DataLoader(gallset, batch_size=args.test_batch, shuffle=False, num_workers=args.workers)
nquery = len(query_label)
ngall = len(gall_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_gall_feat(model,query_loader,nquery)
# for trial in range(1):
ngall = len(gall_label)
gall_feat_fc = extract_query_feat(model,gall_loader,ngall)
# fc feature
distmat = np.matmul(query_feat_fc, np.transpose(gall_feat_fc))
cmc, mAP, mINP = eval_regdb(-distmat, query_label, gall_label)
if trial == 1:
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 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))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Self-paced contrastive learning on unsupervised re-ID")
# data
parser.add_argument('-d', '--dataset', type=str, default='dukemtmcreid',
choices=datasets.names())
parser.add_argument('-b', '--batch-size', type=int, default=2)
parser.add_argument('-j', '--workers', type=int, default=8)
parser.add_argument('--height', type=int, default=288, help="input height")
parser.add_argument('--width', type=int, default=144, help="input width")
parser.add_argument('--num-instances', type=int, default=4,
help="each minibatch consist of "
"(batch_size // num_instances) identities, and "
"each identity has num_instances instances, "
"default: 0 (NOT USE)")
# cluster
parser.add_argument('--eps', type=float, default=0.6,
help="max neighbor distance for DBSCAN")
parser.add_argument('--eps-gap', type=float, default=0.02,
help="multi-scale criterion for measuring cluster reliability")
parser.add_argument('--k1', type=int, default=30,
help="hyperparameter for jaccard distance")
parser.add_argument('--k2', type=int, default=6,
help="hyperparameter for jaccard distance")
# model
parser.add_argument('-a', '--arch', type=str, default='resnet50',
choices=models.names())
parser.add_argument('--features', type=int, default=0)
parser.add_argument('--dropout', type=float, default=0)
parser.add_argument('--momentum', type=float, default=0.2,
help="update momentum for the hybrid memory")
# optimizer
parser.add_argument('--lr', type=float, default=0.00035,
help="learning rate")
parser.add_argument('--weight-decay', type=float, default=5e-4)
parser.add_argument('--epochs', type=int, default=50)
parser.add_argument('--iters', type=int, default=400)
parser.add_argument('--step-size', type=int, default=20)
# training configs
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--print-freq', type=int, default=10)
parser.add_argument('--eval-step', type=int, default=1)
parser.add_argument('--temp', type=float, default=0.05,
help="temperature for scaling contrastive loss")
# path
working_dir = osp.dirname(osp.abspath(__file__))
parser.add_argument('--data-dir', type=str, metavar='PATH',
default=osp.join(working_dir, 'data'))
parser.add_argument('--logs-dir', type=str, metavar='PATH',
default=osp.join(working_dir, 'logs'))
parser.add_argument('--pooling-type', type=str, default='gem')
parser.add_argument('--use-hard', action="store_true")
parser.add_argument('--no-cam', action="store_true")
main()