cumulus3d-cli 0.11.1

cumulus3d command-line tool: progressive drone-image 3D reconstruction in one process
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*
 * interop.rs
 *
 * Copyright (c) 2026 ParkSangWoo
 *
 * Author(s):
 *
 *      ParkSangWoo <dev.parksangwoo@gmail.com>
 *
 *
 * This file is part of cumulus3d.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Third-party notices: parts of the algorithms, default parameters and data
 * formats in this file follow other open-source projects. Their copyright
 * notices and licenses are reproduced in THIRD_PARTY_NOTICES.md.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

//! Stage-by-stage subcommands compatible with an external SfM tool (COLMAP) (thin wrappers). Subcommand names and option strings follow
//! that tool's command line.
//! State between stages is carried by `--database_path` (a FeatureStore binary file) and model folders ([`cumulus3d_core::interop`]
//! format).
//! GPU-related options (`--FeatureExtraction.use_gpu` etc.) are accepted and ignored.

use crate::densewrap::{dense_model, make_pm_backend, parse_profile, DenseConfig};
use clap::{Args, Subcommand};
use cumulus3d_align::{align_to_gps, ModelAlignerOptions};
use cumulus3d_ba::{bundle_adjust, BaConfig};
use cumulus3d_core::analyzer::analyzer_lines;
use cumulus3d_core::interop::{read_model, write_model_binary, write_model_text, ImageOrder};
use cumulus3d_core::io::{read_gps_file, write_ply, PlyLayout, PointCloud};
use cumulus3d_core::reconstruction::bilinear_rgb;
use cumulus3d_core::{CameraModelKind, FeatureStore, ImageId, MatchGraph, MatchGraphOptions, Reconstruction};
use cumulus3d_dense::densify::densify_with;
use cumulus3d_dense::fusion_score::ScoreFusionOptions;
use cumulus3d_dense::{write_undistorted_workspace, DenseScene, UndistortCache, UndistortOptions};
use cumulus3d_features::{CameraMode, ExtractionOptions, FeatureExtractor, ImageStatus};
use cumulus3d_matching::{match_pair_list_file, CpuMatcher, PairMatchingOptions};
use cumulus3d_sfm::{global_mapper, register_images, triangulate_points, GlobalSfmOptions, PointTriangulatorOptions, RegistrationOptions};
use std::path::{Path, PathBuf};
use std::time::Instant;

type R = Result<(), String>;

fn e<E: std::fmt::Display>(x: E) -> String {
    x.to_string()
}

/// Accepts `1/0/true/false` (command-line convention).
pub fn parse_flag(s: &str) -> Result<bool, String> {
    match s.to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "0" | "false" | "no" | "off" => Ok(false),
        _ => Err(format!("불린 값이 아님: {s}")),
    }
}

/// Stage subcommands (command names use the underscore form such as `feature_extractor`).
#[derive(Subcommand, Debug)]
pub enum InteropCmd {
    /// Image folder -> feature store (SIFT extraction, camera initialization).
    #[command(name = "feature_extractor")]
    FeatureExtractor(FeatureExtractorArgs),
    /// Pair list file -> descriptor matching + two-view geometry verification.
    #[command(name = "matches_importer")]
    MatchesImporter(MatchesImporterArgs),
    /// Feature store -> global SfM model (`output_path/0`).
    #[command(name = "global_mapper")]
    GlobalMapper(GlobalMapperArgs),
    /// Register images not yet registered to an existing model.
    #[command(name = "image_registrator")]
    ImageRegistrator(ImageRegistratorArgs),
    /// Triangulate 3D points with the registered poses.
    #[command(name = "point_triangulator")]
    PointTriangulator(PointTriangulatorArgs),
    /// Model bundle adjustment.
    #[command(name = "bundle_adjuster")]
    BundleAdjuster(BundleAdjusterArgs),
    /// Align the model to the GPS ENU frame.
    #[command(name = "model_aligner")]
    ModelAligner(ModelAlignerArgs),
    /// Print model statistics.
    #[command(name = "model_analyzer")]
    ModelAnalyzer(ModelAnalyzerArgs),
    /// Model format conversion (BIN/TXT/PLY).
    #[command(name = "model_converter")]
    ModelConverter(ModelConverterArgs),
    /// Delete images from a model.
    #[command(name = "image_deleter")]
    ImageDeleter(ImageDeleterArgs),
    /// Create the undistortion work folder.
    #[command(name = "image_undistorter")]
    ImageUndistorter(ImageUndistorterArgs),
    /// Densification: image_undistorter output folder -> dense.ply.
    #[command(name = "densify")]
    Densify(Box<DensifyArgs>),
}

