colmap 0.1.2

A comprehensive Rust library for COLMAP-style computer vision and 3D reconstruction
Documentation
//! MVS (Multi-View Stereo) 密集重建模块
//!
//! 这个模块实现了完整的多视角立体视觉算法,用于从稀疏的 SfM 重建结果生成密集的 3D 点云和三角网格。
//! 采用多阶段处理流程:立体匹配 → 深度估计 → 点云融合 → 网格重建。
//!
//! # 主要功能
//!
//! - **立体匹配**:计算图像对之间的视差和深度信息
//! - **深度估计**:使用多视角信息估计每个像素的深度
//! - **点云融合**:将多个深度图融合成统一的 3D 点云
//! - **网格重建**:从点云生成三角网格表面
//! - **质量评估**:提供重建质量的统计信息
//!
//! # 使用示例
//!
//! ## 基本 MVS 重建
//!
//! ```rust,ignore
//! use colmap::mvs::*;
//! use colmap::core::*;
//!
//! // 创建 MVS 配置
//! let config = MvsConfig {
//!     min_num_views: 3,
//!     max_image_size: 1600,
//!     depth_range: (0.1, 100.0),
//!     ..Default::default()
//! };
//!
//! // 创建 MVS 重建器
//! let reconstructor = MvsReconstructor::new(config);
//!
//! // 准备视图信息
//! let views: Vec<ViewInfo> = prepare_views_from_sfm(&reconstruction)?;
//!
//! // 执行密集重建
//! let result = reconstructor.reconstruct(&views)?;
//!
//! println!("生成了 {} 个 3D 点", result.point_cloud.points.len());
//! println!("网格包含 {} 个三角形", result.mesh.triangles.len());
//! # Ok::<(), ColmapError>(())
//! ```
//!
//! ## 分步骤重建
//!
//! ```rust,ignore
//! use colmap::mvs::*;
//!
//! // 1. 立体匹配
//! let stereo_config = StereoMatchConfig::default();
//! let stereo_matcher = StereoMatcher::new(stereo_config);
//! let disparity_maps = stereo_matcher.compute_stereo_pairs(&image_pairs)?;
//!
//! // 2. 深度估计
//! let depth_config = DepthEstimationConfig::default();
//! let depth_estimator = DepthEstimator::new(depth_config);
//! let depth_maps = depth_estimator.estimate_depth_maps(&views, &disparity_maps)?;
//!
//! // 3. 点云融合
//! let fusion_config = FusionConfig::default();
//! let fusion = PointCloudFusion::new(fusion_config);
//! let point_cloud = fusion.fuse_depth_maps(&depth_maps)?;
//!
//! // 4. 网格重建
//! let mesh_config = MeshReconstructionConfig::default();
//! let mesh_reconstructor = MeshReconstructor::new(mesh_config);
//! let mesh = mesh_reconstructor.reconstruct_mesh(&point_cloud)?;
//!
//! println!("重建完成!");
//! # Ok::<(), ColmapError>(())
//! ```
//!
//! ## 高级配置示例
//!
//! ```rust,ignore
//! use colmap::mvs::*;
//!
//! // 自定义立体匹配配置
//! let stereo_config = StereoMatchConfig {
//!     window_size: 5,
//!     max_disparity: 128,
//!     cost_aggregation: CostAggregationType::SemiGlobal,
//!     subpixel_refinement: true,
//!     ..Default::default()
//! };
//!
//! // 自定义深度估计配置
//! let depth_config = DepthEstimationConfig {
//!     num_samples: 256,
//!     ncc_sigma: 0.6,
//!     min_triangulation_angle: 1.0,
//!     incident_angle_sigma: 0.9,
//!     num_iterations: 5,
//! };
//!
//! // 自定义融合配置
//! let fusion_config = FusionConfig {
//!     max_reproj_error: 2.0,
//!     max_depth_error: 0.01,
//!     min_num_pixels: 5,
//!     ..Default::default()
//! };
//!
//! let mvs_config = MvsConfig {
//!     stereo_config,
//!     depth_config,
//!     fusion_config,
//!     min_num_views: 3,
//!     max_image_size: 2048,
//!     depth_range: (0.1, 1000.0),
//!     ..Default::default()
//! };
//!
//! let reconstructor = MvsReconstructor::new(mvs_config);
//! # Ok::<(), ColmapError>(())
//! ```

use crate::core::Result;

// 子模块
pub mod stereo;      // 立体匹配
pub mod depth;       // 深度图估计
pub mod fusion;      // 点云融合
pub mod meshing;     // 网格重建

// 重新导出主要类型
pub use stereo::{
    StereoMatcher, StereoMatchConfig, DisparityMap, DepthMap, StereoMatchResult,
    RectificationParams,
};
pub use depth::{
    DepthEstimator, DepthEstimationConfig, MultiViewDepthResult, NormalMap, CostMap,
    ViewInfo, DepthHypothesis,
};
pub use fusion::{
    PointCloudFusion, FusionConfig, FusedPoint, FusionResult, FusionStatistics,
    DepthMapView,
};
pub use meshing::{
    MeshReconstructor, MeshReconstructionConfig, ReconstructionAlgorithm,
    TriangleMesh, Vertex, Triangle, MeshStatistics,
};

