forked from shrubb/offline-vi-3d-reconstruction
/
detect_match.py
276 lines (246 loc) · 9.39 KB
/
detect_match.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
import numpy as np
from skimage import io
from skimage.feature import ORB
from skimage.color import rgb2gray
from skimage.feature import match_descriptors
from skimage.transform import ProjectiveTransform, AffineTransform
from skimage.measure import ransac
from skimage.feature import plot_matches
import cv2
def detect_kp_desc(img, method='orb', n_keypoints=2000, **args):
"""Find keypoints and their descriptors on the image.
img:
`np.array` of shape == WxHx3
RGB image
method:
str
Name of the method to use. Options are: ['orb', 'lf-net']
n_keypoints:
int
Number of keypoints to find
**args:
dict
Other parameters to pass to keypoints detector without any chanages
return:
tuple (2,)
Coordinates and descriptors of found keypoints
"""
if method == 'orb':
detector_exctractor = ORB(n_keypoints=n_keypoints, **args)
# detector_exctractor = cv2.ORB_create(nfeatures=n_keypoints, **args)
elif method == 'lf-net':
# https://github.com/vcg-uvic/lf-net-release
raise NotImplemetedError()
detector_exctractor.detect_and_extract(rgb2gray(img).astype(np.float64))
return detector_exctractor.keypoints, detector_exctractor.descriptors
def match_flann(
src_descriptors, dest_descriptors,
num_trees=5,
checks=50,
n_neighbors=2,
apply_ratio_test=False
):
# FLANN parameters
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=num_trees)
search_params = dict(checks=checks)
# matching procedure
flann = cv2.FlannBasedMatcher(index_params,search_params)
src_descriptors = src_descriptors.astype(np.float32)
dest_descriptors = dest_descriptors.astype(np.float32)
matches = flann.knnMatch(src_descriptors, dest_descriptors, k=n_neighbors)
# ratio test as per Lowe's paper
if apply_ratio_test:
good = []
matchesMask = [[0,0] for i in xrange(len(matches))]
for i,(m,n) in enumerate(matches):
if m.distance < 0.7 * n.distance:
matchesMask[i]=[1,0]
good.append([m])
matches = good
# get rid of cv2 format
matches = np.array([[
matches[i][j].queryIdx, matches[i][j].trainIdx]
for i in range(len(matches))
for j in range(len(matches[i]))
])
return matches
def match_robust(
src_keypoints, src_descriptors,
dest_keypoints, dest_descriptors,
method='brute-force',
model_class=AffineTransform,
min_samples=4,
residual_threshold=1,
max_trials=5000,
**kwargs
):
"""Find matches of keypoints between two images and filter outlier with RANSAC.
src_keypoints, dest_keypoints:
(both) `np.array(float)` of the shape (N, 2)
Coordinates of keypoints in format (x, y) each
src_descriptors, dest_descriptors:
(both) `np.array(float)` of the shape (N, P)
Descriptors of the keypoints. P is a descriptor dim
model_class:
`skimage.transform`
Model of plane transformation
min_samples:
int
Number of points needed to construct the transformation.
The harder the model is the more points are needed.
See the docs to know about each particular model.
residual_threshold:
int
Distance in pixel in which the points are considered as "the same".
max_trials:
int
Number of trials to do before stopping.
The more is the number of keypoints, the larger `max_trials` should be.
**kwargs:
dict
Other params, kept unchanged
return:
model, matches
model: transformation of the 1st frame to the second
matches:
`np.array` of shape == (num_matched_keypoints, 2)
List of matches in format: np.array([[src_kp_id1, dest_kp_id1], ...], dtype=int)
"""
if method == 'brute-force':
matches = match_descriptors(src_descriptors, dest_descriptors)
elif method == 'flann':
matches = match_descriptors(src_descriptors, dest_descriptors)
model, inliers = ransac(
(src_keypoints[matches[:,0]], dest_keypoints[matches[:,1]]),
model_class=model_class,
min_samples=min_samples,
residual_threshold=residual_threshold,
max_trials=max_trials,
**kwargs
)
matches = matches[inliers]
return model, matches
def extract_features(image_collection_raw, image_collection, profile=True):
"""
Match keypoints of each image pair by their descriptors.
"""
sfm_storage = SFMStorage()
for i in range(len(image_collection)):
a = ImagePose()
a.img = image_collection_raw[i]
if profile: beg = time.time()
img = image_collection[i]
keypoints, a.desc = detect_kp_desc(img)
a.kp = keypoints[:,::-1] # !!! because we need (x,y), not (y,x)
if profile: print('Detect time:', time.time() - beg)
sfm_storage.img_pose.append(a)
return sfm_storage
def match_pairwise(sfm_storage, vis_matches, profile=True):
"""
Match keypoints of each image pair by their descriptors.
sfm_storage:
`SFMStorage` instance
vis_matches:
bool
Whether to draw the matches
profile:
bool
Whether to measure execution time
return:
`SFMStorage` instance
`SFMStorage` instance filled with matches information
"""
for i in range(len(sfm_storage.img_pose)):
for j in range(i+1, len(sfm_storage.img_pose)):
# detect features and extract descriptors
src_keypoints, src_descriptors = sfm_storage.img_pose[i].kp, sfm_storage.img_pose[i].desc
dest_keypoints, dest_descriptors = sfm_storage.img_pose[j].kp, sfm_storage.img_pose[j].desc
# RANSAC outlier filtering
if profile: beg = time.time()
robust_transform, matches = match_robust(
src_keypoints, src_descriptors,
dest_keypoints, dest_descriptors,
method='flann',
min_samples=4,
residual_threshold=100,
max_trials=3000,
)
if profile: print('Match and RANSAC time:', time.time() - beg)
# save img1-kp1-img2-kp2 matches to global helper SFM instance
for m in matches:
sfm_storage.img_pose[i].kp_matches[(m[0], j)] = m[1]
sfm_storage.img_pose[j].kp_matches[(m[1], i)] = m[0]
print(f"Feature matching: image {i} <-> image {j} ==> {len(matches)} matches")
# vis
if vis_matches:
plt.figure(figsize=FIGSIZE)
ax = plt.axes()
ax.axis("off")
ax.set_title(f"Inlier correspondences: {len(matches)} points matched")
plot_matches(
ax,
sfm_storage.img_pose[i].img,
sfm_storage.img_pose[j].img,
src_keypoints[:,::-1],
dest_keypoints[:,::-1],
matches
)
plt.show();
return sfm_storage
def match_sequential(sfm_storage, vis_matches, profile=True):
"""
Match keypoints of each image pair by their descriptors
"""
for i in range(len(sfm_storage.img_pose)-1):
j = i+1
# detect features and extract descriptors
src_keypoints, src_descriptors = sfm_storage.img_pose[i].kp, sfm_storage.img_pose[i].desc
dest_keypoints, dest_descriptors = sfm_storage.img_pose[j].kp, sfm_storage.img_pose[j].desc
# RANSAC outlier filtering
if profile: beg = time.time()
robust_transform, matches = match_robust(
src_keypoints, src_descriptors,
dest_keypoints, dest_descriptors,
method='flann',
min_samples=4,
residual_threshold=100,
max_trials=3000,
)
print(matches.shape)
if profile: print('Match and RANSAC time:', time.time() - beg)
# save img1-kp1-img2-kp2 matches to global helper SFM instance
for m in matches:
sfm_storage.img_pose[i].kp_matches[(m[0], j)] = m[1]
sfm_storage.img_pose[j].kp_matches[(m[1], i)] = m[0]
print(f"Feature matching: image {i} <-> image {j} ==> {len(matches)} matches")
# vis
FIGSIZE = (15, 10)
if vis_matches:
plt.figure(figsize=FIGSIZE)
ax = plt.axes()
ax.axis("off")
ax.set_title(f"Inlier correspondences: {len(matches)} points matched")
plot_matches(
ax,
sfm_storage.img_pose[i].img,
sfm_storage.img_pose[j].img,
src_keypoints[:,::-1], # !!!
dest_keypoints[:,::-1], # !!!
matches
)
plt.show();
return sfm_storage
def detect_and_match(
image_collection_raw,
match_type='sequential',
vis_matches=False
):
image_collection = [x.astype(np.float64) / 255. for x in image_collection_raw]
sfm_storage = SFMStorage()
sfm_storage = extract_features(image_collection_raw, image_collection)
if match_type == 'pairwise':
sfm_storage = match_pairwise(sfm_storage, vis_matches)
elif match_type == 'sequential':
sfm_storage = match_sequential(sfm_storage, vis_matches)
return sfm_storage