/// Arguments of `feature_extractor`.
#[derive(Args, Debug)]
pub struct FeatureExtractorArgs {
    /// Feature store file path (created if missing).
    #[arg(long = "database_path")]
    pub database_path: PathBuf,
    /// Input image folder.
    #[arg(long = "image_path")]
    pub image_path: PathBuf,
    /// File listing the image names to process (the whole folder if absent).
    #[arg(long = "image_list_path")]
    pub image_list_path: Option<PathBuf>,
    /// Camera model name.
    #[arg(long = "ImageReader.camera_model", default_value = "SIMPLE_RADIAL")]
    pub camera_model: String,
    /// All images share a single camera.
    #[arg(long = "ImageReader.single_camera", default_value = "0", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub single_camera: bool,
    /// One camera per folder.
    #[arg(long = "ImageReader.single_camera_per_folder", default_value = "0", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub single_camera_per_folder: bool,
    /// Use an existing camera id (when >= 0).
    #[arg(long = "ImageReader.existing_camera_id")]
    pub existing_camera_id: Option<i64>,
    /// Specify camera parameters directly (comma separated).
    #[arg(long = "ImageReader.camera_params")]
    pub camera_params: Option<String>,
    /// Focal length = factor x max(w, h) when there is no EXIF focal length.
    #[arg(long = "ImageReader.default_focal_length_factor", default_value_t = 1.2)]
    pub default_focal_length_factor: f64,
    /// Maximum number of features per image.
    #[arg(long = "SiftExtraction.max_num_features", default_value_t = 8192)]
    pub max_num_features: usize,
    /// Maximum SIFT input size (pixels).
    #[arg(long = "SiftExtraction.max_image_size", default_value_t = 3200)]
    pub max_image_size: usize,
    /// Whether to use the GPU (accepted and ignored).
    #[arg(long = "FeatureExtraction.use_gpu", value_parser = parse_flag)]
    pub use_gpu: Option<bool>,
    /// Whether to use the GPU (accepted and ignored).
    #[arg(long = "SiftExtraction.use_gpu", value_parser = parse_flag)]
    pub sift_use_gpu: Option<bool>,
}

/// Arguments of `matches_importer`.
#[derive(Args, Debug)]
pub struct MatchesImporterArgs {
    /// Feature store file path.
    #[arg(long = "database_path")]
    pub database_path: PathBuf,
    /// Pair list file (`name1 name2` per line).
    #[arg(long = "match_list_path")]
    pub match_list_path: PathBuf,
    /// Matching type (only `pairs` is supported).
    #[arg(long = "match_type", default_value = "pairs")]
    pub match_type: String,
    /// Whether to use the GPU (accepted and ignored).
    #[arg(long = "FeatureMatching.use_gpu", value_parser = parse_flag)]
    pub use_gpu: Option<bool>,
    /// Whether to use the GPU (accepted and ignored).
    #[arg(long = "SiftMatching.use_gpu", value_parser = parse_flag)]
    pub sift_use_gpu: Option<bool>,
    /// Maximum number of matches per pair.
    #[arg(long = "SiftMatching.max_num_matches", default_value_t = 32768)]
    pub max_num_matches: usize,
}

/// Arguments of `global_mapper`.
#[derive(Args, Debug)]
pub struct GlobalMapperArgs {
    /// Feature store file path.
    #[arg(long = "database_path")]
    pub database_path: PathBuf,
    /// Image folder (if given, point colors are extracted).
    #[arg(long = "image_path")]
    pub image_path: Option<PathBuf>,
    /// Output folder (the model goes under `0/`).
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Number of global BA iterations.
    #[arg(long = "GlobalMapper.ba_num_iterations")]
    pub ba_num_iterations: Option<usize>,
    /// Skip re-triangulation.
    #[arg(long = "GlobalMapper.skip_retriangulation", value_parser = parse_flag)]
    pub skip_retriangulation: Option<bool>,
    /// Maximum number of tracks to keep.
    #[arg(long = "GlobalMapper.keep_max_num_tracks")]
    pub keep_max_num_tracks: Option<usize>,
}

/// Arguments of `image_registrator`.
#[derive(Args, Debug)]
pub struct ImageRegistratorArgs {
    /// Feature store file path.
    #[arg(long = "database_path")]
    pub database_path: PathBuf,
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output model folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
}

/// Arguments of `point_triangulator`.
#[derive(Args, Debug)]
pub struct PointTriangulatorArgs {
    /// Feature store file path.
    #[arg(long = "database_path")]
    pub database_path: PathBuf,
    /// Image folder (if given, point colors are extracted).
    #[arg(long = "image_path")]
    pub image_path: Option<PathBuf>,
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output model folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Delete existing 3D points and triangulate again.
    #[arg(long = "clear_points", default_value = "1", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub clear_points: bool,
}

/// Arguments of `bundle_adjuster`.
#[derive(Args, Debug)]
pub struct BundleAdjusterArgs {
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output model folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Maximum number of iterations.
    #[arg(long = "BundleAdjustment.max_num_iterations", default_value_t = 100)]
    pub max_num_iterations: usize,
    /// Refine the focal length.
    #[arg(long = "BundleAdjustment.refine_focal_length", default_value = "1", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub refine_focal_length: bool,
    /// Refine the principal point.
    #[arg(long = "BundleAdjustment.refine_principal_point", default_value = "0", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub refine_principal_point: bool,
    /// Refine extra parameters such as distortion.
    #[arg(long = "BundleAdjustment.refine_extra_params", default_value = "1", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub refine_extra_params: bool,
}

