use std::collections::HashMap;
use std::path::{Path, PathBuf};
use rayon::prelude::*;
use visloc_rs::io::gps_prior::{
read_exif_gps, spatial_pairs, GpsPriorSet, PriorCoordinates, PriorFrame,
};
use visloc_rs::slam::incremental_sfm::{estimate_position_prior_alignment, SfmPositionPriors};
use visloc_rs::vision::features::sift::{extract_sift, GrayImage, SiftConfig};
use visloc_rs::vision::matching::DescriptorMatch;
use visloc_rs::vision::two_view::{
ConfigurationType, TwoViewCorrespondence, TwoViewGeometryOptions, TwoViewGeometryVerifier,
};
use visloc_rs::{
incremental_sfm, write_colmap_reconstruction_for_3dgs, BruteForceMatcher, Camera,
CrossCheckMatcher, FeatureSet, IncrementalSfmConfig, Matcher, PairwiseMatches, Pose,
};
const IMAGE_SUFFIXES: [&str; 5] = [".png", ".jpg", ".jpeg", ".bmp", ".tiff"];
struct Args {
flags: HashMap<String, String>,
}
impl Args {
fn parse() -> Self {
let mut flags = HashMap::new();
let mut positional: Vec<String> = Vec::new();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if arg.starts_with("--") {
let key = arg.trim_start_matches("--").to_string();
let mut value = String::new();
if let Some(v) = args.next() {
value = v;
}
flags.insert(key, value);
} else {
positional.push(arg);
}
}
if let Some(sub) = positional.first() {
flags.insert("subcommand".to_string(), sub.clone());
}
Self { flags }
}
fn get(&self, key: &str) -> Option<&str> {
self.flags.get(key).map(|s| s.as_str()).or_else(|| {
self.flags
.iter()
.find(|(k, _)| k.ends_with(key))
.map(|(_, v)| v.as_str())
})
}
fn get_or(&self, key: &str, default: &str) -> String {
self.get(key).unwrap_or(default).to_string()
}
fn use_gpu(&self, key: &str) -> Result<bool, String> {
let on = matches!(self.get(key), Some("1") | Some("true") | Some("True"));
if on && !cfg!(feature = "gpu") {
return Err(format!("--{key} needs a build with --features gpu"));
}
Ok(on)
}
}
fn warn_unknown_flags(args: &Args, known: &[&str]) {
for k in args.flags.keys() {
if k == "subcommand" || k == "help" {
continue;
}
if !known.iter().any(|n| k == n || k.ends_with(n)) {
eprintln!("colmap-shim: ignoring unsupported flag --{k}");
}
}
}
fn data_dir(database_path: &Path) -> PathBuf {
let mut name = database_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "db".to_string());
name.push_str(".d");
database_path.parent().unwrap_or(Path::new(".")).join(name)
}
fn list_images(dir: &Path) -> Result<Vec<PathBuf>, String> {
let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
.map_err(|e| format!("cannot read image dir {dir:?}: {e}"))?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| {
p.extension()
.map(|x| {
let x = format!(".{}", x.to_string_lossy().to_lowercase());
IMAGE_SUFFIXES.contains(&x.as_str())
})
.unwrap_or(false)
})
.collect();
files.sort();
if files.is_empty() {
return Err(format!("no images found under {dir:?}"));
}
Ok(files)
}
fn write_feature_file(
path: &Path,
keypoints: &[(f64, f64)],
descriptors: &[Vec<f32>],
) -> Result<(), String> {
let mut out = String::new();
for ((x, y), descriptor) in keypoints.iter().zip(descriptors) {
out.push_str(&format!("{x:.4} {y:.4} {:.4}", 1.0));
for d in descriptor {
out.push_str(&format!(" {d:.5}"));
}
out.push('\n');
}
std::fs::write(path, out).map_err(|e| format!("write {path:?}: {e}"))
}
fn cmd_feature_extractor(args: &Args) -> Result<(), String> {
let db = PathBuf::from(args.get_or("database_path", "database.db"));
let image_dir = PathBuf::from(args.get_or("image_path", "."));
let max_keypoints: usize = args
.get_or("SiftExtraction.max_features", "4096")
.parse()
.map_err(|e| format!("{e}"))?;
let gpu = args.use_gpu("SiftExtraction.use_gpu")?;
warn_unknown_flags(
args,
&[
"database_path",
"image_path",
"SiftExtraction.max_features",
"SiftExtraction.use_gpu",
],
);
#[cfg(not(feature = "image-io"))]
{
let _ = (db, image_dir, max_keypoints, gpu);
Err("feature_extractor requires building with --features image-io".to_string())
}
#[cfg(feature = "image-io")]
{
let dir = data_dir(&db);
std::fs::create_dir_all(dir.join("features"))
.map_err(|e| format!("mkdir {:?}: {e}", dir.join("features")))?;
let images = list_images(&image_dir)?;
let config = if gpu {
SiftConfig {
max_keypoints,
..SiftConfig::default()
}
} else {
SiftConfig {
max_keypoints,
normalization: visloc_rs::vision::features::sift::SiftNormalization::L1Root,
descriptor_magnification: 3.0,
max_orientations: 2,
prefer_larger_scale: true,
vlfeat_compatible_detector: true,
vlfeat_compatible_descriptor: true,
vlfeat_bilinear_orientations: true,
..SiftConfig::default()
}
};
#[cfg(feature = "gpu")]
let mut sift_gpu = if gpu {
let ctx = visloc_sift_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
Some(visloc_sift_gpu::SiftGpu::new(ctx))
} else {
None
};
#[cfg(not(feature = "gpu"))]
let _ = gpu;
let mut gps = String::from("# NAME LAT_DEG LON_DEG ALT_M (EXIF GPS)\n");
let mut gps_count = 0usize;
for image in &images {
if let Some(fix) = read_exif_gps(image) {
let name = image.file_name().unwrap().to_string_lossy();
gps.push_str(&format!(
"{name} {:.9} {:.9} {}\n",
fix.lat_deg,
fix.lon_deg,
fix.alt_m.map_or("nan".to_string(), |a| format!("{a:.4}"))
));
gps_count += 1;
}
}
if gps_count > 0 {
let gps_path = dir.join("gps_priors.txt");
std::fs::write(&gps_path, gps).map_err(|e| format!("write {gps_path:?}: {e}"))?;
println!(
"feature_extractor: EXIF GPS on {gps_count}/{} images -> {gps_path:?}",
images.len()
);
}
for image in &images {
let name = image.file_name().unwrap().to_string_lossy().to_string();
let stem = Path::new(&name).file_stem().unwrap().to_string_lossy();
let out_path = dir.join("features").join(format!("{stem}_features.txt"));
if out_path.exists() {
continue;
}
let image_bytes = std::fs::read(image).map_err(|e| format!("read {image:?}: {e}"))?;
let dynamic = image::load_from_memory(&image_bytes)
.map_err(|e| format!("decode {image:?}: {e}"))?;
let gray = dynamic.to_luma8();
let (w, h) = (gray.width(), gray.height());
let pixels: Vec<f32> = gray.as_raw().iter().map(|&b| b as f32).collect();
let gray = GrayImage::new(w as usize, h as usize, &pixels)
.map_err(|e| format!("gray {image:?}: {e}"))?;
#[cfg(feature = "gpu")]
let extracted = match sift_gpu.as_mut() {
Some(g) => g
.extract(&gray, &config)
.map_err(|e| format!("gpu sift {image:?}: {e}")),
None => extract_sift(&gray, &config).map_err(|e| format!("sift {image:?}: {e}")),
};
#[cfg(not(feature = "gpu"))]
let extracted =
extract_sift(&gray, &config).map_err(|e| format!("sift {image:?}: {e}"));
let (keypoints, descriptors) = extracted?;
let kp: Vec<(f64, f64)> = keypoints.iter().map(|k| (k.x, k.y)).collect();
write_feature_file(&out_path, &kp, &descriptors)?;
println!("extracted {name}: {} keypoints", keypoints.len());
}
println!(
"feature_extractor: {} images -> {:?}",
images.len(),
dir.join("features")
);
Ok(())
}
}
fn load_stored_features(db: &Path) -> Result<(Vec<FeatureSet>, Vec<String>), String> {
let dir = data_dir(db).join("features");
let mut files: Vec<String> = std::fs::read_dir(&dir)
.map_err(|e| format!("read {dir:?}: {e}"))?
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| n.ends_with("_features.txt"))
.collect();
files.sort();
let mut features = Vec::new();
let mut names = Vec::new();
for f in files {
let path = dir.join(&f);
let text = std::fs::read_to_string(&path).map_err(|e| format!("read {path:?}: {e}"))?;
let mut keypoints = Vec::new();
let mut descriptors = Vec::new();
for line in text.lines().filter(|l| !l.trim().is_empty()) {
let tokens: Vec<&str> = line.split_whitespace().collect();
if tokens.len() < 7 {
continue;
}
keypoints.push(nalgebra::Point2::new(
tokens[0].parse().map_err(|e| format!("{e}"))?,
tokens[1].parse().map_err(|e| format!("{e}"))?,
));
let start = if tokens.len() >= 3 + 128 {
tokens.len() - 128
} else {
3
};
descriptors.push(
tokens[start..]
.iter()
.map(|t| t.parse::<f32>().map_err(|e| format!("{e}")))
.collect::<Result<Vec<f32>, _>>()?,
);
}
names.push(format!(
"{}.jpg",
f.strip_suffix("_features.txt").unwrap_or(&f)
));
features.push(FeatureSet::new(keypoints, descriptors).map_err(|e| format!("{e}"))?);
}
Ok((features, names))
}
fn cpu_matches(fi: &FeatureSet, fj: &FeatureSet) -> Vec<DescriptorMatch> {
let matcher = BruteForceMatcher { ratio: Some(0.8) };
CrossCheckMatcher::new(matcher).match_descriptors(&fi.descriptors, &fj.descriptors)
}
fn verify_pair(
camera: &Camera,
fi: &FeatureSet,
fj: &FeatureSet,
dm: &[DescriptorMatch],
min_matches: usize,
) -> Option<Vec<(usize, usize)>> {
if dm.len() < min_matches {
return None;
}
let corrs: Vec<TwoViewCorrespondence> = dm
.iter()
.map(|m| {
TwoViewCorrespondence::new(fi.keypoints[m.query_index], fj.keypoints[m.train_index])
})
.collect();
let verifier = TwoViewGeometryVerifier::new(TwoViewGeometryOptions::for_camera(camera, 4.0));
let report = verifier.classify(&corrs, camera);
let keep = matches!(
report.config,
ConfigurationType::Calibrated | ConfigurationType::Uncalibrated
);
if !keep || report.inliers.len() < min_matches {
return None;
}
Some(
report
.inliers
.iter()
.map(|&idx| (dm[idx].query_index, dm[idx].train_index))
.collect(),
)
}
fn cmd_exhaustive_matcher(args: &Args) -> Result<(), String> {
cmd_matcher(args, false)
}
fn cmd_spatial_matcher(args: &Args) -> Result<(), String> {
cmd_matcher(args, true)
}
fn cmd_matcher(args: &Args, spatial: bool) -> Result<(), String> {
let db = PathBuf::from(args.get_or("database_path", "database.db"));
let gpu = args.use_gpu("SiftMatching.use_gpu")?;
warn_unknown_flags(
args,
&[
"database_path",
"SiftMatching.use_gpu",
"SpatialMatching.max_num_neighbors",
"SpatialMatching.max_distance",
"SpatialMatching.ignore_z",
"pose_priors_path",
"pose_priors_format",
],
);
#[cfg(not(feature = "gpu"))]
let _ = gpu;
let (features, names) = load_stored_features(&db)?;
let (w, h) = (1600u32, 1066u32);
let fx = 0.55 * w as f64;
let camera = Camera::pinhole(1, w, h, fx, fx, w as f64 / 2.0, h as f64 / 2.0);
let all: Vec<(usize, usize)> = if spatial {
let (priors, _) = load_position_priors(args, &db, &names)?;
let positions: Vec<_> = priors
.priors
.iter()
.map(|p| p.map(|p| p.position))
.collect();
let max_neighbors: usize = args
.get_or("SpatialMatching.max_num_neighbors", "50")
.parse()
.map_err(|e| format!("max_num_neighbors: {e}"))?;
let max_distance = parse_f64(args, "SpatialMatching.max_distance", 100.0)?;
let ignore_z = !matches!(
args.get("SpatialMatching.ignore_z"),
Some("0") | Some("false")
);
let pairs = spatial_pairs(&positions, max_neighbors, max_distance, ignore_z);
println!(
"spatial_matcher: {} candidate pairs (up to {max_neighbors} neighbours within {max_distance} m)",
pairs.len()
);
pairs
} else {
(0..names.len())
.flat_map(|i| ((i + 1)..names.len()).map(move |j| (i, j)))
.collect()
};
let total = all.len();
#[cfg(feature = "gpu")]
let gpu_bank = if gpu {
let ctx = visloc_sift_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
let sets: Vec<&[Vec<f32>]> = features.iter().map(|f| f.descriptors.as_slice()).collect();
let bank = visloc_sift_gpu::FeatureBank::upload(&ctx, &sets)
.map_err(|e| format!("gpu feature bank: {e}"))?;
let matcher = visloc_sift_gpu::GpuMatcher::new(&ctx);
Some((ctx, bank, matcher))
} else {
None
};
let mut pairs: Vec<PairwiseMatches> = Vec::new();
let mut done = 0usize;
for chunk in all.chunks(2048) {
#[cfg(feature = "gpu")]
let chunk_matches: Option<Vec<Vec<DescriptorMatch>>> =
gpu_bank.as_ref().and_then(|(ctx, bank, m)| {
m.match_pairs(ctx, bank, chunk, Some(0.8), true)
.map_err(|e| eprintln!("GPU matching failed ({e}); this chunk on the CPU"))
.ok()
});
#[cfg(not(feature = "gpu"))]
let chunk_matches: Option<Vec<Vec<DescriptorMatch>>> = None;
let verified: Vec<PairwiseMatches> = chunk
.par_iter()
.enumerate()
.filter_map(|(c, &(i, j))| {
let dm = match &chunk_matches {
Some(all) => std::borrow::Cow::Borrowed(&all[c]),
None => std::borrow::Cow::Owned(cpu_matches(&features[i], &features[j])),
};
verify_pair(&camera, &features[i], &features[j], &dm, 20).map(|matches| {
PairwiseMatches {
image_i: i,
image_j: j,
matches,
two_view_config: None,
essential_matches: None,
essential_matrix: None,
}
})
})
.collect();
pairs.extend(verified);
done += chunk.len();
println!("matched {done}/{total}");
}
let dir = data_dir(&db);
std::fs::create_dir_all(&dir).map_err(|e| format!("{e}"))?;
let path = dir.join("matches.txt");
let mut text = format!("{}\n", names.len());
for n in &names {
text.push_str(&format!("{n}\n"));
}
text.push_str(&format!("{}\n", pairs.len()));
for pair in &pairs {
text.push_str(&format!(
"{} {} {}\n",
pair.image_i,
pair.image_j,
pair.matches.len()
));
for (qi, tj) in &pair.matches {
text.push_str(&format!("{qi} {tj}\n"));
}
}
std::fs::write(&path, text).map_err(|e| format!("write {path:?}: {e}"))?;
println!(
"{}: verified {}/{} pairs -> {path:?}",
if spatial {
"spatial_matcher"
} else {
"exhaustive_matcher"
},
pairs.len(),
total
);
Ok(())
}
fn flag(args: &Args, key: &str) -> bool {
matches!(args.get(key), Some("1") | Some("true") | Some("True"))
}
fn parse_f64(args: &Args, key: &str, default: f64) -> Result<f64, String> {
args.get(key).map_or(Ok(default), |v| {
v.parse().map_err(|e| format!("--{key} {v:?}: {e}"))
})
}
fn load_position_priors(
args: &Args,
db: &Path,
names: &[String],
) -> Result<(SfmPositionPriors, PriorFrame), String> {
let (path, coordinates) = match args.get("pose_priors_path") {
Some(path) => (
PathBuf::from(path),
args.get_or("pose_priors_format", "wgs84")
.parse::<PriorCoordinates>()?,
),
None => (data_dir(db).join("gps_priors.txt"), PriorCoordinates::Wgs84),
};
if !path.exists() {
return Err(format!(
"GPS priors needed: no {path:?} (the feature extractor \
writes it from EXIF GPS; or pass --pose_priors_path)"
));
}
let mut set = GpsPriorSet::read(&path, coordinates).map_err(|e| e.to_string())?;
let std_x = parse_f64(args, "prior_position_std_x", 1.0)?;
let std_y = parse_f64(args, "prior_position_std_y", std_x)?;
let std_z = parse_f64(args, "prior_position_std_z", 1.0)?;
if flag(args, "overwrite_priors_covariance") {
for prior in set.priors.values_mut() {
prior.std_horizontal_m = None;
prior.std_vertical_m = None;
}
}
let (local, frame) = set.to_local_enu(names, None, nalgebra::Vector3::new(std_x, std_y, std_z));
let mut priors = SfmPositionPriors::from_local_priors(&local);
priors.robust_loss_scale = None;
if !matches!(
args.get("use_robust_loss_on_prior_position"),
Some("0") | Some("false") | Some("False")
) {
priors.robust_loss_scale = Some(parse_f64(
args,
"prior_position_loss_scale",
visloc_rs::slam::incremental_sfm::DEFAULT_PRIOR_LOSS_SCALE,
)?);
}
if let Some(max_error) = args.get("prior_position_ransac_max_error") {
priors.alignment_max_error = Some(
max_error
.parse()
.map_err(|e| format!("ransac max error: {e}"))?,
);
}
println!(
"GPS priors for {}/{} images from {path:?}",
priors.num_priors(),
names.len()
);
Ok((priors, frame))
}
fn cmd_mapper(args: &Args) -> Result<(), String> {
cmd_mapper_with(args, false)
}
fn cmd_mapper_with(args: &Args, force_prior_position: bool) -> Result<(), String> {
let db = PathBuf::from(args.get_or("database_path", "database.db"));
let output = PathBuf::from(args.get_or("output_path", "sparse"));
let min_matches: usize = args
.get_or("Mapper.min_num_matches", "20")
.parse()
.map_err(|e| format!("{e}"))?;
let ba_gpu = args.use_gpu("Mapper.ba_use_gpu")?;
warn_unknown_flags(
args,
&[
"database_path",
"output_path",
"Mapper.min_num_matches",
"Mapper.ba_use_gpu",
"use_prior_position",
"prior_position_std_x",
"prior_position_std_y",
"prior_position_std_z",
"overwrite_priors_covariance",
"prior_position_ransac_max_error",
"use_robust_loss_on_prior_position",
"prior_position_loss_scale",
"pose_priors_path",
"pose_priors_format",
],
);
#[cfg(feature = "gpu")]
if ba_gpu {
let ctx = visloc_ba_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
visloc_rs::slam::set_ba_accelerator(Box::new(visloc_ba_gpu::GpuBundleAdjuster::new(ctx)));
}
#[cfg(not(feature = "gpu"))]
let _ = ba_gpu;
let (features, names) = load_stored_features(&db)?;
let matches_path = data_dir(&db).join("matches.txt");
if !matches_path.exists() {
return Err(format!(
"no matches at {matches_path:?}; run `exhaustive_matcher` first"
));
}
let matches_text = std::fs::read_to_string(&matches_path).map_err(|e| format!("{e}"))?;
let lines: Vec<&str> = matches_text.lines().collect();
let mut cursor = 0usize;
let next_line = |cursor: &mut usize| -> &str {
let l = lines[*cursor];
*cursor += 1;
l
};
let name_count: usize = next_line(&mut cursor)
.trim()
.parse()
.map_err(|e| format!("{e}"))?;
for _ in 0..name_count {
next_line(&mut cursor);
}
let pair_count: usize = next_line(&mut cursor)
.trim()
.parse()
.map_err(|e| format!("{e}"))?;
let mut pairwise = Vec::new();
for _ in 0..pair_count {
let head: Vec<usize> = next_line(&mut cursor)
.split_whitespace()
.map(|t| t.parse().map_err(|e| format!("{e}")))
.collect::<Result<_, _>>()?;
let count = head[2];
let mut matches = Vec::with_capacity(count);
for _ in 0..count {
let m: Vec<usize> = next_line(&mut cursor)
.split_whitespace()
.map(|t| t.parse().map_err(|e| format!("{e}")))
.collect::<Result<_, _>>()?;
matches.push((m[0], m[1]));
}
pairwise.push(PairwiseMatches {
image_i: head[0],
image_j: head[1],
matches,
two_view_config: None,
essential_matches: None,
essential_matrix: None,
});
}
let (w, h) = (1600u32, 1066u32);
let fx = 0.55 * w as f64;
let camera = Camera::pinhole(1, w, h, fx, fx, w as f64 / 2.0, h as f64 / 2.0);
let use_prior_position = force_prior_position || flag(args, "Mapper.use_prior_position");
let (position_priors, prior_frame) = if use_prior_position {
let (priors, frame) = load_position_priors(args, &db, &names)?;
(Some(priors), Some(frame))
} else {
(None, None)
};
let config = IncrementalSfmConfig {
min_seed_matches: min_matches,
position_priors: position_priors.clone(),
..IncrementalSfmConfig::default()
};
let result = incremental_sfm(&camera, &features, &pairwise, &config)
.map_err(|e| format!("mapper failed: {e}"))?;
if let (Some(priors), Some(frame)) = (position_priors.as_ref(), prior_frame.as_ref()) {
match estimate_position_prior_alignment(&result.poses, priors) {
Some(check) => {
println!(
"mapper: GPS priors: {}/{} registered prior images agree, RMSE {:.3} m (residual scale {:.4})",
check.inliers.len(),
check.num_candidates,
check.inlier_rmse,
check.similarity.scale
);
let sparse = output.join("sparse");
std::fs::create_dir_all(&sparse).map_err(|e| format!("mkdir {sparse:?}: {e}"))?;
let origin = sparse.join("enu_origin.txt");
std::fs::write(&origin, frame.describe())
.map_err(|e| format!("write {origin:?}: {e}"))?;
}
None => println!(
"mapper: GPS priors were not used (fewer than {} registered images with a prior); the model keeps an arbitrary frame and scale",
priors.min_num_priors
),
}
}
type LandmarkObs = (usize, usize, nalgebra::Point2<f64>);
type Landmark = (nalgebra::Point3<f64>, Vec<LandmarkObs>);
let mut poses_out: Vec<Pose> = Vec::new();
let mut features_out: Vec<FeatureSet> = Vec::new();
let mut landmarks: Vec<Landmark> = Vec::new();
let mut slot = 0usize;
let mut id_slot = std::collections::HashMap::new();
for (id, pose) in result.poses.iter().enumerate() {
if let Some(p) = pose {
id_slot.insert(id, slot);
poses_out.push(p.clone());
features_out.push(features[id].clone());
slot += 1;
}
}
for track in &result.tracks {
let obs: Vec<LandmarkObs> = track
.observations
.iter()
.filter_map(|(img, kp, px)| {
let slot = *id_slot.get(img)?;
Some((slot, *kp, *px))
})
.collect();
if obs.is_empty() {
continue;
}
landmarks.push((track.position, obs));
}
write_colmap_reconstruction_for_3dgs(
output.join("sparse"),
&camera,
&poses_out,
&features_out,
&landmarks,
|k| {
names[result
.poses
.iter()
.enumerate()
.filter(|(_, p)| p.is_some())
.nth(k)
.map(|(id, _)| id)
.unwrap_or(0)]
.clone()
},
)
.map_err(|e| format!("export failed: {e}"))?;
println!(
"mapper: registered {}/{} images, {} points, mean reprojection {:.3} px",
result.registered_images,
names.len(),
result.tracks.len(),
result.mean_reprojection_px
);
Ok(())
}
fn cmd_model_converter(args: &Args) -> Result<(), String> {
let input = PathBuf::from(args.get_or("input_path", "."));
let output_type = args.get_or("output_type", "TXT");
warn_unknown_flags(args, &["input_path", "output_path", "output_type"]);
if output_type != "TXT" {
return Err(format!("output type {output_type} unsupported (TXT only)"));
}
for file in ["cameras.txt", "images.txt", "points3D.txt"] {
let src = input.join(file);
if src.exists() {
println!("{}", src.display());
}
}
Ok(())
}
fn main() {
let args = Args::parse();
let result = match args.flags.get("subcommand").map(String::as_str) {
Some("feature_extractor") => cmd_feature_extractor(&args),
Some("exhaustive_matcher") => cmd_exhaustive_matcher(&args),
Some("spatial_matcher") => cmd_spatial_matcher(&args),
Some("mapper") => cmd_mapper(&args),
Some("pose_prior_mapper") => cmd_mapper_with(&args, true),
Some("model_converter") => cmd_model_converter(&args),
Some(other) => Err(format!(
"unknown subcommand `{other}` (expected feature_extractor | exhaustive_matcher | spatial_matcher | mapper | pose_prior_mapper | model_converter)"
)),
None => Err("usage: colmap <subcommand> [--flags] — see module docs".to_string()),
};
if let Err(error) = result {
eprintln!("colmap: {error}");
std::process::exit(1);
}
}