forked from cvg/Hierarchical-Localization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
match_features.py
175 lines (152 loc) · 6.02 KB
/
match_features.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
import argparse
from typing import Union, Optional, Dict
from pathlib import Path
import pprint
import collections.abc as collections
from tqdm import tqdm
import h5py
import torch
from . import matchers, logger
from .utils.base_model import dynamic_load
from .utils.parsers import names_to_pair, parse_retrieval
from .utils.io import list_h5_names
'''
A set of standard configurations that can be directly selected from the command
line using their name. Each is a dictionary with the following entries:
- output: the name of the match file that will be generated.
- model: the model configuration, as passed to a feature matcher.
'''
confs = {
'superglue': {
'output': 'matches-superglue',
'model': {
'name': 'superglue',
'weights': 'outdoor',
'sinkhorn_iterations': 50,
},
},
'superglue-fast': {
'output': 'matches-superglue-it5',
'model': {
'name': 'superglue',
'weights': 'outdoor',
'sinkhorn_iterations': 5,
},
},
'NN-superpoint': {
'output': 'matches-NN-mutual-dist.7',
'model': {
'name': 'nearest_neighbor',
'do_mutual_check': True,
'distance_threshold': 0.7,
},
},
'NN-ratio': {
'output': 'matches-NN-mutual-ratio.8',
'model': {
'name': 'nearest_neighbor',
'do_mutual_check': True,
'ratio_threshold': 0.8,
}
},
'NN-mutual': {
'output': 'matches-NN-mutual',
'model': {
'name': 'nearest_neighbor',
'do_mutual_check': True,
},
}
}
def main(conf: Dict,
pairs: Path, features: Union[Path, str],
export_dir: Optional[Path] = None,
matches: Optional[Path] = None,
features_ref: Optional[Path] = None,
overwrite: bool = False) -> Path:
if isinstance(features, Path) or Path(features).exists():
features_q = features
if matches is None:
raise ValueError('Either provide both features and matches as Path'
' or both as names.')
else:
if export_dir is None:
raise ValueError('Provide an export_dir if features is not'
f' a file path: {features}.')
features_q = Path(export_dir, features+'.h5')
if matches is None:
matches = Path(
export_dir, f'{features}_{conf["output"]}_{pairs.stem}.h5')
if features_ref is None:
features_ref = features_q
if isinstance(features_ref, collections.Iterable):
features_ref = list(features_ref)
else:
features_ref = [features_ref]
match_from_paths(conf, pairs, matches, features_q, features_ref, overwrite)
return matches
@torch.no_grad()
def match_from_paths(conf: Dict,
pairs_path: Path,
match_path: Path,
feature_path_q: Path,
feature_paths_refs: Path,
overwrite: bool = False) -> Path:
logger.info('Matching local features with configuration:'
f'\n{pprint.pformat(conf)}')
if not feature_path_q.exists():
raise FileNotFoundError(f'Query feature file {feature_path_q}.')
for path in feature_paths_refs:
if not path.exists():
raise FileNotFoundError(f'Reference feature file {path}.')
name2ref = {n: i for i, p in enumerate(feature_paths_refs)
for n in list_h5_names(p)}
assert pairs_path.exists(), pairs_path
pairs = parse_retrieval(pairs_path)
pairs = [(q, r) for q, rs in pairs.items() for r in rs]
device = 'cuda' if torch.cuda.is_available() else 'cpu'
Model = dynamic_load(matchers, conf['model']['name'])
model = Model(conf['model']).eval().to(device)
match_path.parent.mkdir(exist_ok=True, parents=True)
skip_pairs = set(list_h5_names(match_path)
if match_path.exists() and not overwrite else ())
for (name0, name1) in tqdm(pairs, smoothing=.1):
pair = names_to_pair(name0, name1)
# Avoid to recompute duplicates to save time
if pair in skip_pairs or names_to_pair(name0, name1) in skip_pairs:
continue
data = {}
with h5py.File(str(feature_path_q), 'r') as fd:
grp = fd[name0]
for k, v in grp.items():
data[k+'0'] = torch.from_numpy(v.__array__()).float().to(device)
# some matchers might expect an image but only use its size
data['image0'] = torch.empty((1,)+tuple(grp['image_size'])[::-1])
with h5py.File(str(feature_paths_refs[name2ref[name1]]), 'r') as fd:
grp = fd[name1]
for k, v in grp.items():
data[k+'1'] = torch.from_numpy(v.__array__()).float().to(device)
data['image1'] = torch.empty((1,)+tuple(grp['image_size'])[::-1])
data = {k: v[None] for k, v in data.items()}
pred = model(data)
with h5py.File(str(match_path), 'a') as fd:
if pair in fd:
del fd[pair]
grp = fd.create_group(pair)
matches = pred['matches0'][0].cpu().short().numpy()
grp.create_dataset('matches0', data=matches)
if 'matching_scores0' in pred:
scores = pred['matching_scores0'][0].cpu().half().numpy()
grp.create_dataset('matching_scores0', data=scores)
skip_pairs.add(pair)
logger.info('Finished exporting matches.')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--pairs', type=Path, required=True)
parser.add_argument('--export_dir', type=Path)
parser.add_argument('--features', type=str,
default='feats-superpoint-n4096-r1024')
parser.add_argument('--matches', type=Path)
parser.add_argument('--conf', type=str, default='superglue',
choices=list(confs.keys()))
args = parser.parse_args()
main(confs[args.conf], args.pairs, args.features, args.export_dir)