/// Arguments of `model_aligner`.
#[derive(Args, Debug)]
pub struct ModelAlignerArgs {
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output model folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Reference GPS file (line: `name latitude longitude altitude`).
    #[arg(long = "ref_images_path")]
    pub ref_images_path: PathBuf,
    /// Whether the reference is GPS (only 1 is supported).
    #[arg(long = "ref_is_gps", default_value = "1", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub ref_is_gps: bool,
    /// Alignment frame (only `enu` is supported).
    #[arg(long = "alignment_type", default_value = "enu")]
    pub alignment_type: String,
    /// Maximum error of the robust estimate (meters, 0 = no robust estimation).
    #[arg(long = "alignment_max_error", default_value_t = 0.0)]
    pub alignment_max_error: f64,
    /// Minimum number of common images required for alignment.
    #[arg(long = "min_common_images", default_value_t = 3)]
    pub min_common_images: usize,
}

/// Arguments of `model_analyzer`.
#[derive(Args, Debug)]
pub struct ModelAnalyzerArgs {
    /// Model folder.
    #[arg(long = "path")]
    pub path: PathBuf,
    /// Print detailed statistics.
    #[arg(long = "verbose", default_value = "0", value_parser = parse_flag, action = clap::ArgAction::Set)]
    pub verbose: bool,
}

/// Arguments of `model_converter`.
#[derive(Args, Debug)]
pub struct ModelConverterArgs {
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output folder or file.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Output format (BIN|TXT|PLY).
    #[arg(long = "output_type")]
    pub output_type: String,
}

/// Arguments of `image_deleter`.
#[derive(Args, Debug)]
pub struct ImageDeleterArgs {
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output model folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// File listing the image ids to delete.
    #[arg(long = "image_ids_path")]
    pub image_ids_path: Option<PathBuf>,
    /// File listing the image names to delete.
    #[arg(long = "image_names_path")]
    pub image_names_path: Option<PathBuf>,
}

/// Arguments of `image_undistorter`.
#[derive(Args, Debug)]
pub struct ImageUndistorterArgs {
    /// Input image folder.
    #[arg(long = "image_path")]
    pub image_path: PathBuf,
    /// Input model folder.
    #[arg(long = "input_path")]
    pub input_path: PathBuf,
    /// Output work folder.
    #[arg(long = "output_path")]
    pub output_path: PathBuf,
    /// Output format (only this value is supported).
    #[arg(long = "output_type", default_value = "COLMAP")]
    pub output_type: String,
    /// Maximum size of undistorted images (-1 = unlimited).
    #[arg(long = "max_image_size", default_value_t = -1)]
    pub max_image_size: i64,
}