/// MVS 重建配置
#[derive(Debug, Clone)]
pub struct MvsConfig {
    /// 立体匹配配置
    pub stereo_config: StereoMatchConfig,
    /// 深度估计配置
    pub depth_config: DepthEstimationConfig,
    /// 点云融合配置
    pub fusion_config: FusionConfig,
    /// 网格重建配置
    pub mesh_config: MeshReconstructionConfig,
    /// 最小视图数
    pub min_num_views: usize,
    /// 最大图像尺寸
    pub max_image_size: u32,
    /// 深度范围
    pub depth_range: (f32, f32),
}

/// 立体匹配配置(保持向后兼容)
#[derive(Debug, Clone)]
pub struct StereoConfig {
    /// 窗口大小
    pub window_size: usize,
    /// 最大视差
    pub max_disparity: i32,
    /// 代价阈值
    pub cost_threshold: f32,
}

impl Default for MvsConfig {
    fn default() -> Self {
        Self {
            stereo_config: StereoMatchConfig::default(),
            depth_config: DepthEstimationConfig::default(),
            fusion_config: FusionConfig::default(),
            mesh_config: MeshReconstructionConfig::default(),
            min_num_views: 3,
            max_image_size: 2048,
            depth_range: (0.1, 100.0),
        }
    }
}

impl Default for StereoConfig {
    fn default() -> Self {
        Self {
            window_size: 5,
            max_disparity: 128,
            cost_threshold: 0.1,
        }
    }
}

/// MVS 重建管道
#[derive(Debug)]
pub struct MvsReconstructor {
    config: MvsConfig,
    stereo_matcher: StereoMatcher,
    depth_estimator: DepthEstimator,
    point_cloud_fusion: PointCloudFusion,
    mesh_reconstructor: MeshReconstructor,
}

impl MvsReconstructor {
    /// 创建新的MVS重建器
    pub fn new(config: MvsConfig) -> Self {
        let stereo_matcher = StereoMatcher::new(config.stereo_config.clone());
        let depth_estimator = DepthEstimator::new(config.depth_config.clone());
        let point_cloud_fusion = PointCloudFusion::new(config.fusion_config.clone());
        let mesh_reconstructor = MeshReconstructor::new(config.mesh_config.clone());

        Self {
            config,
            stereo_matcher,
            depth_estimator,
            point_cloud_fusion,
            mesh_reconstructor,
        }
    }

    /// 执行完整的MVS重建管道
    pub fn reconstruct(
        &self,
        views: &[ViewInfo],
    ) -> Result<MvsReconstructionResult> {
        println!("Starting MVS reconstruction with {} views", views.len());

        // 1. 多视角深度估计
        let mut depth_results = Vec::new();
        for (i, reference_view) in views.iter().enumerate() {
            println!("Processing view {}/{}", i + 1, views.len());
            
            // 选择源视图
            let source_views: Vec<ViewInfo> = views
                .iter()
                .enumerate()
                .filter(|(j, _)| *j != i)
                .map(|(_, view)| view.clone())
                .collect();

            if source_views.len() >= self.config.min_num_views - 1 {
                let depth_result = self.depth_estimator.estimate_depth(
                    reference_view,
                    &source_views,
                )?;
                depth_results.push((i, depth_result));
            }
        }

        println!("Generated {} depth maps", depth_results.len());

        // 2. 构建深度图视图
        let mut depth_map_views = Vec::new();
        for (view_idx, depth_result) in depth_results {
            let view = &views[view_idx];
            depth_map_views.push(DepthMapView {
                depth_map: depth_result.depth_map,
                normal_map: Some(depth_result.normal_map),
                cost_map: Some(depth_result.cost_map),
                image: view.image.clone(),
            });
        }

        // 3. 点云融合
        let fusion_result = self.point_cloud_fusion.fuse_depth_maps(&depth_map_views)?;
        println!("Fused {} points", fusion_result.points.len());

        // 4. 网格重建
        let mesh = self.mesh_reconstructor.reconstruct_mesh(&fusion_result)?;
        println!("Generated mesh with {} vertices and {} triangles", 
                mesh.vertices.len(), mesh.triangles.len());

        Ok(MvsReconstructionResult {
            point_cloud: fusion_result,
            mesh,
            depth_maps: depth_map_views,
        })
    }
}

/// MVS重建结果
#[derive(Debug)]
pub struct MvsReconstructionResult {
    /// 融合点云
    pub point_cloud: FusionResult,
    /// 三角网格
    pub mesh: TriangleMesh,
    /// 深度图
    pub depth_maps: Vec<DepthMapView>,
}