-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetrics.py
2406 lines (1874 loc) · 94.1 KB
/
metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import subprocess
import json
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import wandb
from models.gcn.gcn import GCN
import utils.flowlib as fl
from hungarian_algorithm.hungarian import Hungarian, HungarianError
class Metrics(object):
def __init__(self, *args, **kwargs):
"""
Compute accuracy metrics from this Metrics class
Args:
acc_metric (String): String used to indicate selected accuracy metric
Return:
None
"""
self.metric_type = kwargs['acc_metric']
if self.metric_type == 'Accuracy':
self.metric_object = Accuracy(*args, **kwargs)
elif self.metric_type == 'pck_curve_hand':
self.metric_object = PCK_Curve_Hand(*args, **kwargs)
elif self.metric_type == 'PCK_FlowTrack':
self.metric_object = PCK_FlowTrack(*args, **kwargs)
elif self.metric_type == 'Contrastive_Accuracy':
self.metric_object = Contrastive_Accuracy(*args, **kwargs)
elif self.metric_type == 'Save_Video_Keypoints':
self.metric_object = Save_Video_Keypoints(*args, **kwargs)
elif self.metric_type == 'Save_Frame_Video_Heatmaps':
self.metric_object = Save_Frame_Video_Heatmaps(*args, **kwargs)
elif self.metric_type == 'Eval_PoseTrack18_det':
self.metric_object = Eval_PoseTrack18_det(*args, **kwargs)
elif self.metric_type == 'Eval_PoseTrack17_det':
self.metric_object = Eval_PoseTrack17_det(*args, **kwargs)
else:
self.metric_type = None
def get_accuracy(self, predictions, targets, **kwargs):
"""
Return accuracy from selected metric type
Args:
predictions: model predictions
targets: ground truth or targets
"""
if self.metric_type == None:
return -1
else:
return self.metric_object.get_accuracy(predictions, targets, **kwargs)
class Accuracy(object):
"""
Standard accuracy computation. # of correct cases/# of total cases
"""
def __init__(self, *args, **kwargs):
self.ndata = kwargs['ndata']
self.count = 0
self.correct = 0.
self.total = 0.
def get_accuracy(self, predictions, data):
"""
Args:
predictions (Tensor, shape [N,*])
data (dictionary):
- labels (Tensor, shape [N,*])
Return:
Accuracy # of correct case/ # of total cases
"""
targets = data['labels']
assert (predictions.shape[0] == targets.shape[0])
if self.count >= self.ndata:
self.count = 0
self.correct = 0
self.total = 0
targets = targets.detach().cpu().numpy()
predictions = predictions.detach().cpu().numpy()
if len(targets.shape) == 2 and len(predictions.shape) == 2:
self.correct += np.sum(np.argmax(predictions,1) == targets[:, -1])
self.total += predictions.shape[0]
else:
self.correct += np.sum(np.argmax(predictions,1) == targets[:, -1])
self.total += predictions.shape[0]
# END IF
self.count += predictions.shape[0]
return self.correct/self.total
class IOU():
"""
Intersection-over-union between one prediction bounding box
and plausible ground truth bounding boxes
"""
def __init__(self, *args, **kwargs):
pass
def intersect(self, box_p, box_t):
"""
Intersection area between predicted bounding box and
all ground truth bounding boxes
Args:
box_p (Tensor, shape [4]): prediction bounding box, coordinate format [x1, y1, x2, y2]
box_t (Tensor, shape [N,4]): target bounding boxes
Return:
intersect area (Tensor, shape [N]): intersect_area for all target bounding boxes
"""
x_left = torch.max(box_p[0], box_t[:,0])
y_top = torch.max(box_p[1], box_t[:,1])
x_right = torch.min(box_p[2], box_t[:,2])
y_bottom = torch.min(box_p[3], box_t[:,3])
width = torch.clamp(x_right - x_left, min=0)
height = torch.clamp(y_bottom - y_top, min=0)
intersect_area = width * height
return intersect_area
def iou(self, box_p, box_t):
"""
Performs intersection-over-union
Args:
box_p (Tensor, shape [4]): prediction bounding box, coordinate format [x1, y1, x2, y2]
box_t (Tensor, shape [N,4]): target bounding boxes
Return:
overlap (Tensor, shape [1]): max overlap
ind (Tensor, shape [1]): index of bounding box with largest overlap
"""
intersect_area = self.intersect(box_p, box_t)
box_p_area = (box_p[2] - box_p[0]) * (box_p[3] - box_p[1])
box_t_area = (box_t[:,2] - box_t[:,0]) * (box_t[:,3] - box_t[:,1])
union = box_p_area + box_t_area - intersect_area
#NOTE: Make sure to remove this line. It's only to get around area of single keypoints, for now
union = torch.clamp(union, min=0.001)
overlap = torch.max(intersect_area/union)
ind = torch.argmax(intersect_area/union)
assert overlap >= 0.0
assert overlap <= 1.0
return overlap, ind
def get_accuracy(self, prediction, targets):
"""
Args:
prediction (Tensor, shape [4]): prediction bounding box, coordinate format [x1, y1, x2, y2]
targets (Tensor, shape [N,4]): target bounding boxes
Return:
iou (Tensor, shape[1]): Highest iou amongst target bounding boxes
ind (Tensor, shape[1]): Index of target bounding box with highest score
"""
iou_score, ind = self.iou(prediction, targets)
return iou_score, ind
class PCK_Curve_Hand():
def __init__(self, threshold=torch.linspace(0,1,101),**kwargs):
#def __init__(self, threshold=torch.Tensor([0.5]),**kwargs):
""""
Probability of Correct Keypoint (PCK) evaluation metric for OpenPose hand model
Args:
threshold (Tensor, shape [11]): normalized distance thresholds
ndata (scalar): total number of datapoints in dataset
Returns:
None
"""
self.threshold = threshold
self.acc = torch.zeros(len(self.threshold), 21)
self.viz = kwargs['viz']
self.ndata = kwargs['ndata']
self.nbatch = np.ceil(self.ndata/kwargs['batch_size']).astype(np.int)
self.count = 0
self.logger = kwargs['logger'] #logging tool
self.debug = kwargs['debug']
def get_accuracy(self, predictions, data):
"""
Args:
predictions:
data
"""
if self.count == self.nbatch: #reset accuracy each epoch
self.count = 0
self.acc = torch.zeros(len(self.threshold), 21)
W,H = data['frame_size']
hand_pts = data['key_pts']
occluded = data['occ']
padding = data['padding']
input_crop = data.get('input_crop', data['bbox'])
if 'head_size' in data:
#head_size = data['head_size'].float() / H.float() * 368
head_size = data['head_size'].float()
dist_thresh = 0.7 * head_size.unsqueeze(1) * self.threshold.repeat(len(head_size),1) #Distance threshold is normalized to 0.7*head_size
else:
#if no given head size, then normalize to longest side of bounding box
bbox = data['bbox']
bbox_size = torch.max(bbox[...,2]-bbox[...,0], bbox[...,3]-bbox[...,1])
dist_thresh = bbox_size * self.threshold.repeat(len(bbox_size),1) #Distance threshold is normalized to longest side of bounding box
if isinstance(predictions, tuple):
_, _, _, _, _, out6 = predictions
else:
out6 = predictions[:,0]
import matplotlib.pyplot as plt
B,D,H_,W_ = out6.shape
x = hand_pts[:,0,:,0]
y = hand_pts[:,0,:,1]
gt_pts = torch.stack((x,y)).permute(1,2,0).float()
mask = (1 - data['occ'][:,0])[...,None]
pred_pts = []
for b in range(B):
#kp = out6[b, :-1]: #ignore last layer (background)
kp = out6[b] #not regressing to background layer
max_indices = torch.argmax(kp.view(-1,H_*W_), dim=1)
rows = (max_indices / W_).float()
cols = (max_indices % H_).float()
#adjust for padding and image crpo
pl,pt,pr,pb = padding[b,0]
crop = input_crop[b,0]
crop_h = crop[3]-crop[1]
crop_w = crop[2]-crop[0]
'''
#GT data
temp = data['temp']
cols = temp[b,0,:,0]
rows = temp[b,0,:,1]
x_new = np.ceil((cols / 368 * crop_w) - pl + crop[0])
y_new = np.ceil((rows / 368 * crop_h) - pt + crop[1])
'''
x_new = ((cols / W_ * crop_w) - pl + crop[0]).int()
y_new = ((rows / H_ * crop_h) - pt + crop[1]).int()
pred_pts.append(torch.stack((x_new,y_new), dim=1))
if self.viz:
B,H,W,C = data['data'].shape
plt.figure(figsize=(16,7))
extent = np.int(0), np.int(368), np.int(0), np.int(368)
plt.subplot(2,3,1)
img = data['data'][b].cpu().numpy()
plt.imshow(img)
plt.scatter(x[b],y[b],c='g')
plt.scatter(x_new.cpu(), y_new.cpu(),c='r')
plt.title('Image with keypoints')
plt.subplot(2,3,2)
#heatmap = torch.max(out6[0,:-1],dim=0)[0]
heatmap = torch.max(out6[b],dim=0)[0]
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(heatmap.cpu().numpy(), cmap='jet', alpha=0.5, interpolation='none', extent=extent)
plt.title('Predicted')
plt.subplot(2,3,3)
#gt_heatmap = torch.max(data['heatmaps'][0,:-1],dim=0)[0]
gt_heatmap = torch.max(data['heatmaps'][b,0],dim=0)[0]
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(gt_heatmap.cpu().numpy(), cmap='jet', alpha=0.5, interpolation='none', extent=extent)
plt.title('Groundtruth')
plt.subplot(2,3,5)
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(out6[0,-1].cpu().numpy(), cmap='jet', alpha=0.5, interpolation='none', extent=extent)
plt.title('Predicted background')
plt.subplot(2,3,6)
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(data['heatmaps'][0,-1].cpu().numpy(), cmap='jet', alpha=0.5, interpolation='none', extent=extent)
plt.title('Background')
plt.show()
pred_pts = torch.stack(pred_pts).float().cpu()
dist = torch.norm(pred_pts*mask-gt_pts, dim=2)
for idx in range(len(self.threshold)):
self.acc[idx, :] += torch.sum((dist <= dist_thresh[:,idx].unsqueeze(1)),dim=0,dtype=torch.float)/self.ndata
self.count += 1
if self.count == self.nbatch:
if self.viz:
plt.plot(self.threshold.cpu().numpy(), torch.mean(self.acc, dim=1).cpu().numpy())
plt.grid(True, 'both')
plt.xlabel('Normalized Distance')
plt.ylabel('PCK')
plt.ylim([0, 1])
plt.show()
if not self.debug:
mean_acc = torch.mean(self.acc, dim=1).cpu().numpy()
if self.logger:
for idx in range(len(self.threshold)):
self.logger.log({'PCKh (Normalized Distance)':mean_acc[idx]})
#Return area under the curve
return torch.sum(torch.mean(self.acc, dim=1)/len(self.acc)).item()
#Mostly adapted from: https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/core/
class PCK_FlowTrack():
def __init__(self, threshold=0.5, **kwargs):
""""
Probability of Correct Keypoint (PCK) evaluation metric
but uses ground truth heatmap rather than x,y locations
First value to be returned is average accuracy across 'idxs',
followed by individual accuracies
Args:
threshold (Tensor, shape [11]): normalized distance thresholds
ndata (scalar): total number of datapoints in dataset
Returns:
None
"""
self.viz = kwargs['viz']
self.threshold = threshold
self.ndata = kwargs['ndata']
self.nbatch = np.ceil(self.ndata/kwargs['batch_size']).astype(np.int)
self.count = 0
self.correct = 0
self.total = 0
self.logger = kwargs['logger'] #logging tool
self.debug = kwargs['debug']
def get_max_preds(self, batch_heatmaps):
'''
get predictions from score maps
heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
'''
assert isinstance(batch_heatmaps, np.ndarray), \
'batch_heatmaps should be numpy.ndarray'
assert batch_heatmaps.ndim == 4, 'batch_images should be 4-ndim'
batch_size = batch_heatmaps.shape[0]
num_joints = batch_heatmaps.shape[1]
width = batch_heatmaps.shape[3]
heatmaps_reshaped = batch_heatmaps.reshape((batch_size, num_joints, -1))
idx = np.argmax(heatmaps_reshaped, 2)
maxvals = np.amax(heatmaps_reshaped, 2)
maxvals = maxvals.reshape((batch_size, num_joints, 1))
idx = idx.reshape((batch_size, num_joints, 1))
preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
preds[:, :, 0] = (preds[:, :, 0]) % width
preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)
pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
pred_mask = pred_mask.astype(np.float32)
preds *= pred_mask
return preds, maxvals
def calc_dists(self, preds, target, normalize):
preds = preds.astype(np.float32)
target = target.astype(np.float32)
dists = np.zeros((preds.shape[1], preds.shape[0]))
for n in range(preds.shape[0]):
for c in range(preds.shape[1]):
if target[n, c, 0] > 1 and target[n, c, 1] > 1:
normed_preds = preds[n, c, :] / normalize[n]
normed_targets = target[n, c, :] / normalize[n]
dists[c, n] = np.linalg.norm(normed_preds - normed_targets)
else:
dists[c, n] = -1
return dists
def dist_acc(self, dists, thr=0.5):
#Let's return the number of dists vals below threshold and average across all data
dist_cal = np.not_equal(dists, -1)
num_dist_cal = dist_cal.sum()
if num_dist_cal > 0:
return np.less(dists[dist_cal], thr).sum(), num_dist_cal
else:
return 0,0
def get_accuracy(self, predictions, data):
#model may output intermediate feature maps in tuple
if isinstance(predictions, tuple):
predictions = predictions[-1][:,:21].unsqueeze(1) #ignore last layer, unsqueeze T dim
target = data['heatmaps'].numpy()
predictions = predictions.cpu().numpy()
B,T,D,H,W = target.shape
#Reshape, temporal dimension now represents multiple objects per image
target = np.reshape(target, (B*T,D,H,W))
predictions = np.reshape(predictions, (B*T,D,H,W))
idx = list(range(predictions.shape[1]))
norm = 1.0
self.count += B
if self.count > self.ndata:
self.count = 0
self.correct = 0
self.total = 0
if self.viz:
joints = data['joint_names']
import matplotlib.pyplot as plt
for bt in range(B*T):
b = int(bt/T)
t = bt % T
img = data['data'][b,:,t].permute(1,2,0).cpu().numpy()
mean = np.array([[[123.675,116.28,103.52]]])
std = np.array([[[58.395,57.12,57.375]]])
img = np.clip(((img*std)+mean)/255,0,1)
extent = np.int(0), np.int(72), np.int(0), np.int(96)
'''
for j_idx in idx:
plt.figure(1, figsize=(12,8))
plt.subplot(5,5,j_idx+1)
plt.title('gt '+joints[j_idx][0])
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(target[bt, j_idx], cmap='jet', alpha=0.5, vmin=0, vmax=1, interpolation='none', extent=extent)
plt.colorbar()
plt.figure(2, figsize=(12,8))
plt.subplot(5,5,j_idx+1)
plt.title('pred '+joints[j_idx][0])
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(predictions[bt, j_idx], cmap='jet', alpha=0.5, vmin=0, vmax=1, interpolation='none', extent=extent)
plt.colorbar()
'''
plt.figure(1, figsize=(12,8))
plt.subplot(1,3,1)
plt.imshow(img, extent=extent)
plt.subplot(1,3,2)
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(np.max(target[bt], axis=0), cmap='jet', alpha=0.5, vmin=0, vmax=1, interpolation='none', extent=extent)
#plt.colorbar()
plt.subplot(1,3,3)
plt.imshow(img, interpolation='none', extent=extent)
plt.imshow(np.max(predictions[bt], axis=0), cmap='jet', alpha=0.5, vmin=0, vmax=1, interpolation='none', extent=extent)
#Display plot
plt.show()
#Save as .png instead of displaying plot
#os.makedirs('./eval_vis_outputs', exist_ok=True)
#plt.savefig('./eval_vis_outputs/'+str(data['obj_ids'][b].item())+'.png')
#plt.close()
pred, _ = self.get_max_preds(predictions)
target, _ = self.get_max_preds(target)
h = predictions.shape[2]
w = predictions.shape[3]
norm = np.ones((pred.shape[0], 2)) * np.array([h, w]) / 10
dists = self.calc_dists(pred, target, norm)
acc = np.zeros(len(idx))
avg_acc = 0
cnt = 0
for i in range(len(idx)):
acc[i], num_cal = self.dist_acc(dists[idx[i]], self.threshold)
avg_acc = avg_acc + acc[i]
cnt += num_cal
self.correct += avg_acc
self.total += cnt
if cnt == 0:
return torch.tensor(0)
else:
return self.correct/self.total
class Contrastive_Accuracy(object):
"""
Standard accuracy computation. # of correct cases/# of total cases
"""
def __init__(self, *args, **kwargs):
self.margin = kwargs['cont_acc_margin']
self.ndata = kwargs['ndata']
self.count = 0
self.correct = 0.
self.total = 0.
def get_accuracy(self, predictions, data):
"""
Args:
predictions (tuple):
- output1 (Tensor, shape [N, D])
- output2 (Tensor, shape [N, D])
data (dictionary):
- pair_label (Tensor, shape [N,1])
Return:
Accuracy # of correct case/ # of total cases
"""
output1, output2 = predictions
targets = data['pair_label']
if self.count >= self.ndata:
self.count = 0
self.correct = 0
self.total = 0
output1 = output1.detach().cpu()
output2 = output2.detach().cpu()
targets = targets.numpy()
dist_sq = torch.sum(pow(output2 - output1, 2), 1)
dist = torch.sqrt(dist_sq).numpy()
self.correct += np.sum((dist < self.margin) == targets)
self.total += output1.shape[0]
self.count += output1.shape[0]
return self.correct/self.total
class Save_Video_Keypoints():
"""
Write predictions to JSON, visualize and save as video
"""
def __init__(self, *args, **kwargs):
#self.result_dir = kwargs['result_dir']
self.load_type = kwargs['load_type']
self.batch_size = kwargs['batch_size']
self.ndata = kwargs['ndata']
self.count = 0
self.json_anns = {}
self.output_dir = os.path.join('./outputs',kwargs['model']+'-'+kwargs['exp'])
os.makedirs(self.output_dir, exist_ok=True)
self.viz = kwargs['viz']
self.eval_object = Eval_PoseTrack18_det(*args, **kwargs)
self.conf_threshold = kwargs['conf_threshold']
self.vout = cv2.VideoWriter()
self.fourcc = cv2.VideoWriter_fourcc(*'MP4V')
self.fps = 10 #29.97
self.vout_path = None
self.prev_f_path = None
self.prev_keypoints = []
self.prev_bbox = []
self.img = None
self.prev_seq = None
self.dex = []
self.xy_positions = {}
self.logger = kwargs['logger'] #logging tool
self.debug = kwargs['debug']
def get_accuracy(self, predictions, data):
"""
predictions (Tensor, shape [N,*])
data (dictionary):
- labels (Tensor, shape [N,*])
#Open-loop, labels may or may not exist
Return:
0
"""
bbox = data['bbox']
frame_path = data['frame_path']
frame_size = data['frame_size']
input_crop = data.get('input_crop', data['bbox'])
vid_id = data['vid_id']
neighbor_link = data['neighbor_link']
link_colors = data['link_colors']
labels = data.get('labels', None)
#predictions = predictions[-1].unsqueeze(1).cpu().numpy()
predictions = predictions.cpu().numpy()
input_crop = input_crop.int().numpy()
B,T,D,H,W = predictions.shape
padding = data.get('padding', torch.zeros(B,T,4))
#Reshape, temporal dimension now represents multiple objects per image
predictions = np.reshape(predictions, (B*T,D,H,W))
input_crop = np.reshape(input_crop, (B,T,-1))
idx = list(range(predictions.shape[1]))
pred, maxvals = self.eval_object.get_max_preds(predictions)
#NOTE: ONLY for PoseTrack18 dataset
#maxvals[:,3:5] = 0 #Left-Right ears are un-annotated
pred_mask = maxvals > self.conf_threshold
scores = np.clip(maxvals,0,1)
links = neighbor_link[0]
link_color = link_colors[0]
pred = np.reshape(pred, (B,T,D,2))
pred_mask = np.reshape(pred_mask, (B,T,D,1))
for b in range(B):
f_path = frame_path[0][b]
frame_w = frame_size[0][b]
frame_h = frame_size[1][b]
#Use same numpy image for all objects on same frame
if self.prev_f_path == None:
#'data' here must be original image
self.img = data['data'][b].cpu().numpy()
elif self.prev_f_path != f_path: #New frame
frame_id = self.prev_f_path.split('/')[-1].split('.')[0]
frame_id = int(''.join(c for c in frame_id if c.isdigit())) #strip non-numbers
anns = self.eval_object.assign_ids(self.json_anns, self.prev_seq, frame_id, self.prev_keypoints, self.prev_bbox, (frame_w, frame_h), self.img, label=self.dex)
self.prev_keypoints = []
self.prev_bbox = []
self.dex = []
max_tid = 0
#Draw assigned track ids on image
font = cv2.FONT_HERSHEY_SIMPLEX
if not anns is None:
for ann in anns:
tid = ann['track_id']
kpts = np.array(ann['keypoints']).reshape(D,3)
mask = kpts[:,2] > 0
xmin, ymin, _ = np.min(kpts[mask],0)
#cv2.putText(self.img, str(tid)+', '+ann['label'], (int(xmin),int(ymin)), font, 1.75, (0,255,255), 2, cv2.LINE_AA)
max_tid = max(tid, max_tid)
'''
#Save centroid positions
det_bbox = ann['det_box']
x_avg = (det_bbox[2]+det_bbox[0])/2
y_avg = (det_bbox[3]+det_bbox[1])/2
pos = ','.join((str(x_avg), str(y_avg), ann['label']))
if frame_id not in self.xy_positions:
self.xy_positions[frame_id] = {tid:pos}
else:
self.xy_positions[frame_id][tid] = pos
'''
self.vout.write(self.img)
#'data' here must be original image
self.img = data['data'][b].cpu().numpy()
#seq_name = f_path.split('/')[-2]
seq_name = vid_id[b]
if self.prev_seq != seq_name:
'''
if len(self.xy_positions.values()) > 0:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
tids = {}
for xy in self.xy_positions.values():
for tid, pos in xy.items():
if tid not in tids: tids[tid] = []
#pos = xy.get(tid, '-1,-1,n/a')
tids[tid].append(pos)
plt.ylim(top=0, bottom=frame_h)
plt.xlim(left=0,right=frame_w)
for tid, pos in tids.items():
x = np.array([float(dat.split(',')[0]) for dat in pos])
y = np.array([float(dat.split(',')[1]) for dat in pos])
dex = [dat.split(',')[2] for dat in pos if dat.split(',')[2] != 'n/a']
dex = max(set(dex), key=dex.count)
#color = list(np.random.choice(range(256), size=3))
x = x[x != -1]
y = y[y != -1]
plt.plot(x, y)
plt.plot(x[0],y[0],'go')
plt.plot(x[-1],y[-1],'ro')
plt.text(np.mean(x), np.mean(y), str(tid)+','+dex, fontsize=15)
#plt.show()
plt.savefig(os.path.join(self.output_dir, self.prev_seq+'.png'))
plt.close()
'''
self.prev_seq = seq_name
self.vout.release()
self.vout_path = os.path.join(self.output_dir,seq_name+'.mp4')
print(self.vout_path)
self.vout.open(self.vout_path, self.fourcc, self.fps, (frame_w.item(), frame_h.item()), True)
self.json_anns[seq_name] = {'annotations':[]}
self.xy_positions = {}
for t in range(T):
crop = input_crop[b,t]
pad = padding[b,t] #pl, pt, pr, pb
if crop[0] == -1:
continue
keypoints = np.concatenate((pred[b,t], pred_mask[b,t]), axis=-1)
if 'stride' in data:
#Scale coordinates from heatmap size
sw, sh = data['stride'][b]
keypoints[:,0] *= sw.item()
keypoints[:,1] *= sh.item()
#Apply inverse transform w/ respect original image
inv_trans = data['inv_trans']
keypoints[:,:2] = self.eval_object.transform_pts(keypoints[:,:2], inv_trans[b,t])
keypoints[keypoints[:,2] < 1] = 0
else:
#scale coordinates to crop size
crop_h = (crop[3]-crop[1]).item()
crop_w = (crop[2]-crop[0]).item()
keypoints[:,0] *= (crop_w/W)
keypoints[:,1] *= (crop_h/H)
#Undo crop
keypoints[:,0] += crop[0].item()
keypoints[:,1] += crop[1].item()
#Subtract padding if was added
keypoints[:,0] -= pad[0].item()
keypoints[:,1] -= pad[1].item()
if np.sum(keypoints[...,-1]>self.conf_threshold) >= 1:
self.prev_keypoints.append(keypoints)
self.prev_bbox.append(bbox[b,t].float())
#dexter = 'right' if labels[b].item() else 'left'
#self.dex.append(dexter)
box_line_size = 1 + np.floor(frame_w.item()/400).astype('int')
line_size = 4 * max(1, np.floor(frame_w.item()/400).astype('int'))
rad_size = 3 * max(1, np.floor(frame_w.item()/400).astype('int'))
xmin, ymin, xmax, ymax = crop #cropped input to model
#cv2.rectangle(self.img, (int(xmin),int(ymin)), (int(xmax),int(ymax)), color=(0,0,255)) #draw model input
xmin, ymin, xmax, ymax = bbox[b,t].int()
cv2.rectangle(self.img, (int(xmin),int(ymin)), (int(xmax),int(ymax)), color=(255,255,255), thickness=box_line_size) #draw tight bbox
for idx,(p1,p2) in enumerate(links):
x1, y1, c1 = keypoints[p1]
x2, y2, c2 = keypoints[p2]
#Filter keypoints outside of tight bounding box
if x1 < xmin or x1 > xmax or y1 < ymin or y1 > ymax:
c1 = 0
if x2 < xmin or x2 > xmax or y2 < ymin or y2 > ymax:
c2 = 0
col = col1 = col2 = link_color[idx].tolist() #R,G,B
r1 = r2 = rad_size
#let's make the wrist connection more obvious
if p1 == 0:
col1 = (255,255,255)
r1 = np.floor(rad_size*1.5).astype('int')
if p2 == 0:
col2 = (255,255,255)
r2 = np.floor(rad_size*1.5).astype('int')
if c1 != 0 and c2 != 0:
cv2.line(self.img, (int(x1),int(y1)), (int(x2),int(y2)), (col[2],col[1],col[0]), line_size)
if c1 != 0:
cv2.circle(self.img, (int(x1),int(y1)), radius=r1, color=(col1[2],col1[1],col1[0]), thickness=-1)
if c2 != 0 :
cv2.circle(self.img, (int(x2),int(y2)), radius=r2, color=(col2[2],col2[1],col2[0]), thickness=-1)
self.prev_f_path = f_path
self.count += B
if self.count >= self.ndata:
frame_id = self.prev_f_path.split('/')[-1].split('.')[0]
frame_id = int(''.join(c for c in frame_id if c.isdigit())) #strip non-numbers
anns = self.eval_object.assign_ids(self.json_anns, self.prev_seq, frame_id, self.prev_keypoints, self.prev_bbox, (frame_w, frame_h), self.img, label=self.dex)
self.prev_keypoints = []
self.prev_bbox = []
#Draw assigned track ids on image
font = cv2.FONT_HERSHEY_SIMPLEX
if not anns is None:
for ann in anns:
tid = ann['track_id']
kpts = np.array(ann['keypoints']).reshape(D,3)
mask = kpts[:,2] > 0
xmin, ymin, _ = np.min(kpts[mask],0)
#cv2.putText(self.img, str(tid)+', '+ann['label'], (int(xmin),int(ymin)), font, 1.75, (0,255,255), 2, cv2.LINE_AA)
'''
#Save centroid positions
det_bbox = ann['det_box']
x_avg = (det_bbox[2]+det_bbox[0])/2
y_avg = (det_bbox[3]+det_bbox[1])/2
pos = ','.join((str(x_avg), str(y_avg), ann['label']))
if frame_id not in self.xy_positions:
self.xy_positions[frame_id] = {tid:pos}
else:
self.xy_positions[frame_id][tid] = pos
'''
self.vout.write(self.img)
'''
import matplotlib.pyplot as plt
tids = {}
for xy in self.xy_positions.values():
for tid in range(0,max_tid+1):
if tid not in tids: tids[tid] = []
pos = xy.get(tid, '-1,-1,n/a')
tids[tid].append(pos)
plt.ylim(top=0, bottom=frame_h)
plt.xlim(left=0,right=frame_w)
for tid, pos in tids.items():
x = np.array([float(dat.split(',')[0]) for dat in pos])
y = np.array([float(dat.split(',')[1]) for dat in pos])
dex = [dat.split(',')[2] for dat in pos if dat.split(',')[2] != 'n/a']
dex = max(set(dex), key=dex.count)
#color = list(np.random.choice(range(256), size=3))
x = x[x != -1]
y = y[y != -1]
plt.plot(x, y)
plt.text(np.mean(x), np.mean(y), str(tid)+','+dex, fontsize=15)
#plt.show()
plt.savefig(os.path.join(self.output_dir, seq_name+'.png'))
plt.close()
'''
return 0
class Save_Frame_Video_Heatmaps():
"""
Reproject all heatmap predictions to full frame videos
"""
def __init__(self, *args, **kwargs):
#self.result_dir = kwargs['result_dir']
self.load_type = kwargs['load_type']
self.batch_size = kwargs['batch_size']
self.ndata = kwargs['ndata']
self.count = 0
self.json_anns = {}
self.output_dir = os.path.join('./outputs',kwargs['model']+'-'+kwargs['exp'])
os.makedirs(self.output_dir, exist_ok=True)
self.viz = kwargs['viz']
self.eval_object = Eval_PoseTrack18_det(*args, **kwargs)
self.conf_threshold = kwargs['conf_threshold']
self.vout = cv2.VideoWriter()
self.fourcc = cv2.VideoWriter_fourcc(*'MP4V')
#self.fps = 29.97
self.fps = 10
self.vout_path = None
self.prev_f_path = None
self.img = None
self.rgb_img = None
self.img_hm = None
self.save_feat = True #Save each heatmap image as a feature
self.save_feat_dir = os.path.join(kwargs['save_feat_dir'], kwargs['model']+'-'+kwargs['exp'])
self.prev_seq = None
self.logger = kwargs['logger'] #logging tool
self.debug = kwargs['debug']
def get_accuracy(self, predictions, data):
"""
predictions (Tensor, shape [N,*])
data (dictionary):
- labels (Tensor, shape [N,*])
#Open-loop, labels may or may not exist
Return:
0
"""
bbox = data['bbox']
frame_path = data['frame_path']
frame_size = data['frame_size']
input_crop = data.get('input_crop', data['bbox'])
vid_id = data['vid_id']
predictions = predictions.cpu().numpy()
input_crop = input_crop.int().numpy()
B,T,D,H,W = predictions.shape
padding = data.get('padding', torch.zeros(B,T,4))
#Reshape, temporal dimension now represents multiple objects per image
predictions = np.reshape(predictions, (B*T,D,H,W))
input_crop = np.reshape(input_crop, (B,T,-1))
idx = list(range(predictions.shape[1]))
#NOTE: ONLY for PoseTrack18 dataset
#maxvals[:,3:5] = 0 #Left-Right ears are un-annotated
for b in range(B):
f_path = frame_path[0][b]
frame_w = frame_size[0][b]
frame_h = frame_size[1][b]
seq_name = vid_id[b]
#Use same numpy image for all objects on same frame
if self.prev_f_path == None:
#'data' here must be original image
if self.viz:
self.rgb_img = data['data'][b].cpu().numpy()
self.img = np.zeros((frame_h, frame_w, 3), dtype=np.float32)
self.img_hm = np.zeros((frame_h, frame_w, D), dtype=np.float32)
elif self.prev_f_path != f_path: #New frame
frame_id = self.prev_f_path.split('/')[-1].split('.')[0]
frame_id = int(''.join(c for c in frame_id if c.isdigit())) #strip non-numbers
#Normalize and quantize