/// Arguments of `densify`.
#[derive(Args, Debug)]
pub struct DensifyArgs {
    /// image_undistorter output folder (images/, sparse/). If `--image_path` is given, the model with distortion (`--input_path`) is
    /// undistorted in memory instead.
    #[arg(long = "input_path", short = 'i')]
    pub input_path: PathBuf,
    /// Output PLY.
    #[arg(long = "output_path", short = 'o')]
    pub output_path: PathBuf,
    /// If given, `input_path` is treated as an input model with distortion and the images in this folder are undistorted in memory.
    #[arg(long = "image_path")]
    pub image_path: Option<PathBuf>,
    /// Maximum undistortion size (in-memory undistortion path).
    #[arg(long = "max_image_size", default_value_t = 960)]
    pub max_image_size: i64,
    /// Number of source views per reference view (<= 32).
    #[arg(long = "number-views", default_value_t = 10)]
    pub number_views: usize,
    /// PatchMatch backend (cuda).
    #[arg(long = "pm-backend", default_value = "cuda")]
    pub pm_backend: String,
    /// Profile (fast|quality).
    #[arg(long = "mvs-profile", default_value = "fast")]
    pub mvs_profile: String,
    /// Cost window radius (default: profile value 5).
    #[arg(long = "window-radius")]
    pub window_radius: Option<i32>,
    /// Cost window sample stride 1|2 (default: fast 2, quality 1).
    #[arg(long = "window-step")]
    pub window_step: Option<i32>,
    /// Upper bound on the number of scales.
    #[arg(long = "max-levels")]
    pub max_levels: Option<usize>,
    /// Only the first N images in registration order (when using `--image_path`).
    #[arg(long = "max-images")]
    pub max_images: Option<usize>,
    /// Fusion mode (consistency|traversal|score).
    #[arg(long = "fusion-mode")]
    pub fusion_mode: Option<String>,
    /// Consistent fusion: minimum number of agreeing views besides the reference.
    #[arg(long = "fusion-min-views")]
    pub fusion_min_views: Option<usize>,
    /// Fusion relative depth tolerance.
    #[arg(long = "fusion-depth-error")]
    pub fusion_depth_error: Option<f64>,
    /// Fusion normal tolerance angle (degrees).
    #[arg(long = "fusion-normal-error")]
    pub fusion_normal_error: Option<f64>,
    /// Fusion reprojection tolerance (pixels).
    #[arg(long = "fusion-reproj-error")]
    pub fusion_reproj_error: Option<f64>,
    /// Handling of remaining pixels in consistent fusion (none|release|second-pass).
    #[arg(long = "fusion-residual")]
    pub fusion_residual: Option<String>,
    /// Second-pass fusion: minimum number of agreeing views besides the reference (default 2).
    #[arg(long = "residual-min-views")]
    pub residual_min_views: Option<usize>,
    /// Second-pass fusion: relative depth tolerance (default 0.5x the first pass).
    #[arg(long = "residual-depth-error")]
    pub residual_depth_error: Option<f64>,
    /// Second-pass fusion: normal tolerance angle (degrees, default 0.67x the first pass).
    #[arg(long = "residual-normal-error")]
    pub residual_normal_error: Option<f64>,
    /// Second-pass fusion: second-pass points within this distance of a first-pass point (GSD multiple, default 0.5) are discarded.
    #[arg(long = "residual-min-dist")]
    pub residual_min_dist: Option<f64>,
    /// Consistent fusion: mark used pixels (1|0).
    #[arg(long = "fusion-mark-used", value_parser = parse_flag)]
    pub fusion_mark_used: Option<bool>,
    /// Consistent fusion: marking radius (pixels).
    #[arg(long = "fusion-mark-radius")]
    pub fusion_mark_radius: Option<usize>,
    /// Consistent fusion: number of overlapping views to check.
    #[arg(long = "fusion-num-images")]
    pub fusion_num_images: Option<usize>,
    /// Override the number of geometric iterations at all scales.
    #[arg(long = "geo-iters")]
    pub geo_iters: Option<u32>,
    /// Override the number of geometric run rounds.
    #[arg(long = "geo-rounds")]
    pub geo_rounds: Option<u32>,
    /// Consistent fusion: inverse-variance weighting (1|0).
    #[arg(long = "fusion-inverse-variance", value_parser = parse_flag)]
    pub fusion_inverse_variance: Option<bool>,
    /// Fused-cloud smoothing along normals: iterations (0 = off).
    #[arg(long = "fusion-smooth-iters")]
    pub fusion_smooth_iters: Option<usize>,
    /// Fused-cloud smoothing: neighbour radius (GSD multiple).
    #[arg(long = "fusion-smooth-radius")]
    pub fusion_smooth_radius: Option<f64>,
    /// Fused-cloud smoothing: range sigma along the normal (GSD multiple).
    #[arg(long = "fusion-smooth-range")]
    pub fusion_smooth_range: Option<f64>,
    /// Fused-cloud smoothing: neighbour normal gate (degrees).
    #[arg(long = "fusion-smooth-normal")]
    pub fusion_smooth_normal: Option<f64>,
    /// Free-space visibility filter: neighbouring views checked per fused point (0 = off).
    #[arg(long = "visibility-views")]
    pub visibility_views: Option<usize>,
    /// Free-space visibility filter: relative depth tolerance.
    #[arg(long = "visibility-tau")]
    pub visibility_tau: Option<f64>,
    /// Free-space visibility filter: minimum violating views to remove a point.
    #[arg(long = "visibility-min-violations")]
    pub visibility_min_violations: Option<usize>,
    /// Depth map filter: minimum number of agreeing views.
    #[arg(long = "filter-min-views")]
    pub filter_min_views: Option<u32>,
    /// Depth map filter: forward/backward reprojection tolerance (pixels).
    #[arg(long = "filter-geom-error")]
    pub filter_geom_error: Option<f32>,
    /// Depth map filter: minimum NCC.
    #[arg(long = "filter-min-ncc")]
    pub filter_min_ncc: Option<f32>,
    /// Remove small fragments (1|0).
    #[arg(long = "remove-speckles", value_parser = parse_flag)]
    pub remove_speckles: Option<bool>,
    /// Boundary-aware gap filling (1|0).
    #[arg(long = "fill-holes", value_parser = parse_flag)]
    pub fill_holes: Option<bool>,
    /// Direction-diversity damping of neighbor selection (1 = off).
    #[arg(long = "diversity-decay")]
    pub diversity_decay: Option<f64>,
    /// Reference patch variance threshold for adding coarse-scale candidates (0 = off).
    #[arg(long = "weak-texture-var")]
    pub weak_texture_var: Option<f32>,
    /// 5x5 median plane filter before readout (1|0).
    #[arg(long = "median-filter", value_parser = parse_flag)]
    pub median_filter: Option<bool>,
    /// Print statistics of the resulting point cloud (spacing, outliers, duplicates).
    #[arg(long = "stats")]
    pub stats: bool,
    /// Score fusion: acceptance threshold tau (default 2.0).
    #[arg(long = "score-tau")]
    pub score_tau: Option<f64>,
    /// Score fusion: reprojection error weight sigma_e (pixels, default 1.0).
    #[arg(long = "score-sigma-e")]
    pub score_sigma_e: Option<f64>,
    /// Score fusion: viewing-angle weight sigma_theta (degrees, default 2.0).
    #[arg(long = "score-sigma-theta")]
    pub score_sigma_theta: Option<f64>,
    /// Score fusion: free-space violation penalty coefficient lambda (default 1.0).
    #[arg(long = "score-lambda")]
    pub score_lambda: Option<f64>,
    /// PLY for the second-pass fusion points only (when `--fusion-residual second-pass`).
    #[arg(long = "residual-out")]
    pub residual_out: Option<PathBuf>,
    /// Fusion variants file (`name|fusion flags` per line). The depth maps are built once and a `<output_path folder>/<name>.ply` is
    /// written per variant.
    #[arg(long = "fusion-variants")]
    pub fusion_variants: Option<PathBuf>,
}

