3D-Reconstruction / frames /custom_matcher.py
RatanK's picture
Added custom matching script
925cab1
Raw History Blame Contribute Delete
5.31 kB
import os
import re
import subprocess
from pathlib import Path
COLMAP_BIN = "colmap"
COLMAP_DB = Path("../colmap/global/database.db")
FRAMES_DIR = Path("")
COLMAP_DIR = Path("../colmap")
INTER_MODES = ["inter_01", "inter_all", "inter_indexwise"]
def run(cmd):
print(">> Running:", " ".join(map(str, cmd)))
subprocess.run(cmd, check=True)
def run_feature_extractor(image_dir):
run([
COLMAP_BIN, "feature_extractor",
"--database_path", str(COLMAP_DB),
"--image_path", str(FRAMES_DIR),
"--ImageReader.single_camera_per_folder", "1"
])
def run_matches_importer(image_dir, match_file):
run([
COLMAP_BIN, "matches_importer",
"--database_path", str(COLMAP_DB),
"--match_list_path", str(match_file)
])
def run_mapper(image_dir, image_list, output_dir):
run([
COLMAP_BIN, "mapper",
"--database_path", str(COLMAP_DB),
"--image_path", str(FRAMES_DIR),
"--image_list_path", str(image_list),
"--output_path", str(output_dir)
])
def merge_models(input_dirs, output_dir):
run([
COLMAP_BIN, "model_merger",
"--input_path1", str(input_dirs[0]),
"--input_path2", str(input_dirs[1]),
"--output_path", str(output_dir)
])
def colmap_reconstruct(image_dir, image_list_file, pairs_file, output_dir):
run_feature_extractor(image_dir)
run_matches_importer(image_dir, pairs_file)
run_mapper(image_dir, image_list_file, output_dir)
def get_registered_images_count(model_dir):
model_dir = Path(model_dir)
if not model_dir.exists():
return 0
result = subprocess.run(
[COLMAP_BIN, "model_analyzer", "--path", str(model_dir)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
match = re.search(r"Registered images:\s+(\d+)", result.stderr)
return int(match.group(1)) if match else 0
def best_submodel(path):
subdirs = sorted(Path(path).iterdir())
best, max_count = None, 0
for sub in subdirs:
if sub.is_dir():
count = get_registered_images_count(sub)
if count > max_count:
best, max_count = sub.name, count
return best, max_count
def main(sceneA, sceneB):
sceneA_dir = FRAMES_DIR / sceneA
sceneB_dir = FRAMES_DIR / sceneB
sceneA_out = COLMAP_DIR / sceneA
sceneB_out = COLMAP_DIR / sceneB
# Step 1: Reconstruct intra scenes
for scene_dir, output_dir, scene in [(sceneA_dir, sceneA_out, sceneA), (sceneB_dir, sceneB_out, sceneB)]:
if not output_dir.exists():
os.makedirs(output_dir, exist_ok=True)
print(f"==> Reconstructing intra-scene for {scene}")
colmap_reconstruct(
image_dir=scene_dir,
image_list_file=scene_dir / "images_list.txt",
pairs_file=scene_dir / "image_pairs.txt",
output_dir=output_dir
)
else:
print(f"[✓] Skipping {scene}, already reconstructed.")
# Step 2: Inter modes
inter_base = f"{sceneA}_{sceneB}"
inter_dir = FRAMES_DIR / inter_base
for mode in INTER_MODES:
inter_out = COLMAP_DIR / f"{inter_base}_{mode}"
inter_pairs = inter_dir / f"image_pairs_{mode}.txt"
inter_list = inter_dir / "images_list.txt"
if mode == "inter_indexwise":
if not inter_pairs.exists() or os.path.getsize(inter_pairs) == 0:
print(f"[!] Skipping {mode}: image_pairs file missing or empty.")
continue
if not inter_out.exists():
os.makedirs(inter_out, exist_ok=True)
print(f"==> Reconstructing inter-scene for mode: {mode}")
colmap_reconstruct(
image_dir=inter_dir,
image_list_file=inter_list,
pairs_file=inter_pairs,
output_dir=inter_out
)
else:
print(f"[✓] Skipping inter-mode {mode}, already reconstructed.")
# Step 3: Merging with best subfolders
best_a, _ = best_submodel(sceneA_out)
best_i, _ = best_submodel(inter_out)
best_b, _ = best_submodel(sceneB_out)
merged_out = COLMAP_DIR / f"{inter_base}_merged_{mode}"
if merged_out.exists():
print(f"[✓] Merged model for {mode} already exists.")
else:
print(f"==> Merging {best_a} of {sceneA} + {best_i} of inter → tmp_merge")
tmp_merge = COLMAP_DIR / "tmp_merge"
os.makedirs(tmp_merge, exist_ok=True)
merge_models([sceneA_out / str(best_a), inter_out / str(best_i)], tmp_merge)
print(f"==> Merging tmp_merge + {best_b} of {sceneB} → final merged for {mode}")
os.makedirs(merged_out, exist_ok=True)
merge_models([tmp_merge, sceneB_out / str(best_b)], merged_out)
print(f"==> Cleaning up tmp_merge")
subprocess.run(["rm", "-rf", str(tmp_merge)], check=True)
print(f"==> Merged model for {mode} created at {merged_out}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--sceneA", required=True)
parser.add_argument("--sceneB", required=True)
args = parser.parse_args()
main(args.sceneA, args.sceneB)