fangmingguo commited on
Commit
928c066
·
verified ·
1 Parent(s): b8f3639

Upload infer.py

Browse files
Files changed (1) hide show
  1. infer.py +164 -0
infer.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import numpy as np
3
+ import cv2
4
+ import axengine as axe
5
+
6
+ def parse_args() -> argparse.Namespace:
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument("--model", type=str, required=True, help="Path to the axmodel")
9
+ parser.add_argument("--img1", type=str, required=True, help="Path to the first image")
10
+ parser.add_argument("--img2", type=str, required=True, help="Path to the second image")
11
+ parser.add_argument("--output", type=str, default="matches.jpg", help="The output image directory")
12
+ parser.add_argument("--threshold", type=float, default=0.005, help="The keypoint threshold")
13
+ parser.add_argument("--max_points", type=int, default=100, help="The max num for keypoints")
14
+ return parser.parse_args()
15
+
16
+ def preprocess_image(path: str, h: int, w: int):
17
+ img = cv2.imread(path)
18
+ raw_h, raw_w = img.shape[:2]
19
+
20
+ if (raw_h, raw_w) != (h, w):
21
+ img = cv2.resize(img, (w, h))
22
+ scale_h = raw_h / h
23
+ scale_w = raw_w / w
24
+ else:
25
+ scale_h = 1.0
26
+ scale_w = 1.0
27
+
28
+ img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
29
+ img_tensor = img_gray.astype(np.float32) / 255.0
30
+ img_tensor = img_tensor[None, None, :, :] # -> (1, 1, H, W)
31
+
32
+ return img_tensor, img, (scale_h, scale_w)
33
+
34
+ def get_keypoints(score_map, threshold):
35
+ row, col = np.where(score_map > threshold) # y, x
36
+ if len(row) == 0:
37
+ return np.zeros((0, 2), dtype=np.float32), np.zeros((0,), dtype=np.float32)
38
+
39
+ scores = score_map[row, col]
40
+ keypoints = np.stack([col, row], axis=1).astype(np.float32)
41
+ return keypoints, scores
42
+
43
+ def get_descriptors(kp, desc_map):
44
+ if len(kp) == 0:
45
+ return np.zeros((0, 256), dtype=np.float32)
46
+
47
+ c, h, w = desc_map.shape
48
+ x = kp[:, 0] / 8.0
49
+ y = kp[:, 1] / 8.0
50
+
51
+ x0 = np.floor(x).astype(np.int32)
52
+ x1 = x0 + 1
53
+ y0 = np.floor(y).astype(np.int32)
54
+ y1 = y0 + 1
55
+
56
+ x0 = np.clip(x0, 0, w - 1)
57
+ x1 = np.clip(x1, 0, w - 1)
58
+ y0 = np.clip(y0, 0, h - 1)
59
+ y1 = np.clip(y1, 0, h - 1)
60
+
61
+ wa = (x1 - x) * (y1 - y)
62
+ wb = (x1 - x) * (y - y0)
63
+ wc = (x - x0) * (y1 - y)
64
+ wd = (x - x0) * (y - y0)
65
+
66
+ wa = wa[None, :]
67
+ wb = wb[None, :]
68
+ wc = wc[None, :]
69
+ wd = wd[None, :]
70
+
71
+ Q_tl = desc_map[:, y0, x0]
72
+ Q_bl = desc_map[:, y1, x0]
73
+ Q_tr = desc_map[:, y0, x1]
74
+ Q_br = desc_map[:, y1, x1]
75
+
76
+ sampled = (Q_tl * wa + Q_bl * wb + Q_tr * wc + Q_br * wd)
77
+ descriptors = sampled.T
78
+ norm = np.linalg.norm(descriptors, axis=1, keepdims=True)
79
+ descriptors = descriptors / (norm + 1e-6)
80
+
81
+ return descriptors.astype(np.float32)
82
+
83
+ def infer(model: str, img1_path: str, img2_path: str, output: str, threshold: float, max_points: int):
84
+ session = axe.InferenceSession(model)
85
+
86
+ # superpoint only have one input
87
+ input_name = session.get_inputs()[0].name # get model input node name
88
+ input_shape = session.get_inputs()[0].shape # get model input shape (1, 1, H, W)
89
+ target_h, target_w = input_shape[2], input_shape[3]
90
+ print(f"Inference resolution: {target_w}x{target_h}")
91
+
92
+ # preprocess images
93
+ input_tensor1, img1, scale1 = preprocess_image(img1_path, target_h, target_w)
94
+ input_tensor2, img2, scale2 = preprocess_image(img2_path, target_h, target_w)
95
+
96
+ res1 = session.run(None, {input_name: input_tensor1})
97
+ res2 = session.run(None, {input_name: input_tensor2})
98
+
99
+ # [1,480,640], [1,256,60,80]
100
+ score_map1, desc1_map = res1[0], res1[1]
101
+ score_map2, desc2_map = res2[0], res2[1]
102
+
103
+ keypoints1, scores1 = get_keypoints(score_map1[0], threshold)
104
+ keypoints2, scores2 = get_keypoints(score_map2[0], threshold)
105
+
106
+ print(f"Found {len(keypoints1)} keypoints in image 1")
107
+ print(f"Found {len(keypoints2)} keypoints in image 2")
108
+
109
+ if len(keypoints1) > max_points:
110
+ idx = np.argsort(scores1)[::-1][:max_points]
111
+ keypoints1 = keypoints1[idx]
112
+ scores1 = scores1[idx]
113
+ if len(keypoints2) > max_points:
114
+ idx = np.argsort(scores2)[::-1][:max_points]
115
+ keypoints2 = keypoints2[idx]
116
+ scores2 = scores2[idx]
117
+
118
+ desc1 = get_descriptors(keypoints1, desc1_map[0])
119
+ desc2 = get_descriptors(keypoints2, desc2_map[0])
120
+
121
+ bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
122
+ matches = bf.match(desc1, desc2)
123
+ matches = sorted(matches, key=lambda x: x.distance)
124
+
125
+ points1 = [cv2.KeyPoint(x, y, 1) for x, y in keypoints1]
126
+ points2 = [cv2.KeyPoint(x, y, 1) for x, y in keypoints2]
127
+
128
+ match_img = cv2.drawMatches(
129
+ img1, points1,
130
+ img2, points2,
131
+ matches, None,
132
+ flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS,
133
+ matchColor=(0, 255, 0)
134
+ )
135
+
136
+ # if len(matches) > 4:
137
+ # pts1 = np.float32([keypoints1[m.queryIdx] for m in matches]).reshape(-1, 1, 2)
138
+ # pts2 = np.float32([keypoints2[m.trainIdx] for m in matches]).reshape(-1, 1, 2)
139
+
140
+ # H, mask = cv2.findHomography(pts1, pts2, cv2.RANSAC, 3.0)
141
+
142
+ # if mask is not None:
143
+ # matches_mask = mask.ravel().tolist()
144
+ # inlier_matches = [m for i, m in enumerate(matches) if matches_mask[i]]
145
+ # print(f"Inliers: {len(inlier_matches)} / {len(matches)}")
146
+
147
+ # inlier_img = cv2.drawMatches(
148
+ # img1, points1,
149
+ # img2, points2,
150
+ # inlier_matches, None,
151
+ # flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS,
152
+ # matchColor=(0, 255, 0)
153
+ # )
154
+ # cv2.imwrite("inliers_" + output, inlier_img)
155
+
156
+ cv2.imwrite(output, match_img)
157
+ print(f"Result saved to {output}")
158
+
159
+ def main():
160
+ args = parse_args()
161
+ infer(args.model, args.img1, args.img2, args.output, args.threshold, args.max_points)
162
+
163
+ if __name__ == '__main__':
164
+ main()