/// Apply the densify subcommand options to the settings.
pub(crate) fn apply_densify_args(a: &DensifyArgs, o: &mut cumulus3d_dense::DensifyOptions) -> R {
    if let Some(r) = a.window_radius {
        o.pm.window_radius = r;
    }
    if let Some(st) = a.window_step {
        o.pm.window_step = st;
    }
    if let Some(l) = a.max_levels {
        o.max_levels = l;
    }
    if let Some(m) = a.fusion_mode.as_deref().filter(|m| !is_score_mode(m)) {
        o.set_fusion_mode(cumulus3d_dense::FusionMode::parse(m).ok_or_else(|| format!("알 수 없는 --fusion-mode {m}"))?);
    }
    let f = &mut o.fusion;
    if let Some(v) = a.fusion_min_views {
        f.min_consistent_views = v;
    }
    if let Some(v) = a.fusion_depth_error {
        f.max_depth_error = v;
    }
    if let Some(v) = a.fusion_normal_error {
        f.max_normal_error_deg = v;
    }
    if let Some(v) = a.fusion_reproj_error {
        f.max_reproj_error = v;
    }
    if let Some(m) = &a.fusion_residual {
        f.residual = cumulus3d_dense::FusionResidual::parse(m).ok_or_else(|| format!("알 수 없는 --fusion-residual {m}"))?;
    }
    if let Some(v) = a.residual_min_views {
        f.residual_params.min_views = v;
    }
    if let Some(v) = a.residual_depth_error {
        f.residual_params.depth_error = Some(v);
    }
    if let Some(v) = a.residual_normal_error {
        f.residual_params.normal_error_deg = Some(v);
    }
    if let Some(v) = a.residual_min_dist {
        f.residual_params.min_dist_gsd = v;
    }
    if let Some(v) = a.fusion_mark_used {
        f.mark_used = v;
    }
    if let Some(v) = a.fusion_mark_radius {
        f.mark_radius = v;
    }
    if let Some(v) = a.fusion_num_images {
        f.consistency_num_images = v;
    }
    if let Some(v) = a.geo_iters {
        o.geometric_iters_override = Some(v);
    }
    if let Some(v) = a.geo_rounds {
        o.geometric_rounds_override = Some(v);
    }
    if let Some(v) = a.fusion_inverse_variance {
        f.inverse_variance = v;
    }
    if let Some(v) = a.fusion_smooth_iters {
        f.smooth.iterations = v;
    }
    if let Some(v) = a.fusion_smooth_radius {
        f.smooth.radius_gsd = v;
    }
    if let Some(v) = a.fusion_smooth_range {
        f.smooth.sigma_range_gsd = v;
    }
    if let Some(v) = a.fusion_smooth_normal {
        f.smooth.normal_deg = v;
    }
    if let Some(v) = a.visibility_views {
        f.visibility.check_views = v;
    }
    if let Some(v) = a.visibility_tau {
        f.visibility.tau = v;
    }
    if let Some(v) = a.visibility_min_violations {
        f.visibility.min_violations = v;
    }
    if let Some(v) = a.filter_min_views {
        o.filter.min_num_consistent = v;
    }
    if let Some(v) = a.filter_geom_error {
        o.filter.geom_max_cost = v;
    }
    if let Some(v) = a.filter_min_ncc {
        o.filter.min_ncc = v;
    }
    if let Some(v) = a.remove_speckles {
        o.post.remove_speckles = v;
    }
    if let Some(v) = a.fill_holes {
        o.post.fill_holes = v;
    }
    if let Some(v) = a.diversity_decay {
        o.neighbors.diversity_decay = v;
    }
    if let Some(v) = a.weak_texture_var {
        o.pm.weak_texture_var = v;
    }
    if let Some(v) = a.median_filter {
        o.filter.median_filter = v;
    }
    Ok(())
}

fn is_score_mode(m: &str) -> bool {
    m.eq_ignore_ascii_case("score")
}

fn apply_score_args(a: &DensifyArgs, s: &mut ScoreFusionOptions) {
    if let Some(v) = a.score_tau {
        s.tau = v;
    }
    if let Some(v) = a.score_sigma_e {
        s.sigma_e_px = v;
    }
    if let Some(v) = a.score_sigma_theta {
        s.sigma_theta_deg = v;
    }
    if let Some(v) = a.score_lambda {
        s.lambda = v;
    }
}

fn has_score_args(a: &DensifyArgs) -> bool {
    a.score_tau.is_some() || a.score_sigma_e.is_some() || a.score_sigma_theta.is_some() || a.score_lambda.is_some()
}

/// Score fusion settings. With `--fusion-mode score`, it inherits the tolerances of `o.fusion` (after the other fusion flags are applied)
/// and overrides them with `--score-*`.
/// `base` is the densify command's own arguments in a fusion variant: if the variant line has no `--fusion-mode`, that mode is followed,
/// and its `--score-*` are applied first.
pub(crate) fn score_options(
    a: &DensifyArgs,
    o: &cumulus3d_dense::DensifyOptions,
    base: Option<&DensifyArgs>,
) -> Result<Option<ScoreFusionOptions>, String> {
    let mode = a.fusion_mode.as_deref().or_else(|| base.and_then(|b| b.fusion_mode.as_deref()));
    if !mode.is_some_and(is_score_mode) {
        if has_score_args(a) || base.is_some_and(|b| a.fusion_mode.is_none() && has_score_args(b)) {
            return Err("--score-* 는 --fusion-mode score 와 함께".into());
        }
        return Ok(None);
    }
    let mut s = ScoreFusionOptions::from_fusion(&o.fusion);
    if let Some(b) = base {
        apply_score_args(b, &mut s);
    }
    apply_score_args(a, &mut s);
    Ok(Some(s))
}

