-
Notifications
You must be signed in to change notification settings - Fork 9
/
func_vpr.py
1852 lines (1612 loc) · 82.7 KB
/
func_vpr.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 func, func_sr
import time
import numpy as np
import matplotlib.pyplot as plt
import h5py
from tqdm import tqdm
from dataloaders.baidu_dataloader import Baidu_Dataset
from dataloaders.aerial_dataloader import Aerial
#from dataloaders.datasets_vg import map_builder
#from dataloaders.datasets_vg import util
#import utm
from glob import glob
from collections import defaultdict
import os
from os.path import join
from natsort import natsorted
import cv2
from typing import Literal, List
import torch
from tkinter import *
import matplotlib
from utilities import VLAD
from sklearn.decomposition import PCA
import pickle
import faiss
import json
from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors import KDTree
from torchvision import transforms as tvf
from sam.segment_anything import sam_model_registry, SamPredictor, SamAutomaticMaskGenerator
from utilities import DinoV2ExtractFeatures
from DINO.dino_wrapper import get_dino_pixel_wise_features_model, preprocess_frame
import importlib
# vlad_buff = importlib.import_module("VLAD-BuFF")
# from VLAD-BuFF.vpr_model import VPRModel
# from SALAD.vpr_model import VPRModel as VPRModelSalad
# from FastSAM.fastsam import FastSAM, FastSAMPrompt
# from FastSAM.utils.tools import convert_box_xywh_to_xyxy
import sys
sys.path.append('VLAD-BuFF')
# import utils
import vpr_model
import torch.nn.functional as F
# matplotlib.use('TkAgg')
workdir = '/media/kartik/data/kartik/data/segrec/out'
workdir_data = '/media/kartik/data/kartik/data/segrec/'
# cfg = {'rmin':0, 'desired_width':640, 'desired_height':480}
def first_k_unique_indices(ranked_indices, K):
"""
Obtain the first K unique indices from a ranked list of N indices.
:param ranked_indices: List[int] - List of ranked indices
:param K: int - Number of unique indices to obtain
:return: List[int] - List containing first K unique indices
"""
seen = set()
return [x for x in ranked_indices if x not in seen and (seen.add(x) or True)][:K]
def weighted_borda_count(*ranked_lists_with_scores):
"""
Merge ranked lists using a weighted Borda Count method where each index's score
is based on its similarity score rather than its position.
:param ranked_lists_with_scores: Variable number of tuples/lists containing (index, score) pairs.
:return: A list of indices sorted by their aggregated scores.
"""
scores = {}
for ranked_list in ranked_lists_with_scores:
for index, score in ranked_list:
if index in scores:
scores[index] += score
else:
scores[index] = score
sorted_indices = sorted(scores.keys(), key=lambda index: scores[index], reverse=True)
return sorted_indices
def get_matches(matches,gt,sims,segRangeQuery,imIndsRef,n=1,method="max_sim"):
"""
final version seems to be max_seg_topk_wt_borda_Im (need to confirm)
"""
preds=[]
for i in range(len(gt)):
if method == "max_sim":
match = np.flip(np.argsort(sims[segRangeQuery[i]])[-50:])
# pred_match.append(match)
match_patch = matches[segRangeQuery[i]][match]
pred = imIndsRef[match_patch]
pred_top_k = first_k_unique_indices(pred,n)
preds.append(pred_top_k)
elif method == "max_seg":
match_patch = matches[segRangeQuery[i]]
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method =="max_seg_sim":
match_patch = matches[segRangeQuery[i]]
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-6:])]
sims_patch = sims[segRangeQuery[i]]
sim_temp=[]
for j in range(len(pred)):
try:
sim_temp.append(np.max(sims_patch[np.where(imIndsRef[match_patch]==pred[j])[0]]))
except:
print("index: ", i)
print("pred: ", pred[j])
print("imInds: ", imIndsRef[match_patch])
pred = pred[np.flip(np.argsort(sim_temp))][:n]
preds.append(pred)
elif method=="max_seg_topk":
match_patch = matches[segRangeQuery[i]].flatten()
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method=="max_seg_topk_borda":
match_patch = matches[segRangeQuery[i]].T.tolist()
match_patch = merge_ranked_lists(*match_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method=="max_seg_topk_avg":
match_patch = matches[segRangeQuery[i]].T.tolist()
match_patch = average_rank_method(*match_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method=="max_seg_topk_wt_borda":
match_patch = matches[segRangeQuery[i]].T.tolist()
#TODO min max norm
# sims_patch = sims[segRangeQuery[i]].T.tolist()
sims_patch = sims[segRangeQuery[i]].T
sims_max = np.max(sims)
sims_min = np.min(sims)
sims_patch = (sims_patch - sims_min)/(sims_max-sims_min)
sims_patch = sims_patch.tolist()
pair_patch = [list(zip(match_patch[k],sims_patch[k])) for k in range(len(sims_patch))]
# pair_patch = [list(zip(match_patch[k],sims_patch[k])) for k in range(len(sims_patch))]
match_patch = weighted_borda_count(*pair_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method=="max_seg_topk_avg_sim":
match_patch = matches[segRangeQuery[i]].T.tolist()
#TODO min max norm
sims_patch = sims[segRangeQuery[i]].T
sims_max = np.max(sims)
sims_min = np.min(sims)
sims_patch = (sims_patch - sims_min)/(sims_max-sims_min)
sims_patch = sims_patch.tolist()
pair_patch = [list(zip(match_patch[k],sims_patch[k])) for k in range(len(sims_patch))]
# print(sims_patch)
# break
match_patch = average_similarity_scores(*pair_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
#using imInds
elif method=="max_seg_topk":
match_patch = matches[segRangeQuery[i]].flatten()
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method=="max_seg_topk_borda_Im":
match_patch = matches[segRangeQuery[i]].T.tolist()
match_patch = merge_ranked_lists(*imIndsRef[match_patch])
# segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
# pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(match_patch[:n])
elif method=="max_seg_topk_avg_Im":
match_patch = matches[segRangeQuery[i]].T.tolist()
match_patch = average_rank_method(*imIndsRef[match_patch])
# segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
# pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(match_patch[:n])
elif method=="max_seg_topk_wt_borda_Im":
match_patch = matches[segRangeQuery[i]].T.tolist()
#TODO min max norm
# sims_patch = sims[segRangeQuery[i]].T.tolist()
sims_patch = sims[segRangeQuery[i]].T
sims_max = np.max(sims)
sims_min = np.min(sims)
sims_patch = (sims_patch - sims_min)/(sims_max-sims_min)
sims_patch = sims_patch.tolist()
pair_patch = [list(zip(imIndsRef[match_patch[k]],sims_patch[k])) for k in range(len(sims_patch))]
# pair_patch = [list(zip(match_patch[k],sims_patch[k])) for k in range(len(sims_patch))]
match_patch = weighted_borda_count(*pair_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(match_patch[:n])
elif method=="max_seg_topk_avg_sim_Im":
match_patch = matches[segRangeQuery[i]].T.tolist()
#TODO min max norm
sims_patch = sims[segRangeQuery[i]].T
sims_max = np.max(sims)
sims_min = np.min(sims)
sims_patch = (sims_patch - sims_min)/(sims_max-sims_min)
sims_patch = sims_patch.tolist()
pair_patch = [list(zip(imIndsRef[match_patch[k]],sims_patch[k])) for k in range(len(sims_patch))]
# print(sims_patch)
# break
match_patch = average_similarity_scores(*pair_patch)
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(match_patch[:n])
return preds
def get_matches_for_single_image_pair(matches,sims,segRangeQuery,imIndsRef,n=1,method="max_sim"):
"""
Here, we are only considering a single image pair for the query and reference images,
rather than the entire dataset. This is for qualitative analysis purposes.
Using max_sim currently for this analysis as that seems to make sense for a given image pair.
Need to think about borda soon
Although final version for full dataset testing is be max_seg_topk_wt_borda_Im .
"""
preds=[]
i = 0
# for i in range(len(gt)):
if method == "max_sim":
match = np.flip(np.argsort(sims[segRangeQuery[i]])[-50:])
# pred_match.append(match)
sorted_query_segment_indices = match
sorted_reference_image_indices = matches[segRangeQuery[i]][match]
# match_patch = matches[segRangeQuery[i]][match]
# pred = imIndsRef[match_patch]
# pred_top_k = first_k_unique_indices(pred,n)
# preds.append(pred_top_k)
return sorted_query_segment_indices, sorted_reference_image_indices
# elif method == "max_seg":
# match_patch = matches[segRangeQuery[i]]
# segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
# pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# # sim_score_t = sim_img.T[i][pred]
# # preds.append(pred[np.flip(np.argsort(sim_score_t))])
# preds.append(pred)
# elif method =="max_seg_sim":
# match_patch = matches[segRangeQuery[i]]
# segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
# pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-6:])]
# sims_patch = sims[segRangeQuery[i]]
# sim_temp=[]
# for j in range(len(pred)):
# try:
# sim_temp.append(np.max(sims_patch[np.where(imIndsRef[match_patch]==pred[j])[0]]))
# except:
# print("index: ", i)
# print("pred: ", pred[j])
# print("imInds: ", imIndsRef[match_patch])
# pred = pred[np.flip(np.argsort(sim_temp))][:n]
# preds.append(pred)
# elif method=="max_seg_topk_wt_borda_Im":
# match_patch = matches[segRangeQuery[i]].T.tolist()
# #TODO min max norm
# # sims_patch = sims[segRangeQuery[i]].T.tolist()
# sims_patch = sims[segRangeQuery[i]].T
# sims_max = np.max(sims)
# sims_min = np.min(sims)
# sims_patch = (sims_patch - sims_min)/(sims_max-sims_min)
# sims_patch = sims_patch.tolist()
# pair_patch = [list(zip(imIndsRef[match_patch[k]],sims_patch[k])) for k in range(len(sims_patch))]
# # pair_patch = [list(zip(match_patch[k],sims_patch[k])) for k in range(len(sims_patch))]
# match_patch = weighted_borda_count(*pair_patch)
# segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
# pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# # sim_score_t = sim_img.T[i][pred]
# # preds.append(pred[np.flip(np.argsort(sim_score_t))])
# preds.append(match_patch[:n])
# return preds
def get_matches_old(matches,gt,sims,segRangeQuery,imIndsRef,n=1,method="max_sim"):
preds=[]
for i in range(len(gt)):
if method == "max_sim":
match = np.flip(np.argsort(sims[segRangeQuery[i]])[-50:])
# pred_match.append(match)
match_patch = matches[segRangeQuery[i]][match]
pred = imIndsRef[match_patch]
pred_top_k = first_k_unique_indices(pred,n)
preds.append(pred_top_k)
elif method == "max_seg":
match_patch = matches[segRangeQuery[i]]
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-n:])]
# sim_score_t = sim_img.T[i][pred]
# preds.append(pred[np.flip(np.argsort(sim_score_t))])
preds.append(pred)
elif method =="max_seg_sim":
match_patch = matches[segRangeQuery[i]]
segIdx = np.where(np.bincount(imIndsRef[match_patch])>0)[0]
pred = segIdx[np.flip(np.argsort(np.bincount(imIndsRef[match_patch])[segIdx])[-6:])]
sims_patch = sims[segRangeQuery[i]]
sim_temp=[]
for j in range(len(pred)):
try:
sim_temp.append(np.max(sims_patch[np.where(imIndsRef[match_patch]==pred[j])[0]]))
except:
print("index: ", i)
print("pred: ", pred[j])
print("imInds: ", imIndsRef[match_patch])
pred = pred[np.flip(np.argsort(sim_temp))][:n]
preds.append(pred)
return preds
def convert_to_queries_results_for_map(max_seg_preds, gt):
queries_results = []
for query_idx, refs in enumerate(max_seg_preds):
query_results = [ref in gt[query_idx] for ref in refs]
queries_results.append(query_results)
return queries_results
def calculate_ap(retrieved_items):
"""
Calculate the average precision (AP) for a single query.
retrieved_items: a list of boolean values, where True indicates a relevant item, and False indicates a non-relevant item.
"""
relevant_items = sum(retrieved_items)
if relevant_items == 0:
return 0 # Return 0 if there are no relevant items
cumsum = 0
precision_at_k = 0
for i, is_relevant in enumerate(retrieved_items, start=1):
if is_relevant:
cumsum += 1
precision_at_k += cumsum / i
average_precision = precision_at_k / relevant_items
return average_precision
def calculate_map(queries_results):
"""
Calculate the mean average precision (mAP) for a set of queries.
queries_results: a list of lists, where each inner list represents the retrieved items for a query,
with True for relevant items and False for non-relevant items.
# Example usage
queries_results = [
[True, False, True, False, True], # Query 1: list of retrieved items (True = relevant, False = not relevant)
[False, True, True, False, False], # Query 2
[True, True, False, False, False], # Query 3
]
map_score = calculate_map(queries_results)
print(f"Mean Average Precision (mAP): {map_score}")
"""
ap_scores = [calculate_ap(query) for query in queries_results]
return sum(ap_scores) / len(ap_scores) if ap_scores else 0
def calc_recall(pred,gt,n,analysis=False):
recall=[0]*n
recall_per_query=[0]*len(gt)
num_eval = 0
for i in range(len(gt)):
if len(gt[i])==0:
continue
num_eval+=1
for j in range(len(pred[i])):
# print(len(max_seg_preds[i]))
# print(i)
if n==1:
if pred[i] in gt[i]:
recall[j]+=1
recall_per_query[i]=1
break
else:
if pred[i][j] in gt[i]:
recall[j]+=1
break
recalls = np.cumsum(recall)/float(num_eval)
print("POSITIVES/TOTAL segVLAD for this dataset: ", np.cumsum(recall),"/", num_eval)
if analysis:
return recalls.tolist(), recall_per_query
return recalls.tolist()
def unpickle(file):
pickle_out = open(file,'rb')
desc = pickle.load(pickle_out)
pickle_out.close()
return desc
def getIdxs(ims,masks_in, minArea=400, retunrMask = True):
imInds =[]
regInds=[]
segMasks =[]
for i in tqdm(range(len(ims))):
im_name = ims[i]
key =f"{im_name}"
# print(key)
segRange=[]
regIndsIm=[]
segmask=[]
count = 0
for k in natsorted(masks_in[key+'/masks/'].keys()):
mask = masks_in[key+f'/masks/{k}/']
# for mask in masks:
# m = mask['segmentation'][()]
# m = torch.nn.functional.interpolate(m.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
if mask['area'][()]>minArea:
if retunrMask:
segmask.append(mask['segmentation'][()])
regIndsIm.append(count)
imInds.append(i)
count+=1
regInds.append(regIndsIm)
segMasks.append(segmask)
return np.array(imInds), regInds, segMasks
def getIdxs_simple_without_segMasks(ims,masks_in, minArea=400, retunrMask = True):
imInds =[]
regInds=[]
segMasks =[]
for i in tqdm(range(len(ims))):
im_name = ims[i]
key =f"{im_name}"
# print(key)
segRange=[]
regIndsIm=[]
# segmask=[]
count = 0
for k in natsorted(masks_in[key+'/masks/'].keys()):
# mask = masks_in[key+f'/masks/{k}/']
# for mask in masks:
# m = mask['segmentation'][()]
# m = torch.nn.functional.interpolate(m.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
# if mask['area'][()]>minArea:
# if retunrMask:
# segmask.append(mask['segmentation'][()])
regIndsIm.append(count)
imInds.append(i)
# print(imInds)
count+=1
regInds.append(regIndsIm)
# segMasks.append(segmask)
return np.array(imInds), regInds, segMasks
def getAnyLocFt(img, extractor, device='cuda',upsample=True):
base_tf = tvf.Compose([tvf.ToTensor(),
tvf.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])])
with torch.no_grad():
img_pt = base_tf(img).to(device)
# Make image patchable (14, 14 patches)
c, h, w = img_pt.shape
h_reduced, w_reduced = h // 14, w // 14 # h_r * w_r = 17 * 22 = 374
h_new, w_new = h_reduced * 14, w_reduced * 14
img_pt = tvf.CenterCrop((h_new, w_new))(img_pt)[None, ...]
# Extract descriptor
feat = extractor(img_pt) # [1, num_patches, desc_dim] i.e. [1, 374, 1536]
feat = feat.reshape(1,h_reduced,w_reduced,-1) # [1, 17, 22, 1536]
feat = feat.permute(0, 3, 1, 2) # [1, 1536, 17, 22]
if upsample:
feat = torch.nn.functional.interpolate(feat, [h,w], mode="bilinear", align_corners=True) # [1, 1536, 240, 320]
return feat #pixel wise features: [1, 1536, 240, 320] for img size of (240, 320, 3) if upsample=True else [1, 1536, 17, 22]
def loadSAM(sam_checkpoint, cfg, device = 'cuda'):
model_type = "vit_h"
sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)
mask_generator = SamAutomaticMaskGenerator(sam)
return mask_generator
def loadSAM_FastSAM(fastsam_checkpoint, cfg, device = 'cuda'):
model = FastSAM(fastsam_checkpoint)
model.to(device) # Ensure model is moved to the appropriate device
# model_type = "vit_t"
# sam = mobile_sam_model_registry[model_type](checkpoint=sam_checkpoint)
# sam.to(device=device)
# mask_generator = MobileSamAutomaticMaskGenerator(sam)
return model
def loadDINO(cfg, device = "cuda"):
if cfg['dinov2']:
dino = DinoV2ExtractFeatures("dinov2_vitg14", 31, 'value', device='cuda',norm_descs=False)
else:
dino = get_dino_pixel_wise_features_model(cfg = cfg, device = device)
return dino
def process_single_SAM(cfg, img, models, device):
mask_generator = models
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if cfg['resize']:
img_p = cv2.resize(img, (cfg['desired_width'],cfg['desired_height']))
else : img_p = img
masks = mask_generator.generate(img_p)
return img_p, masks
def process_single_DINO(cfg,img,models,device):
dino = models
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if cfg['resize']:
img_p = cv2.resize(img, (cfg['desired_width'],cfg['desired_height']))
else : img_p =img
if cfg['dinov2']:
img_feat = getAnyLocFt(img_p, dino, device, upsample=False)
# img_feat = getAnyLocFt(img_p, dino, device, upsample=True) #shub
else:
img_d = preprocess_frame(img_p, cfg=cfg)
img_feat = dino.forward(img_d)
img_feat_norm = torch.nn.functional.normalize(img_feat, dim=1)
return img_p, img_feat_norm
def masks_given_image(SAM, ims_i, dataPath1, cfg, mask_full_resolution=False, device="cuda"):
rmin = cfg['rmin']
if mask_full_resolution: #DINO always full resolution
width_SAM, height_SAM = cfg['desired_width'], cfg['desired_height']
print(f"IMPORTANT: The dimensions being used for SAM extraction are {width_SAM}x{height_SAM} pixels.")
else:
width_SAM, height_SAM = int(0.5 * cfg['desired_width']), int(0.5 * cfg['desired_height'])
print(f"IMPORTANT: The dimensions being used for SAM extraction are {width_SAM}x{height_SAM} pixels.")
masks_seg = []
im = cv2.imread(f'{dataPath1}/{ims_i}')[rmin:,:,:]
cfg_sam = { "desired_width": width_SAM, "desired_height": height_SAM, "detect": 'dino', "use_sam": True, "class_threshold": 0.9, \
"desired_feature": 0, "query_type": 'text', "sort_by": 'area', "use_16bit": False, "use_cuda": True,\
"dino_strides": 4, "use_traced_model": False,
"rmin":0, "DAStoreFull":False, "dinov2": True, "wrap":False, "resize": True} # robohop specifc params
im_p, masks = process_single_SAM(cfg_sam, im, SAM, device)
for j, m in enumerate(masks):
# for k in m.keys():
# import pdb; pdb.set_trace()
mask_area = m['area']
# if mask_area < 12000:
# if mask_area < 7000:
# masks_seg.append(m['segmentation'])#[()])
masks_seg.append(m['segmentation'])#[()])
return masks_seg, masks
def masks_given_image_old(sam_checkpoint, ims_i, dataPath1, cfg, mask_full_resolution=False, device="cuda"):
rmin = cfg['rmin']
if mask_full_resolution: #DINO always full resolution
width_SAM, height_SAM = cfg['desired_width'], cfg['desired_height']
print(f"IMPORTANT: The dimensions being used for SAM extraction are {width_SAM}x{height_SAM} pixels.")
else:
width_SAM, height_SAM = int(0.5 * cfg['desired_width']), int(0.5 * cfg['desired_height'])
print(f"IMPORTANT: The dimensions being used for SAM extraction are {width_SAM}x{height_SAM} pixels.")
cfg_sam = { "desired_width": width_SAM, "desired_height": height_SAM, "detect": 'dino', "use_sam": True, "class_threshold": 0.9, \
"desired_feature": 0, "query_type": 'text', "sort_by": 'area', "use_16bit": False, "use_cuda": True,\
"dino_strides": 4, "use_traced_model": False,
"rmin":0, "DAStoreFull":False, "dinov2": True, "wrap":False, "resize": True} # robohop specifc params
SAM = loadSAM(sam_checkpoint,cfg_sam, device="cuda")
masks_seg = []
im = cv2.imread(f'{dataPath1}/{ims_i}')[rmin:,:,:]
im_p, masks = process_single_SAM(cfg_sam, im, SAM, device)
for j, m in enumerate(masks):
# for k in m.keys():
# import pdb; pdb.set_trace()
mask_area = m['area']
# if mask_area < 12000:
if mask_area < 7000:
masks_seg.append(m['segmentation'])#[()])
# masks_seg.append(m['segmentation'])#[()])
return masks_seg
def dino_given_image(dino, ims_i, dataPath1, cfg, device="cuda"):
rmin = cfg['rmin']
width_DINO, height_DINO = cfg['desired_width'], cfg['desired_height']
cfg_dino = { "desired_width": width_DINO, "desired_height": height_DINO, "detect": 'dino', "use_sam": True, "class_threshold": 0.9, \
"desired_feature": 0, "query_type": 'text', "sort_by": 'area', "use_16bit": False, "use_cuda": True,\
"dino_strides": 4, "use_traced_model": False,
"rmin":0, "DAStoreFull":False, "dinov2": True, "wrap":False, "resize": True} # robohop specifc params
im = cv2.imread(f'{dataPath1}/{ims_i}')[rmin:,:,:]
im_p, ift_dino = process_single_DINO(cfg_dino,im,dino,device)
# ift_dino = ift_dino.detach().cpu().numpy()
# dino_desc = torch.from_numpy(ift_dino)
# return dino_desc
ift_dino = ift_dino.detach().cpu()
return ift_dino
def process_dino_ft_to_h5(h5FullPath,cfg,ims,models,device = "cuda",dataDir="./"):
rmin = cfg['rmin']
with h5py.File(h5FullPath, "w") as f:
# loop over images and create a h5py group per image
# imnames = sorted(os.listdir(f'{workdir}/{datasetpath}'))
# for i, imname in enumerate(imnames):
# im = cv2.imread(f'{workdir}/{datasetpath}/{imname}')
for i, _ in enumerate(tqdm(ims)):
if isinstance(ims[0],str):
imname = ims[i]
im = cv2.imread(f'{dataDir}/{imname}')[rmin:,:,:]
else:
imname, im = i, ims[i][rmin:,:,:]
im_p, ift_dino = process_single_DINO(cfg,im,models,device)
grp = f.create_group(f"{imname}")
grp.create_dataset("ift_dino", data=ift_dino.detach().cpu().numpy())
def process_SAM_to_h5(h5FullPath,cfg,ims,models,device="cuda",dataDir="./"):
rmin = cfg['rmin']
with h5py.File(h5FullPath, "w") as f:
for i, _ in enumerate(tqdm(ims)):
if isinstance(ims[0],str):
imname = ims[i]
im = cv2.imread(f'{dataDir}/{imname}')[rmin:,:,:]
else:
imname, im = i, ims[i][rmin:,:,:]
im_p, masks = process_single_SAM(cfg,im,models,device)
grp = f.create_group(f"{imname}")
grp.create_group("masks")
for j, m in enumerate(masks):
for k in m.keys():
grp["masks"].create_dataset(f"{j}/{k}", data=m[k])
def process_SAM_to_h5_FastSAM(h5FullPath,cfg,ims,model,device="cuda",dataDir="./"):
rmin = cfg['rmin']
with h5py.File(h5FullPath, "w") as f:
for i, _ in enumerate(tqdm(ims)):
if isinstance(ims[0],str):
imname = ims[i]
# im = cv2.imread(f'{dataDir}/{imname}')[rmin:,:,:]
im = Image.open(f'{dataDir}/{imname}')
else:
imname, im = i, ims[i][rmin:,:,:]
masks = process_single_FastSAM(cfg,im,model,imname, device)
grp = f.create_group(f"{imname}")
grp.create_group("masks")
for j, m in enumerate(masks):
for k in m.keys():
grp["masks"].create_dataset(f"{j}/{k}", data=m[k])
def process_single_FastSAM(cfg,input_image,model, imname, device="cuda", imgsz=1024, iou=0.9, conf=0.4, retina=True):
input_image = input_image.convert("RGB")
if cfg['resize']:
img_np = np.array(input_image)
img_np = cv2.resize(img_np, (cfg['desired_width'], cfg['desired_height']))
input_image = Image.fromarray(img_np)
everything_results = model(
input_image,
device=device,
retina_masks=retina,
imgsz=imgsz,
conf=conf,
iou=iou
)
prompt_process = FastSAMPrompt(input_image, everything_results, device=device)
ann = prompt_process.everything_prompt()
# ann is # Tensor of shape torch.Size([num_objects, height, width])
if isinstance(ann, torch.Tensor):
ann_numpy = ann.cpu().numpy().astype(bool)
else: #if it is an empty list
print("Empty list - no masks found for image name : ", imname)
print("printing ann for verification: ", ann)
# create a mask of two types: one with all ones and one with one random pixel set to True
ann_numpy = np.zeros((2, cfg['desired_height'], cfg['desired_width']), dtype=bool) # careful: numpy uses oppsoite convention of opencv for h,w
ann_numpy[0] = np.ones((cfg['desired_height'], cfg['desired_width']), dtype=bool) # careful: numpy uses oppsoite convention of opencv for h,w
# ann_numpy = np.zeros((1, cfg['desired_height'], cfg['desired_width']), dtype=bool)
random_row = np.random.randint(0, cfg['desired_height'])
random_col = np.random.randint(0, cfg['desired_width'])
# Set the randomly chosen pixel to True
ann_numpy[1, random_row, random_col] = True
# Create the list of dictionaries with segmentation masks
masks = [{"segmentation": ann_numpy[i]} for i in range(ann_numpy.shape[0])]
return masks
def preload_masks(masks_in, image_key):
"""
Preloads all masks for a given image key from the HDF5 file.
Args:
- masks_in: An open h5py File or Group object representing the HDF5 file or a group within it.
- image_key: The key in the HDF5 file for the specific image.
Returns:
- A list of mask data loaded into memory.
"""
masks_path = f"{image_key}/masks/"
mask_keys = natsorted(masks_in[masks_path].keys())
masks_seg = [masks_in[masks_path + k]['segmentation'][()] for k in mask_keys]
return masks_seg
def getIdxSingleFast(img_idx, masks_seg, minArea=400, returnMask=True):
imInds = []
regIndsIm = []
segmask = []
count = 0
# im_name = ims[img_idx]
# key = f"{im_name}"
# Preload all masks for the image
# masks_seg, mask_keys = preload_masks(masks_in, key)
for mask in masks_seg:
# Assuming 'area' is a property that can be efficiently accessed without loading the entire mask
# This may require adjusting based on your actual HDF5 structure and how 'area' is stored
# area = masks_in[f"{key}/masks/{k}/area"][()]
# if area > minArea:
if returnMask:
segmask.append(mask)
regIndsIm.append(count)
imInds.append(img_idx)
count += 1
return np.array(imInds), regIndsIm, segmask
def countNumMasksInDataset(ims, masks_in):
count = 0
for im_name in tqdm(ims, desc="Counting num of masks in dataset"):
# Directly constructing the path to the masks for the current image
mask_path = f"{im_name}/masks/"
if mask_path in masks_in:
# Assuming each key under mask_path corresponds to one mask,
# and we can count them directly.
mask_keys = natsorted(masks_in[mask_path].keys())
count += len(mask_keys)
return count
def getIdxSingleFast_for_single_image_pair(masks_seg, minArea=400, returnMask=True):
"""
This function is for the case where we are doing say qual analysis for a single image pair of query and reference images. So this function is over all the masks of a single image rather than taking all the masks from full dataset.
"""
img_idx = 0 # Only 1 image is handled every function call
imInds = []
regIndsIm = []
segmask = []
count = 0
# im_name = ims[img_idx]
# key = f"{im_name}"
# Preload all masks for the image
# masks_seg, mask_keys = preload_masks(masks_in, key)
for mask in masks_seg:
# Assuming 'area' is a property that can be efficiently accessed without loading the entire mask
# This may require adjusting based on your actual HDF5 structure and how 'area' is stored
# area = masks_in[f"{key}/masks/{k}/area"][()]
# if area > minArea:
if returnMask:
segmask.append(mask)
regIndsIm.append(count)
imInds.append(img_idx)
count += 1
return np.array(imInds), regIndsIm, segmask
def get_recall(database_vectors, query_vectors, gt, analysis =False, k=5):
# Original PointNetVLAD code
# import pdb;pdb.set_trace()
# if database_vectors.dtype!=np.float32:
# database_output = database_vectors.detach().cpu().numpy()
# queries_output = query_vectors.detach().cpu().numpy()
# else:
database_output = database_vectors
queries_output = query_vectors
# When embeddings are normalized, using Euclidean distance gives the same
# nearest neighbour search results as using cosine distance
database_nbrs = KDTree(database_output)
num_neighbors = k
recall = [0] * num_neighbors
recall_per_query=[0]*len(queries_output)
top1_similarity_score = []
one_percent_retrieved = 0
threshold = max(int(round(len(database_output)/100.0)), 1)
matches =[]
num_evaluated = 0
for i in range(len(queries_output)):
# i is query element ndx
# query_details = query_sets[n][i] # {'query': path, 'northing': , 'easting': }
true_neighbors = gt[i]
distances, indices = database_nbrs.query(np.array([queries_output[i]]), k=num_neighbors)
dict_info = {'seg_id_q': -1, 'img_id_r': indices[0], 'seg_id_r': -1, 'img_id_to_seg_id': -1}
matches.append(dict_info)
# import pdb;pdb.set_trace()
if len(true_neighbors) == 0:
continue
num_evaluated += 1
for j in range(len(indices[0])):
if indices[0][j] in true_neighbors:
if j == 0:
similarity = np.dot(queries_output[i], database_output[indices[0][j]])
top1_similarity_score.append(similarity)
recall[j] += 1
recall_per_query[i]=1
break
# import pdb;pdb.set_trace()
if len(list(set(indices[0][0:threshold]).intersection(set(true_neighbors)))) > 0:
one_percent_retrieved += 1
one_percent_recall = (one_percent_retrieved/float(num_evaluated))*100
print("POSITIVES/TOTAL AnyLoc for this dataset: ", np.cumsum(recall),"/", num_evaluated)
recall = (np.cumsum(recall)/float(num_evaluated))*100
if analysis:
return recall, recall_per_query, matches
return recall,matches
# import pdb;pdb.set_trace()
def aggFt(desc_path, masks, segRange, cfg,aggType, vlad = None, upsample = False, segment_global = False,segment = False):
f = h5py.File(desc_path, "r")
# keys = list(f.keys())
keys = list(natsorted(f.keys()))
imFts=[]
for i in tqdm(range(len(keys))):
if aggType =="avg":
segfeat = torch.empty([1,1536,0]).to('cuda')
dino_desc = torch.from_numpy(f[keys[i]]['ift_dino'][()]).to('cuda')
if upsample:
dino_desc = torch.nn.functional.interpolate(dino_desc, [cfg['desired_height'],cfg['desired_width']], mode="bilinear", align_corners=True)
dino_desc_norm = torch.nn.functional.normalize(dino_desc, dim=1)
if segment_global:
for j in range(len(segRange[i])):
# mask = torch.from_numpy(G.nodes[segRange[i][j]]['segmentation']).to('cuda')
mask = masks[i][segRange[i][j]].to('cuda')
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
reg_feat_norm = dino_desc_norm[:,:,mask]
segfeat = torch.cat((segfeat,reg_feat_norm),axis =2)
imFt = segfeat.mean(axis =2).detach().cpu().numpy()
imFt = np.reshape(imFt, (imFt.shape[-1],))
imFts.append(imFt)
if segment:
for j in range(len(segRange[i])):
# mask = torch.from_numpy(G.nodes[segRange[i][j]]['segmentation']).to('cuda')
mask = torch.from_numpy(masks[i][j]).to('cuda')
if upsample:
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
else :
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height']//14,cfg['desired_width']//14], mode = 'nearest').squeeze().bool()
reg_feat_norm = dino_desc_norm[:,:,mask].mean(axis=2).detach().cpu().numpy()
imFt = reg_feat_norm
imFt = np.reshape(imFt, (imFt.shape[-1],))
imFts.append(imFt)
else :
imFt = dino_desc_norm.mean([2,3]).detach().cpu().numpy()
imFt = np.reshape(imFt, (imFt.shape[-1],))
imFts.append(imFt)
elif aggType=="vlad":
if segment:
dino_desc = torch.from_numpy(f[keys[i]]['ift_dino'][()]).to('cuda')
if upsample:
dino_desc = torch.nn.functional.interpolate(dino_desc, [cfg['desired_height'],cfg['desired_width']], mode="bilinear", align_corners=True)
dino_desc_norm = torch.nn.functional.normalize(dino_desc, dim=1)
for j in range(len(segRange[i])):
mask = torch.from_numpy(masks[i][j]).to('cuda')
# mask = torch.from_numpy(G.nodes[segRange[i][j]]['segmentation']).to('cuda')
if upsample:
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
else :
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height']//14,cfg['desired_width']//14], mode = 'nearest').squeeze().bool()
reg_feat_norm = dino_desc_norm[:,:,mask]
reg_feat_per = reg_feat_norm.permute(0,2,1)
gd = vlad.generate(reg_feat_per.cpu().squeeze())
gd_np = gd.numpy()
imFts.append(gd_np)
# segfeat = torch.empty([1,49152,0])
else:
dino_desc = torch.from_numpy(np.reshape(f[keys[i]]['ift_dino'][()],(1,1536,f[keys[i]]['ift_dino'][()].shape[2]*f[keys[i]]['ift_dino'][()].shape[3]))).to('cuda')
# if upsample:
# dino_desc = torch.nn.functional.interpolate(dino_desc, [cfg['desired_height'],cfg['desired_width']], mode="bilinear", align_corners=True)
dino_desc_norm = torch.nn.functional.normalize(dino_desc, dim=1)
dino_desc_per = dino_desc_norm.permute(0,2,1)
gd = vlad.generate(dino_desc_per.cpu().squeeze())
gd_np = gd.numpy()
imFts.append(gd_np)
return imFts
# from numba import jit
# @jit(nopython=True)
def seg_vlad(desc_path, segMask, segRange, vlad, cfg):
f = h5py.File(desc_path, "r")
keys = list(f.keys())
imFts=torch.empty((0,49152))
imfts_batch = torch.empty((0,49152))
idx = np.empty((cfg['desired_height'],cfg['desired_width'],2)).astype('int32')
for i in range(cfg['desired_height']):
for j in range(cfg['desired_width']):
idx[i,j] = np.array([np.clip(i//14,0,cfg['desired_height']//14-1) ,np.clip(j//14,0,cfg['desired_width']//14-1)])
i=0
for i in tqdm(range(len(keys))):
mask_list=[]
dino_desc = torch.from_numpy(f[keys[i]]['ift_dino'][()]).to('cuda')
# dino_desc = torch.nn.functional.interpolate(dino_desc, [cfg['desired_height'],cfg['desired_width']], mode="bilinear", align_corners=True)
dino_desc = torch.from_numpy(np.reshape(f[keys[i]]['ift_dino'][()],(1,1536,f[keys[i]]['ift_dino'][()].shape[2]*f[keys[i]]['ift_dino'][()].shape[3]))).to('cuda')
# dino_desc=torch.reshape(dino_desc,(1,1536,500*500)).to('cuda')
dino_desc_norm = torch.nn.functional.normalize(dino_desc, dim=1)
for j in range(len(segRange[i])):
mask = torch.from_numpy(segMask[i][j]).to('cuda')
# mask = torch.from_numpy(G.nodes[segRange[i][j]]['segmentation']).to('cuda')
mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), [cfg['desired_height'],cfg['desired_width']], mode = 'nearest').squeeze().bool()
mask_list.append(mask.cpu())
# reg_feat_norm = dino_desc_norm[:,:,mask]
reg_feat_per = dino_desc_norm.permute(0,2,1)
gd,_ = vlad.generate(reg_feat_per.cpu().squeeze(),idx,mask_list)
# gd_np = gd.numpy()
# imFts= np.vstack([imFts,gd_np])
imfts_batch = torch.cat((imfts_batch,gd),dim=0)
if i%100 ==0:
imFts = torch.cat((imFts,imfts_batch),dim=0)
imfts_batch = torch.empty((0,49152))
# else:
imFts = torch.cat((imFts,imfts_batch),dim=0)
return imFts
# segfeat = torch.empty([1,49152,0])
# segfeat = torch.empty([1,49152,0])
def seg_vlad_gpu(desc_path, segMask, segRange, c_centers, cfg, desc_dim = 1536, adj_mat=None):
f = h5py.File(desc_path, "r")
keys = list(f.keys())