Upload folder using huggingface_hub
Browse files- colmap_matcher.sh +2 -2
- feature_matcher.py +359 -0
- feature_matcher_utilities.py +140 -0
colmap_matcher.sh
CHANGED
|
@@ -144,9 +144,9 @@ then
|
|
| 144 |
fi
|
| 145 |
|
| 146 |
# LightGlue Feature Matcher
|
| 147 |
-
if [ "${matcher_type}" == "
|
| 148 |
then
|
| 149 |
-
pixi run -e lightglue python3 Baselines/colmap/
|
| 150 |
colmap matches_importer \
|
| 151 |
--database_path ${database} \
|
| 152 |
--match_list_path "${exp_folder_colmap}/matches.txt" \
|
|
|
|
| 144 |
fi
|
| 145 |
|
| 146 |
# LightGlue Feature Matcher
|
| 147 |
+
if [ "${matcher_type}" == "custom" ]
|
| 148 |
then
|
| 149 |
+
pixi run -e lightglue python3 Baselines/colmap/feature_matcher.py --database ${database} --rgb_path ${rgb_path} --feature superpoint --matcher lightglue --use_gpu ${use_gpu}
|
| 150 |
colmap matches_importer \
|
| 151 |
--database_path ${database} \
|
| 152 |
--match_list_path "${exp_folder_colmap}/matches.txt" \
|
feature_matcher.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
from feature_matcher_utilities import extract_keypoints, feature_matching, unrotate_kps_W
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import numpy as np
|
| 8 |
+
import cv2
|
| 9 |
+
import argparse
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from lightglue import LightGlue
|
| 13 |
+
|
| 14 |
+
# ==========================================
|
| 15 |
+
# ==========================================
|
| 16 |
+
# DATABASE UTILITIES
|
| 17 |
+
# ==========================================
|
| 18 |
+
def load_colmap_db(db_path):
|
| 19 |
+
if not os.path.exists(db_path):
|
| 20 |
+
raise FileNotFoundError(f"Database file not found: {db_path}")
|
| 21 |
+
conn = sqlite3.connect(db_path)
|
| 22 |
+
cursor = conn.cursor()
|
| 23 |
+
return conn, cursor
|
| 24 |
+
|
| 25 |
+
def create_pair_id(image_id1, image_id2):
|
| 26 |
+
if image_id1 > image_id2:
|
| 27 |
+
image_id1, image_id2 = image_id2, image_id1
|
| 28 |
+
return image_id1 * 2147483647 + image_id2
|
| 29 |
+
|
| 30 |
+
def clean_database(cursor):
|
| 31 |
+
"""Removes existing features and matches to ensure a clean overwrite."""
|
| 32 |
+
tables = ["keypoints", "descriptors"]#, "matches"], "two_view_geometry"]
|
| 33 |
+
for table in tables:
|
| 34 |
+
cursor.execute(f"DELETE FROM {table};")
|
| 35 |
+
print("Database cleaned (keypoints, descriptors, matches removed).")
|
| 36 |
+
|
| 37 |
+
def insert_keypoints(cursor, image_id, keypoints, descriptors):
|
| 38 |
+
"""
|
| 39 |
+
keypoints: (N, 2) numpy array, float32
|
| 40 |
+
descriptors: (N, D) numpy array, float32
|
| 41 |
+
"""
|
| 42 |
+
keypoints_blob = keypoints.tobytes()
|
| 43 |
+
descriptors_blob = descriptors.tobytes()
|
| 44 |
+
|
| 45 |
+
# Keypoints
|
| 46 |
+
cursor.execute(
|
| 47 |
+
"INSERT INTO keypoints(image_id, rows, cols, data) VALUES(?, ?, ?, ?)",
|
| 48 |
+
(image_id, keypoints.shape[0], keypoints.shape[1], keypoints_blob)
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Descriptors (Optional but good practice)
|
| 52 |
+
cursor.execute(
|
| 53 |
+
"INSERT INTO descriptors(image_id, rows, cols, data) VALUES(?, ?, ?, ?)",
|
| 54 |
+
(image_id, descriptors.shape[0], descriptors.shape[1], descriptors_blob)
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def insert_matches(cursor, image_id1, image_id2, matches):
|
| 58 |
+
"""
|
| 59 |
+
matches: (K, 2) numpy array, uint32.
|
| 60 |
+
Col 0 is index in image1, Col 1 is index in image2
|
| 61 |
+
"""
|
| 62 |
+
pair_id = create_pair_id(image_id1, image_id2)
|
| 63 |
+
matches_blob = matches.tobytes()
|
| 64 |
+
|
| 65 |
+
cursor.execute(
|
| 66 |
+
"INSERT INTO matches(pair_id, rows, cols, data) VALUES(?, ?, ?, ?)",
|
| 67 |
+
(pair_id, matches.shape[0], matches.shape[1], matches_blob)
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def verify_matches_visual(cursor, image_id1, image_id2, image_dir):
|
| 71 |
+
"""
|
| 72 |
+
Reads matches and keypoints from the COLMAP db and plots them.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
cursor: SQLite cursor connected to the database.
|
| 76 |
+
image_id1: ID of the first image.
|
| 77 |
+
image_id2: ID of the second image.
|
| 78 |
+
image_dir: Path to the directory containing the images.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
# 1. Helper to ensure image_id1 < image_id2 for pair_id calculation
|
| 82 |
+
if image_id1 > image_id2:
|
| 83 |
+
image_id1, image_id2 = image_id2, image_id1
|
| 84 |
+
swapped = True
|
| 85 |
+
else:
|
| 86 |
+
swapped = False
|
| 87 |
+
|
| 88 |
+
pair_id = image_id1 * 2147483647 + image_id2
|
| 89 |
+
|
| 90 |
+
# 2. Fetch Matches
|
| 91 |
+
cursor.execute("SELECT data FROM matches WHERE pair_id = ?", (pair_id,))
|
| 92 |
+
match_row = cursor.fetchone()
|
| 93 |
+
|
| 94 |
+
if match_row is None:
|
| 95 |
+
print(f"No matches found in DB for pair {image_id1}-{image_id2}")
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
# Decode Matches: UINT32 (N, 2)
|
| 99 |
+
matches = np.frombuffer(match_row[0], dtype=np.uint32).reshape(-1, 2)
|
| 100 |
+
|
| 101 |
+
# If we swapped inputs to generate pair_id, we must swap columns in matches
|
| 102 |
+
# so matches[:,0] corresponds to the requested image_id1
|
| 103 |
+
if swapped:
|
| 104 |
+
matches = matches[:, [1, 0]]
|
| 105 |
+
|
| 106 |
+
# 3. Fetch Keypoints for both images
|
| 107 |
+
def get_keypoints_and_name(img_id):
|
| 108 |
+
# Get Name
|
| 109 |
+
cursor.execute("SELECT name FROM images WHERE image_id = ?", (img_id,))
|
| 110 |
+
name = cursor.fetchone()[0]
|
| 111 |
+
|
| 112 |
+
# Get Keypoints
|
| 113 |
+
cursor.execute("SELECT data FROM keypoints WHERE image_id = ?", (img_id,))
|
| 114 |
+
kp_row = cursor.fetchone()
|
| 115 |
+
# Decode Keypoints: FLOAT32 (N, 2)
|
| 116 |
+
kpts = np.frombuffer(kp_row[0], dtype=np.float32).reshape(-1, 2)
|
| 117 |
+
return name, kpts
|
| 118 |
+
|
| 119 |
+
name1, kpts1 = get_keypoints_and_name(image_id1)
|
| 120 |
+
name2, kpts2 = get_keypoints_and_name(image_id2)
|
| 121 |
+
|
| 122 |
+
# 4. Filter Keypoints using the Matches indices
|
| 123 |
+
# matches[:, 0] are indices into kpts1
|
| 124 |
+
# matches[:, 1] are indices into kpts2
|
| 125 |
+
valid_kpts1 = kpts1[matches[:, 0]]
|
| 126 |
+
valid_kpts2 = kpts2[matches[:, 1]]
|
| 127 |
+
|
| 128 |
+
# 5. Load Images
|
| 129 |
+
path1 = os.path.join(image_dir, name1)
|
| 130 |
+
path2 = os.path.join(image_dir, name2)
|
| 131 |
+
|
| 132 |
+
img1 = cv2.imread(path1)
|
| 133 |
+
img2 = cv2.imread(path2)
|
| 134 |
+
|
| 135 |
+
# Convert BGR (OpenCV) to RGB (Matplotlib)
|
| 136 |
+
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
|
| 137 |
+
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
|
| 138 |
+
|
| 139 |
+
# 6. Plotting
|
| 140 |
+
# Concatenate images side-by-side
|
| 141 |
+
h1, w1, _ = img1.shape
|
| 142 |
+
h2, w2, _ = img2.shape
|
| 143 |
+
|
| 144 |
+
# Create a canvas large enough for both
|
| 145 |
+
height = max(h1, h2)
|
| 146 |
+
width = w1 + w2
|
| 147 |
+
canvas = np.zeros((height, width, 3), dtype=np.uint8)
|
| 148 |
+
|
| 149 |
+
canvas[:h1, :w1, :] = img1
|
| 150 |
+
canvas[:h2, w1:w1+w2, :] = img2
|
| 151 |
+
|
| 152 |
+
plt.figure(figsize=(15, 10))
|
| 153 |
+
plt.imshow(canvas)
|
| 154 |
+
|
| 155 |
+
# Plot lines
|
| 156 |
+
# Shift x-coordinates of image2 by w1
|
| 157 |
+
for (x1, y1), (x2, y2) in zip(valid_kpts1, valid_kpts2):
|
| 158 |
+
plt.plot([x1, x2 + w1], [y1, y2], 'c-', alpha=0.6, linewidth=0.5)
|
| 159 |
+
plt.plot(x1, y1, 'r.', markersize=2)
|
| 160 |
+
plt.plot(x2 + w1, y2, 'r.', markersize=2)
|
| 161 |
+
|
| 162 |
+
plt.title(f"DB Verification: {name1} (ID:{image_id1}) <-> {name2} (ID:{image_id2}) | Matches: {len(matches)}")
|
| 163 |
+
plt.axis('off')
|
| 164 |
+
plt.tight_layout()
|
| 165 |
+
plt.show()
|
| 166 |
+
|
| 167 |
+
import numpy as np
|
| 168 |
+
import matplotlib.pyplot as plt
|
| 169 |
+
import cv2
|
| 170 |
+
import os
|
| 171 |
+
import sqlite3
|
| 172 |
+
|
| 173 |
+
def plot_matches_from_db(cursor, image_id1, image_id2, image_dir):
|
| 174 |
+
"""
|
| 175 |
+
Reads matches and keypoints for a specific pair from the COLMAP DB and plots them.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
cursor: SQLite cursor.
|
| 179 |
+
image_id1, image_id2: The IDs of the two images to plot.
|
| 180 |
+
image_dir: Path to the directory containing the actual image files.
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
# 1. Resolve Pair ID (Colmap requires id1 < id2 for unique pair_id)
|
| 184 |
+
if image_id1 > image_id2:
|
| 185 |
+
id_a, id_b = image_id2, image_id1
|
| 186 |
+
swapped = True
|
| 187 |
+
else:
|
| 188 |
+
id_a, id_b = image_id1, image_id2
|
| 189 |
+
swapped = False
|
| 190 |
+
|
| 191 |
+
pair_id = id_a * 2147483647 + id_b
|
| 192 |
+
|
| 193 |
+
# 2. Fetch Matches
|
| 194 |
+
print(f"Fetching matches for pair {image_id1}-{image_id2} (PairID: {pair_id})...")
|
| 195 |
+
cursor.execute("SELECT data, rows, cols FROM matches WHERE pair_id = ?", (pair_id,))
|
| 196 |
+
match_row = cursor.fetchone()
|
| 197 |
+
|
| 198 |
+
if match_row is None:
|
| 199 |
+
print(f"No matches found in database for Pair {image_id1}-{image_id2}")
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
# Decode Matches (UINT32)
|
| 203 |
+
# Blob is match_row[0], rows is [1], cols is [2]
|
| 204 |
+
matches_blob = match_row[0]
|
| 205 |
+
matches = np.frombuffer(matches_blob, dtype=np.uint32).reshape(-1, 2)
|
| 206 |
+
|
| 207 |
+
# If inputs were swapped relative to how COLMAP stores them, swap the columns
|
| 208 |
+
# so matches[:,0] refers to image_id1 and matches[:,1] refers to image_id2
|
| 209 |
+
if swapped:
|
| 210 |
+
matches = matches[:, [1, 0]]
|
| 211 |
+
|
| 212 |
+
# 3. Fetch Keypoints & Image Names
|
| 213 |
+
def get_image_data(img_id):
|
| 214 |
+
cursor.execute("SELECT name FROM images WHERE image_id = ?", (img_id,))
|
| 215 |
+
res = cursor.fetchone()
|
| 216 |
+
if not res:
|
| 217 |
+
raise ValueError(f"Image ID {img_id} not found in 'images' table.")
|
| 218 |
+
name = res[0]
|
| 219 |
+
|
| 220 |
+
cursor.execute("SELECT data FROM keypoints WHERE image_id = ?", (img_id,))
|
| 221 |
+
kp_res = cursor.fetchone()
|
| 222 |
+
if not kp_res:
|
| 223 |
+
raise ValueError(f"No keypoints found for Image ID {img_id}.")
|
| 224 |
+
|
| 225 |
+
# Decode Keypoints (FLOAT32)
|
| 226 |
+
kpts = np.frombuffer(kp_res[0], dtype=np.float32).reshape(-1, 2)
|
| 227 |
+
return name, kpts
|
| 228 |
+
|
| 229 |
+
name1, kpts1 = get_image_data(image_id1)
|
| 230 |
+
name2, kpts2 = get_image_data(image_id2)
|
| 231 |
+
|
| 232 |
+
# 4. Filter Keypoints using Match Indices
|
| 233 |
+
valid_kpts1 = kpts1[matches[:, 0]]
|
| 234 |
+
valid_kpts2 = kpts2[matches[:, 1]]
|
| 235 |
+
|
| 236 |
+
# 5. Visualization
|
| 237 |
+
path1 = os.path.join(image_dir, name1)
|
| 238 |
+
path2 = os.path.join(image_dir, name2)
|
| 239 |
+
|
| 240 |
+
if not os.path.exists(path1) or not os.path.exists(path2):
|
| 241 |
+
print(f"Error: Could not find image files at \n{path1}\n{path2}")
|
| 242 |
+
return
|
| 243 |
+
|
| 244 |
+
img1 = cv2.imread(path1)
|
| 245 |
+
img2 = cv2.imread(path2)
|
| 246 |
+
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
|
| 247 |
+
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
|
| 248 |
+
|
| 249 |
+
# Create canvas
|
| 250 |
+
h1, w1 = img1.shape[:2]
|
| 251 |
+
h2, w2 = img2.shape[:2]
|
| 252 |
+
height = max(h1, h2)
|
| 253 |
+
width = w1 + w2
|
| 254 |
+
canvas = np.zeros((height, width, 3), dtype=np.uint8)
|
| 255 |
+
canvas[:h1, :w1] = img1
|
| 256 |
+
canvas[:h2, w1:w1+w2] = img2
|
| 257 |
+
|
| 258 |
+
plt.figure(figsize=(20, 10))
|
| 259 |
+
plt.imshow(canvas)
|
| 260 |
+
|
| 261 |
+
# Plot matches
|
| 262 |
+
# x2 coordinates need to be shifted by w1
|
| 263 |
+
for (x1, y1), (x2, y2) in zip(valid_kpts1, valid_kpts2):
|
| 264 |
+
plt.plot([x1, x2 + w1], [y1, y2], 'g-', alpha=0.5, linewidth=1.5)
|
| 265 |
+
plt.plot(x1, y1, 'r.', markersize=4)
|
| 266 |
+
plt.plot(x2 + w1, y2, 'r.', markersize=4)
|
| 267 |
+
|
| 268 |
+
plt.title(f"{name1} <-> {name2} | Total Matches: {len(matches)}")
|
| 269 |
+
plt.axis('off')
|
| 270 |
+
plt.tight_layout()
|
| 271 |
+
plt.show()
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
|
| 275 |
+
parser = argparse.ArgumentParser()
|
| 276 |
+
|
| 277 |
+
parser.add_argument("--database", type=Path, required=True)
|
| 278 |
+
parser.add_argument("--rgb_path", type=Path, required=True)
|
| 279 |
+
parser.add_argument("--feature", type=str, required=True)
|
| 280 |
+
parser.add_argument("--matcher", type=str, required=True)
|
| 281 |
+
|
| 282 |
+
args, _ = parser.parse_known_args()
|
| 283 |
+
|
| 284 |
+
DB_PATH = args.database
|
| 285 |
+
IMAGE_DIR = args.rgb_path
|
| 286 |
+
FEATURE_TYPE = args.feature
|
| 287 |
+
MATCHER_TYPE = args.matcher
|
| 288 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 289 |
+
matches_file_path = os.path.join(os.path.dirname(DB_PATH), "matches.txt")
|
| 290 |
+
|
| 291 |
+
conn, cursor = load_colmap_db(DB_PATH)
|
| 292 |
+
cursor.execute("SELECT image_id, name FROM images")
|
| 293 |
+
images_info = {row[0]: row[1] for row in cursor.fetchall()}
|
| 294 |
+
image_ids = sorted(images_info.keys())
|
| 295 |
+
|
| 296 |
+
clean_database(cursor)
|
| 297 |
+
conn.commit()
|
| 298 |
+
|
| 299 |
+
# Keypoint Extraction
|
| 300 |
+
fts = {}
|
| 301 |
+
for i in tqdm(range(len(image_ids)), desc="Feature Extraction"):
|
| 302 |
+
id = image_ids[i]
|
| 303 |
+
fname = images_info[id]
|
| 304 |
+
path = os.path.join(IMAGE_DIR, fname)
|
| 305 |
+
|
| 306 |
+
feats_dict, h, w = extract_keypoints(path, features=FEATURE_TYPE)
|
| 307 |
+
|
| 308 |
+
fts[id] = feats_dict
|
| 309 |
+
|
| 310 |
+
kpts = feats_dict['keypoints'].squeeze(0).cpu().numpy().astype(np.float32)
|
| 311 |
+
descs = feats_dict['descriptors'].squeeze(0).cpu().numpy().astype(np.float32)
|
| 312 |
+
|
| 313 |
+
if FEATURE_TYPE == 'superpoint':
|
| 314 |
+
kpts_rot = unrotate_kps_W(kpts, feats_dict['rotations'].squeeze(0).cpu().numpy().astype(np.float32), h, w)
|
| 315 |
+
else:
|
| 316 |
+
kpts_rot = kpts
|
| 317 |
+
insert_keypoints(cursor, id, kpts_rot, descs)
|
| 318 |
+
|
| 319 |
+
conn.commit()
|
| 320 |
+
|
| 321 |
+
# Feature Matching
|
| 322 |
+
if MATCHER_TYPE == 'lightglue':
|
| 323 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 324 |
+
matcher = LightGlue(features='superpoint', depth_confidence=-1, width_confidence=-1, flash=True).eval().to(device)
|
| 325 |
+
else:
|
| 326 |
+
matcher = None
|
| 327 |
+
|
| 328 |
+
with open(matches_file_path, "w") as f_match:
|
| 329 |
+
for i in tqdm(range(len(image_ids)), desc="Feature Extraction"):
|
| 330 |
+
id1 = image_ids[i]
|
| 331 |
+
fname1 = images_info[id1]
|
| 332 |
+
path1 = os.path.join(IMAGE_DIR, fname1)
|
| 333 |
+
|
| 334 |
+
for j in range(i + 1, len(image_ids)):
|
| 335 |
+
if j == i:
|
| 336 |
+
continue
|
| 337 |
+
id2 = image_ids[j]
|
| 338 |
+
|
| 339 |
+
fname2 = images_info[id2]
|
| 340 |
+
path2 = os.path.join(IMAGE_DIR, fname2)
|
| 341 |
+
matches_tensor = feature_matching(fts[id1], fts[id2], matcher=matcher, features=FEATURE_TYPE, matcher_type=MATCHER_TYPE)
|
| 342 |
+
|
| 343 |
+
if matches_tensor is not None and len(matches_tensor) > 0:
|
| 344 |
+
matches_np = matches_tensor.cpu().numpy().astype(np.uint32)
|
| 345 |
+
#insert_matches(cursor, id1, id2, matches_np)
|
| 346 |
+
|
| 347 |
+
f_match.write(f"{fname1} {fname2}\n")
|
| 348 |
+
np.savetxt(f_match, matches_np, fmt="%d")
|
| 349 |
+
f_match.write("\n")
|
| 350 |
+
|
| 351 |
+
#verify_matches_visual(cursor, image_ids[i], image_ids[j], IMAGE_DIR)
|
| 352 |
+
#plt.show()
|
| 353 |
+
|
| 354 |
+
conn.commit()
|
| 355 |
+
|
| 356 |
+
#plot_matches_from_db(cursor, image_ids[0], image_ids[1], IMAGE_DIR)
|
| 357 |
+
|
| 358 |
+
conn.close()
|
| 359 |
+
print("Database overwrite complete.")
|
feature_matcher_utilities.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
from lightglue import LightGlue
|
| 5 |
+
from lightglue.utils import rbd
|
| 6 |
+
from lightglue import SuperPoint, SIFT
|
| 7 |
+
from lightglue.utils import load_image
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def unrotate_kps_W(kps_rot, k, H, W):
|
| 11 |
+
# Ensure inputs are Numpy
|
| 12 |
+
if hasattr(kps_rot, 'cpu'): kps_rot = kps_rot.cpu().numpy()
|
| 13 |
+
if hasattr(k, 'cpu'): k = k.cpu().numpy()
|
| 14 |
+
|
| 15 |
+
# Squeeze if necessary
|
| 16 |
+
if k.ndim > 1: k = k.squeeze()
|
| 17 |
+
if kps_rot.ndim > 2: kps_rot = kps_rot.squeeze()
|
| 18 |
+
|
| 19 |
+
x_r = kps_rot[:, 0]
|
| 20 |
+
y_r = kps_rot[:, 1]
|
| 21 |
+
|
| 22 |
+
x = np.zeros_like(x_r)
|
| 23 |
+
y = np.zeros_like(y_r)
|
| 24 |
+
|
| 25 |
+
mask0 = (k == 0)
|
| 26 |
+
x[mask0], y[mask0] = x_r[mask0], y_r[mask0]
|
| 27 |
+
|
| 28 |
+
mask1 = (k == 1)
|
| 29 |
+
x[mask1], y[mask1] = (W - 1) - y_r[mask1], x_r[mask1]
|
| 30 |
+
|
| 31 |
+
mask2 = (k == 2)
|
| 32 |
+
x[mask2], y[mask2] = (W - 1) - x_r[mask2], (H - 1) - y_r[mask2]
|
| 33 |
+
|
| 34 |
+
mask3 = (k == 3)
|
| 35 |
+
x[mask3], y[mask3] = y_r[mask3], (H - 1) - x_r[mask3]
|
| 36 |
+
|
| 37 |
+
return np.stack([x, y], axis=-1)
|
| 38 |
+
|
| 39 |
+
def extract_keypoints(path_to_image0, features='superpoint', rotations = [0,1,2,3]):
|
| 40 |
+
# --- Models on GPU ---
|
| 41 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 42 |
+
|
| 43 |
+
# --- Load images as Torch tensors (3,H,W) in [0,1] ---
|
| 44 |
+
timg = load_image(path_to_image0).to(device)
|
| 45 |
+
_, h, w = timg.shape
|
| 46 |
+
|
| 47 |
+
if features == 'sift':
|
| 48 |
+
extractor = SIFT(max_num_keypoints=2048).eval().to(device)
|
| 49 |
+
feats = extractor.extract(timg)
|
| 50 |
+
return feats , h, w
|
| 51 |
+
|
| 52 |
+
if features == 'superpoint':
|
| 53 |
+
extractor = SuperPoint(max_num_keypoints=2048).eval().to(device)
|
| 54 |
+
|
| 55 |
+
# --- Extract local features ---
|
| 56 |
+
feats = {}
|
| 57 |
+
for k in (rotations):
|
| 58 |
+
timg_rotated = torch.rot90(timg, k, dims=(1, 2))
|
| 59 |
+
feats[k] = extractor.extract(timg_rotated)
|
| 60 |
+
#print(f"Extracted {feats[k]['keypoints'].shape[1]} keypoints for rotation {k}")
|
| 61 |
+
|
| 62 |
+
# --- Merge features back to original coordinate system ---
|
| 63 |
+
all_keypoints = []
|
| 64 |
+
all_scores = []
|
| 65 |
+
all_descriptors = []
|
| 66 |
+
all_rotations = []
|
| 67 |
+
for k, feat in feats.items():
|
| 68 |
+
kpts = feat['keypoints'] # Shape (1, N, 2)
|
| 69 |
+
num_kpts = kpts.shape[1]
|
| 70 |
+
# if k == 0:
|
| 71 |
+
# kpts_corrected = kpts
|
| 72 |
+
# elif k == 1:
|
| 73 |
+
# kpts_corrected = torch.stack(
|
| 74 |
+
# [w - 1 - kpts[..., 1], kpts[..., 0]], dim=-1
|
| 75 |
+
# )
|
| 76 |
+
# elif k == 2:
|
| 77 |
+
# kpts_corrected = torch.stack(
|
| 78 |
+
# [w - 1 - kpts[..., 0], h - 1 - kpts[..., 1]], dim=-1
|
| 79 |
+
# )
|
| 80 |
+
# elif k == 3:
|
| 81 |
+
# kpts_corrected = torch.stack(
|
| 82 |
+
# [kpts[..., 1], h - 1 - kpts[..., 0]], dim=-1
|
| 83 |
+
# )
|
| 84 |
+
|
| 85 |
+
rot_indices = torch.full((1, num_kpts), k, dtype=torch.long, device=device)
|
| 86 |
+
all_keypoints.append(feat['keypoints'])
|
| 87 |
+
all_scores.append(feat['keypoint_scores'])
|
| 88 |
+
all_descriptors.append(feat['descriptors'])
|
| 89 |
+
all_rotations.append(rot_indices)
|
| 90 |
+
|
| 91 |
+
# Concatenate all features along the keypoint dimension (dim=1)
|
| 92 |
+
feats_merged = {
|
| 93 |
+
'keypoints': torch.cat(all_keypoints, dim=1),
|
| 94 |
+
'keypoint_scores': torch.cat(all_scores, dim=1),
|
| 95 |
+
'descriptors': torch.cat(all_descriptors, dim=1),
|
| 96 |
+
'rotations': torch.cat(all_rotations, dim=1)
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
num_kpts = feats_merged['keypoints'].shape[1]
|
| 100 |
+
# perm = torch.randperm(num_kpts, device=device)
|
| 101 |
+
|
| 102 |
+
# feats_merged['keypoints'] = feats_merged['keypoints'][:, perm, :]
|
| 103 |
+
# feats_merged['keypoint_scores'] = feats_merged['keypoint_scores'][:, perm]
|
| 104 |
+
# feats_merged['descriptors'] = feats_merged['descriptors'][:, perm, :]
|
| 105 |
+
|
| 106 |
+
# Optional: If you want to retain other keys like 'shape' or 'image_size'
|
| 107 |
+
#feats_merged['image_size'] = torch.tensor([w, h], device=device).unsqueeze(0)
|
| 108 |
+
#feats_merged['scales'] = torch.tensor([w, h], device=device).unsqueeze(0)
|
| 109 |
+
|
| 110 |
+
# for f in feats_merged:
|
| 111 |
+
# if 'scales' not in f:
|
| 112 |
+
# f['scales'] = torch.ones(all_keypoints.shape[:-1], device=device)
|
| 113 |
+
# if 'oris' not in f:
|
| 114 |
+
# f['oris'] = torch.zeros(all_keypoints.shape[:-1], device=device)
|
| 115 |
+
|
| 116 |
+
return feats_merged , h, w
|
| 117 |
+
|
| 118 |
+
def feature_matching(feats0, feats1, matcher = None, features='superpoint', matcher_type='lightglue'):
|
| 119 |
+
#print(f"Matching features using {matcher_type} matcher with {features} features.")
|
| 120 |
+
if matcher_type == "lightglue":
|
| 121 |
+
if matcher is None:
|
| 122 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 123 |
+
matcher = LightGlue(features=features).eval().to(device)
|
| 124 |
+
|
| 125 |
+
out_k = matcher({'image0': feats0, 'image1': feats1})
|
| 126 |
+
_, _, out_k = [rbd(x) for x in [feats0, feats1, out_k]] # remove batch dim
|
| 127 |
+
return out_k['matches']
|
| 128 |
+
|
| 129 |
+
if matcher_type == "brute_force":
|
| 130 |
+
desc0 = feats0['descriptors'].squeeze(0)
|
| 131 |
+
desc1 = feats1['descriptors'].squeeze(0)
|
| 132 |
+
dists = torch.cdist(desc0, desc1, p=2)
|
| 133 |
+
min_dist0, idx0 = dists.min(dim=1)
|
| 134 |
+
min_dist1, idx1 = dists.min(dim=0)
|
| 135 |
+
indices0 = torch.arange(len(idx0), device='cuda')
|
| 136 |
+
mutual_mask = (idx1[idx0] == indices0)
|
| 137 |
+
matches0 = indices0[mutual_mask]
|
| 138 |
+
matches1 = idx0[mutual_mask]
|
| 139 |
+
|
| 140 |
+
return torch.stack([matches0, matches1], dim=-1) # [N, 2]
|