fn load_store(p: &Path) -> Result<FeatureStore, String> {
    if p.exists() {
        FeatureStore::load(p).map_err(|x| format!("{}: {x}", p.display()))
    } else {
        Ok(FeatureStore::new())
    }
}

fn load_model(p: &Path) -> Result<Reconstruction, String> {
    read_model(p).map_err(|x| format!("{}: {x}", p.display()))
}

fn save_model(rec: &Reconstruction, p: &Path) -> R {
    std::fs::create_dir_all(p).map_err(e)?;
    write_model_binary(rec, p, ImageOrder::Registration).map_err(e)
}

fn graph_of(store: &FeatureStore) -> MatchGraph {
    MatchGraph::from_store(store, &MatchGraphOptions::default())
}

/// Extract 3D point colors from the image folder (the common final step of the commands that use a model).
pub fn extract_colors(rec: &mut Reconstruction, image_path: &Path) {
    rec.extract_colors(|im| {
        let img = image::open(image_path.join(&im.name)).ok()?.to_rgb8();
        let (w, h) = (img.width() as usize, img.height() as usize);
        let data = img.into_raw();
        Some(move |x: f64, y: f64| bilinear_rgb(&data, w, h, x, y))
    });
}

fn list_images(root: &Path) -> Vec<String> {
    fn walk(dir: &Path, root: &Path, out: &mut Vec<String>) {
        let Ok(rd) = std::fs::read_dir(dir) else { return };
        for ent in rd.flatten() {
            let p = ent.path();
            if p.is_dir() {
                walk(&p, root, out);
            } else if let Some(ext) = p.extension().and_then(|x| x.to_str()) {
                if matches!(ext.to_ascii_lowercase().as_str(), "jpg" | "jpeg" | "png") {
                    if let Ok(rel) = p.strip_prefix(root) {
                        out.push(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"));
                    }
                }
            }
        }
    }
    let mut v = Vec::new();
    walk(root, root, &mut v);
    v.sort();
    v
}

/// Run one subcommand.
pub fn run(cmd: InteropCmd) -> R {
    let t = Instant::now();
    match cmd {
        InteropCmd::FeatureExtractor(a) => {
            let store = load_store(&a.database_path)?;
            let names = match &a.image_list_path {
                Some(p) => cumulus3d_features::read_image_list(p).map_err(e)?,
                None => list_images(&a.image_path),
            };
            let mut o = ExtractionOptions::default();
            o.reader.camera_model = CameraModelKind::from_name(&a.camera_model).map_err(e)?;
            o.reader.camera_mode = if let Some(id) = a.existing_camera_id.filter(|x| *x >= 0) {
                CameraMode::Existing(id as u32)
            } else if a.single_camera {
                CameraMode::Single
            } else if a.single_camera_per_folder {
                CameraMode::PerFolder
            } else {
                CameraMode::PerImage
            };
            if let Some(p) = &a.camera_params {
                o.reader.camera_params = Some(p.split(',').map(|x| x.trim().parse::<f64>().map_err(e)).collect::<Result<_, _>>()?);
            }
            o.reader.default_focal_length_factor = a.default_focal_length_factor;
            o.reader.max_image_size = a.max_image_size;
            o.sift.max_num_features = a.max_num_features;
            let rep = FeatureExtractor::new().extract_files(&store, &a.image_path, &names, &o).map_err(e)?;
            for r in &rep {
                match &r.status {
                    ImageStatus::Extracted { image_id, camera_id, num_features } => {
                        println!("{} image_id={image_id} camera_id={camera_id} features={num_features}", r.name)
                    }
                    ImageStatus::AlreadyExists { image_id } => println!("{} image_id={image_id} (이미 있음)", r.name),
                    ImageStatus::Failed { error } => println!("{} 실패: {error}", r.name),
                }
            }
            store.save(&a.database_path).map_err(e)?;
        }
        InteropCmd::MatchesImporter(a) => {
            if a.match_type != "pairs" {
                return Err(format!("--match_type {} 미지원(pairs 만)", a.match_type));
            }
            let store = load_store(&a.database_path)?;
            let opts = PairMatchingOptions { max_num_matches: a.max_num_matches, ..Default::default() };
            let (list, st) = match_pair_list_file(&store, &a.match_list_path, &opts, &CpuMatcher::default()).map_err(e)?;
            for n in &list.missing_names {
                println!("경고: 이름 없음 {n}");
            }
            println!(
                "짝 {} 건너뜀 {} 매칭 {} 검증만 {} 유효 기하 {}",
                list.pairs.len(),
                st.num_skipped_existing,
                st.num_matched,
                st.num_verified_only,
                st.num_valid_geometries
            );
            store.save(&a.database_path).map_err(e)?;
        }
        InteropCmd::GlobalMapper(a) => {
            let store = load_store(&a.database_path)?;
            let graph = graph_of(&store);
            let mut o = GlobalSfmOptions::default();
            if let Some(n) = a.ba_num_iterations {
                o.ba_num_iterations = n;
            }
            if let Some(s) = a.skip_retriangulation {
                o.skip_retriangulation = s;
            }
            if let Some(n) = a.keep_max_num_tracks {
                o.tracks.max_num_tracks = n;
            }
            let out = global_mapper(&store, &graph, &o).map_err(e)?;
            if let Some(f) = &out.failure {
                println!("경고: {f}");
            }
            let mut rec = out.reconstruction;
            if let Some(ip) = &a.image_path {
                extract_colors(&mut rec, ip);
            }
            if rec.registered_image_count() > 0 {
                save_model(&rec, &a.output_path.join("0"))?;
            }
            println!("등록 {} 점 {}", rec.registered_image_count(), rec.num_points3d());
        }
        InteropCmd::ImageRegistrator(a) => {
            let store = load_store(&a.database_path)?;
            let graph = graph_of(&store);
            let mut rec = load_model(&a.input_path)?;
            let rep = register_images(&mut rec, &store, &graph, &RegistrationOptions::default()).map_err(e)?;
            println!("시도 {} 등록 {}", rep.attempts.len(), rep.registered().len());
            save_model(&rec, &a.output_path)?;
        }
        InteropCmd::PointTriangulator(a) => {
            let store = load_store(&a.database_path)?;
            let graph = graph_of(&store);
            let mut rec = load_model(&a.input_path)?;
            let o = PointTriangulatorOptions { clear_points: a.clear_points, ..Default::default() };
            let rep = triangulate_points(&mut rec, &graph, &o).map_err(e)?;
            if let Some(ip) = &a.image_path {
                extract_colors(&mut rec, ip);
            }
            println!("{rep:?}");
            save_model(&rec, &a.output_path)?;
        }
        InteropCmd::BundleAdjuster(a) => {
            let mut rec = load_model(&a.input_path)?;
            let cfg = BaConfig {
                max_num_iterations: a.max_num_iterations,
                refine_focal_length: a.refine_focal_length,
                refine_principal_point: a.refine_principal_point,
                refine_extra_params: a.refine_extra_params,
                ..Default::default()
            };
            let s = bundle_adjust(&mut rec, &cfg).map_err(e)?;
            println!("반복 {} 비용 {:.6e} → {:.6e} {:?}", s.num_iterations, s.initial_cost, s.final_cost, s.termination);
            save_model(&rec, &a.output_path)?;
        }
        InteropCmd::ModelAligner(a) => {
            if !a.ref_is_gps || a.alignment_type != "enu" {
                return Err("model_aligner: --ref_is_gps 1 --alignment_type enu 만 지원".into());
            }
            let mut rec = load_model(&a.input_path)?;
            let gps = read_gps_file(&a.ref_images_path).map_err(e)?;
            let o = ModelAlignerOptions { max_error: a.alignment_max_error, min_common_images: a.min_common_images, ..Default::default() };
            let al = align_to_gps(&mut rec, &gps, &o).map_err(e)?;
            for (n, er) in &al.errors {
                println!("{n}: {er:.4}");
            }
            println!("평균 오차 {:.4} 중앙 {:.4} 인라이어 {}/{}", al.mean_error, al.median_error, al.num_inliers, al.common.len());
            save_model(&rec, &a.output_path)?;
        }
        InteropCmd::ModelAnalyzer(a) => {
            let rec = load_model(&a.path)?;
            for l in analyzer_lines(&rec, a.verbose) {
                println!("{l}");
            }
            return Ok(());
        }
        InteropCmd::ModelConverter(a) => {
            let rec = load_model(&a.input_path)?;
            match a.output_type.to_ascii_uppercase().as_str() {
                "BIN" => save_model(&rec, &a.output_path)?,
                "TXT" => {
                    std::fs::create_dir_all(&a.output_path).map_err(e)?;
                    write_model_text(&rec, &a.output_path, ImageOrder::Registration).map_err(e)?
                }
                "PLY" => {
                    let mut c = PointCloud::default();
                    for (_, p) in rec.points3d() {
                        c.positions.push([p.xyz.x as f32, p.xyz.y as f32, p.xyz.z as f32]);
                        c.normals.push([0.0; 3]);
                        c.colors.push(p.color);
                    }
                    write_ply(&a.output_path, &c, PlyLayout::XyzNormalRgb).map_err(e)?
                }
                o => return Err(format!("--output_type {o} 미지원(BIN|TXT|PLY)")),
            }
        }
        InteropCmd::ImageDeleter(a) => {
            let mut rec = load_model(&a.input_path)?;
            let mut warn = Vec::new();
            if let Some(p) = &a.image_ids_path {
                let ids: Vec<ImageId> = std::fs::read_to_string(p).map_err(e)?.split_whitespace().filter_map(|x| x.parse().ok()).collect();
                warn.extend(rec.deregister_images_by_id(&ids));
            }
            if let Some(p) = &a.image_names_path {
                let text = std::fs::read_to_string(p).map_err(e)?;
                let names: Vec<&str> = text.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();
                warn.extend(rec.deregister_images_by_name(&names));
            }
            for w in warn {
                println!("{w}");
            }
            save_model(&rec, &a.output_path)?;
        }
        InteropCmd::ImageUndistorter(a) => {
            if a.output_type != "COLMAP" {
                return Err("image_undistorter: --output_type COLMAP 만 지원".into());
            }
            let rec = load_model(&a.input_path)?;
            let o = UndistortOptions { max_image_size: a.max_image_size, ..Default::default() };
            let r = cumulus3d_dense::undistort_from_dir(&rec, &a.image_path, &o, &UndistortCache::new()).map_err(e)?;
            write_undistorted_workspace(&r, &a.output_path, &o).map_err(e)?;
            println!("보정 {} 실패 {}", r.images.len(), r.failed.len());
        }
        InteropCmd::Densify(a) => {
            let profile = parse_profile(&a.mvs_profile)?;
            let mut cfg = DenseConfig::new(make_pm_backend(&a.pm_backend), profile);
            cfg.undistort.max_image_size = a.max_image_size;
            cfg.densify.neighbors.num_views = a.number_views;
            apply_densify_args(&a, &mut cfg.densify)?;
            cfg.score = score_options(&a, &cfg.densify, None)?;
            // Validate the variants file before depth estimation.
            let variants =
                a.fusion_variants.as_deref().map(|vp| crate::fusion_variants::read_variants(vp, &a, &cfg.densify)).transpose()?;
            let backend = cfg.backend.clone()?;
            let tl = Instant::now();
            let (out, frames, scene) = match &a.image_path {
                Some(ip) => {
                    let model = load_model(&a.input_path)?;
                    let keep: std::collections::HashSet<String> = model
                        .registered_images()
                        .into_iter()
                        .take(a.max_images.unwrap_or(usize::MAX))
                        .filter_map(|i| model.image(i).map(|im| im.name.clone()))
                        .collect();
                    let r = dense_model(&model, |n| keep.contains(n), ip, &cfg)?;
                    eprintln!("[time] 왜곡 보정+장면 {:.2}s", r.undistort_time.as_secs_f64());
                    (r.output, r.frames, r.scene)
                }
                None => {
                    let scene = DenseScene::from_workspace_dir(&a.input_path, &cfg.scene).map_err(e)?;
                    eprintln!("[time] 장면 읽기 {:.2}s", tl.elapsed().as_secs_f64());
                    let n = scene.views.len();
                    (densify_with(&scene, &cfg.densify, cfg.score.as_ref(), backend.as_ref(), None).map_err(e)?, n, scene)
                }
            };
            let tm = &out.timings;
            let lv: Vec<String> = tm.levels.iter().map(|d| format!("{:.2}", d.as_secs_f64())).collect();
            eprintln!(
                "[time] 뷰 {frames}, 깊이맵 {}: 이웃 {:.2}s 준비 {:.2}s 깊이 {:.2}s (스케일별 [{}], 그중 상향표본·판정 {:.2}s) 필터 {:.2}s 융합 {:.2}s 합 {:.2}s",
                out.depth_views,
                tm.neighbors.as_secs_f64(),
                tm.prepare.as_secs_f64(),
                tm.depth().as_secs_f64(),
                lv.join(", "),
                tm.upsample.as_secs_f64(),
                tm.filter.as_secs_f64(),
                tm.fusion.as_secs_f64(),
                tm.total().as_secs_f64()
            );
            let tw = Instant::now();
            out.write_ply(&a.output_path).map_err(e)?;
            if let Some(rp) = &a.residual_out {
                if !out.write_residual_ply(rp).map_err(e)? {
                    eprintln!("경고: 2차 융합 점 없음 → {} 쓰지 않음", rp.display());
                }
            }
            eprintln!("[time] PLY 쓰기 {:.2}s", tw.elapsed().as_secs_f64());
            println!(
                "점 {} (2차 {}) 융합 {:.2}s (1차 {:.2}s 2차 {:.2}s 평활 {:.2}s, 가시성 {:.2}s, 제거 {})",
                out.cloud.len(),
                out.num_residual(),
                tm.fusion.as_secs_f64(),
                tm.fusion_pass1.as_secs_f64(),
                tm.fusion_pass2.as_secs_f64(),
                tm.fusion_smooth.as_secs_f64(),
                tm.fusion_visibility.as_secs_f64(),
                tm.fusion_visibility_removed
            );
            if a.stats {
                let ts = Instant::now();
                let st = cumulus3d_dense::cloud_stats(&scene, &out.depth_maps, &out.cloud, &out.visibility, 200_000, 2.0);
                println!(
                    "통계: 점 {} 표본 {} 이웃 간격 중앙 {:.4} GSD {:.4} 이상점(2px) {:.2}% 평면 이탈(>GSD·고립) {:.2}% 평면 거리 중앙 {:.4} 중복(<GSD/2) {:.2}% ({:.1}s)",
                    st.points,
                    st.sampled,
                    st.nn_spacing_median,
                    st.gsd,
                    100.0 * st.outlier_ratio,
                    100.0 * st.plane_outlier_ratio,
                    st.plane_residual_median,
                    100.0 * st.duplicate_ratio,
                    ts.elapsed().as_secs_f64()
                );
            }
            if let Some(variants) = &variants {
                let dir = a.output_path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
                crate::fusion_variants::run_variants(&scene, &out.depth_maps, variants, dir, a.stats)?;
            }
        }
    }
    eprintln!("Elapsed time: {:.3} [minutes]", t.elapsed().as_secs_f64() / 60.0);
    Ok(())
}