colmap 0.1.2

A comprehensive Rust library for COLMAP-style computer vision and 3D reconstruction
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
# COLMAP Rust 库架构设计

## 1. COLMAP 核心功能分析

### 1.1 主要功能模块

COLMAP 是一个通用的 Structure-from-Motion (SfM) 和 Multi-View Stereo (MVS) 管道,主要包含以下核心功能:

#### 特征提取和匹配
- **SIFT/ORB 特征检测**:检测图像中的关键点
- **特征描述**:为每个关键点生成描述符
- **特征匹配**:在图像对之间匹配特征点
- **几何验证**:使用 RANSAC 验证匹配的几何一致性

#### Structure from Motion (SfM)
- **增量式重建**:逐步添加图像进行重建
- **相机标定**:估计相机内参和畸变参数
- **姿态估计**:计算相机的外参(位置和方向)
- **三角测量**:从多个视图重建 3D 点
- **束调整**:全局优化相机参数和 3D 点位置

#### Multi-View Stereo (MVS)
- **深度图估计**:为每个视图生成密集深度图
- **深度图融合**:将多个深度图融合成完整的 3D 模型
- **点云生成**:从深度图生成密集点云
- **网格重建**:从点云生成三角网格(可选)

### 1.2 数据流分析

```
输入图像 → 特征提取 → 特征匹配 → SfM重建 → MVS重建 → 输出模型
    ↓         ↓         ↓         ↓         ↓         ↓
  Image    Feature   Matches   Cameras   Dense    Mesh
  Files    Points              & Points  Points
```

## 2. Rust 架构设计

### 2.1 模块层次结构

```
colmap/
├── src/
│   ├── lib.rs                 # 库入口,重新导出主要 API
│   ├── core/                  # 核心数据结构和类型
│   │   ├── mod.rs
│   │   ├── camera.rs          # 相机模型和参数
│   │   ├── image.rs           # 图像数据结构
│   │   ├── feature.rs         # 特征点和描述符
│   │   ├── point3d.rs         # 3D 点和轨迹
│   │   ├── pose.rs            # 相机姿态和变换
│   │   └── reconstruction.rs  # 重建结果数据结构
│   ├── feature/               # 特征提取和匹配
│   │   ├── mod.rs
│   │   ├── detector.rs        # 特征检测器接口
│   │   ├── sift.rs           # SIFT 特征提取
│   │   ├── orb.rs            # ORB 特征提取
│   │   ├── matcher.rs        # 特征匹配器
│   │   └── geometric.rs      # 几何验证
│   ├── sfm/                   # Structure from Motion
│   │   ├── mod.rs
│   │   ├── incremental.rs    # 增量式 SfM
│   │   ├── triangulation.rs  # 三角测量
│   │   ├── bundle_adjustment.rs # 束调整优化
│   │   ├── pose_estimation.rs   # 姿态估计
│   │   └── reconstruction.rs    # 重建管道
│   ├── mvs/                   # Multi-View Stereo
│   │   ├── mod.rs
│   │   ├── depth_map.rs      # 深度图估计
│   │   ├── fusion.rs         # 深度图融合
│   │   ├── point_cloud.rs    # 点云生成
│   │   └── meshing.rs        # 网格重建
│   ├── math/                  # 数学工具和算法
│   │   ├── mod.rs
│   │   ├── geometry.rs       # 几何计算
│   │   ├── optimization.rs   # 优化算法
│   │   ├── ransac.rs         # RANSAC 算法
│   │   └── matrix.rs         # 矩阵操作
│   ├── io/                    # 输入输出
│   │   ├── mod.rs
│   │   ├── image_io.rs       # 图像读写
│   │   ├── model_io.rs       # 模型导入导出
│   │   └── database.rs       # 数据库操作
│   └── utils/                 # 工具函数
│       ├── mod.rs
│       ├── logging.rs        # 日志记录
│       ├── parallel.rs       # 并行计算
│       └── config.rs         # 配置管理
```

### 2.2 核心数据结构设计

#### 2.2.1 相机模型 (core/camera.rs)

```rust
/// 相机内参模型
#[derive(Debug, Clone, PartialEq)]
pub struct CameraIntrinsics {
    /// 焦距 (fx, fy)
    pub focal_length: (f64, f64),
    /// 主点 (cx, cy)
    pub principal_point: (f64, f64),
    /// 畸变参数
    pub distortion: DistortionModel,
}

/// 畸变模型
#[derive(Debug, Clone, PartialEq)]
pub enum DistortionModel {
    /// 无畸变
    None,
    /// 径向畸变 (k1, k2, k3)
    Radial([f64; 3]),
    /// 径向+切向畸变 (k1, k2, p1, p2, k3)
    RadialTangential([f64; 5]),
}

/// 相机外参(姿态)
#[derive(Debug, Clone, PartialEq)]
pub struct CameraPose {
    /// 旋转(四元数)
    pub rotation: nalgebra::UnitQuaternion<f64>,
    /// 平移向量
    pub translation: nalgebra::Vector3<f64>,
}

/// 完整的相机模型
#[derive(Debug, Clone)]
pub struct Camera {
    pub id: u32,
    pub intrinsics: CameraIntrinsics,
    pub pose: Option<CameraPose>,
    pub image_size: (u32, u32),
}
```

#### 2.2.2 图像和特征 (core/image.rs, core/feature.rs)

```rust
/// 图像数据结构
#[derive(Debug, Clone)]
pub struct Image {
    pub id: u32,
    pub name: String,
    pub camera_id: u32,
    pub features: Vec<Feature>,
    pub registered: bool,
}

/// 特征点
#[derive(Debug, Clone, PartialEq)]
pub struct Feature {
    /// 图像坐标 (x, y)
    pub point: nalgebra::Point2<f64>,
    /// 特征描述符
    pub descriptor: Vec<u8>,
    /// 对应的 3D 点 ID(如果已三角化)
    pub point3d_id: Option<u32>,
}

/// 特征匹配
#[derive(Debug, Clone, PartialEq)]
pub struct FeatureMatch {
    pub image1_id: u32,
    pub image2_id: u32,
    pub feature1_idx: usize,
    pub feature2_idx: usize,
    pub distance: f32,
}
```

#### 2.2.3 3D 点和重建 (core/point3d.rs, core/reconstruction.rs)

```rust
/// 3D 点
#[derive(Debug, Clone, PartialEq)]
pub struct Point3D {
    pub id: u32,
    /// 3D 坐标
    pub position: nalgebra::Point3<f64>,
    /// RGB 颜色
    pub color: [u8; 3],
    /// 观测轨迹
    pub track: Track,
    /// 重投影误差
    pub error: f64,
}

/// 观测轨迹
#[derive(Debug, Clone, PartialEq)]
pub struct Track {
    /// 观测列表 (image_id, feature_idx)
    pub observations: Vec<(u32, usize)>,
}

/// 重建结果
#[derive(Debug, Clone)]
pub struct Reconstruction {
    /// 相机集合
    pub cameras: HashMap<u32, Camera>,
    /// 图像集合
    pub images: HashMap<u32, Image>,
    /// 3D 点集合
    pub points3d: HashMap<u32, Point3D>,
    /// 重建统计信息
    pub stats: ReconstructionStats,
}
```

### 2.3 接口设计原则

#### 2.3.1 特征提取器接口

```rust
/// 特征检测器 trait
pub trait FeatureDetector {
    type Config;
    
    fn new(config: Self::Config) -> Self;
    fn detect(&self, image: &ImageBuffer<Rgb<u8>, Vec<u8>>) -> Result<Vec<Feature>>;
}

/// 特征匹配器 trait
pub trait FeatureMatcher {
    type Config;
    
    fn new(config: Self::Config) -> Self;
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>>;
}
```

#### 2.3.2 SfM 重建器接口

```rust
/// SfM 重建器 trait
pub trait SfmReconstructor {
    type Config;
    
    fn new(config: Self::Config) -> Self;
    fn reconstruct(
        &mut self,
        images: &[Image],
        matches: &[FeatureMatch],
    ) -> Result<Reconstruction>;
}
```

### 2.4 错误处理设计

```rust
/// 库错误类型
#[derive(Debug, thiserror::Error)]
pub enum ColmapError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    
    #[error("Image processing error: {0}")]
    ImageProcessing(String),
    
    #[error("Feature extraction failed: {0}")]
    FeatureExtraction(String),
    
    #[error("SfM reconstruction failed: {0}")]
    SfmReconstruction(String),
    
    #[error("MVS reconstruction failed: {0}")]
    MvsReconstruction(String),
    
    #[error("Mathematical computation error: {0}")]
    Math(String),
    
    #[error("Configuration error: {0}")]
    Config(String),
}

pub type Result<T> = std::result::Result<T, ColmapError>;
```

### 2.5 配置管理

```rust
/// 全局配置
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ColmapConfig {
    pub feature: FeatureConfig,
    pub sfm: SfmConfig,
    pub mvs: MvsConfig,
    pub parallel: ParallelConfig,
}

/// 特征提取配置
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct FeatureConfig {
    pub detector_type: DetectorType,
    pub max_features: usize,
    pub match_ratio: f32,
}

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum DetectorType {
    Sift,
    Orb,
}
```

## 3. 依赖管理策略

### 3.1 核心依赖

```toml
[dependencies]
# 线性代数和数值计算
nalgebra = { version = "0.32", features = ["serde-serialize"] }
nalgebra-sparse = "0.9"

# 图像处理
image = { version = "0.24", features = ["jpeg", "png", "tiff"] }
imageproc = "0.23"

# 计算机视觉算法
opencv = { version = "0.88", features = ["opencv-4"] }

# 并行计算
rayon = "1.7"

# 序列化
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# 错误处理
thiserror = "1.0"
anyhow = "1.0"

# 日志
log = "0.4"
env_logger = "0.10"

# 数学优化
argmin = "0.8"
argmin-math = "0.3"
```

### 3.2 开发依赖

```toml
[dev-dependencies]
# 测试框架
criterion = { version = "0.5", features = ["html_reports"] }
proptest = "1.0"
rstest = "0.18"

# 临时文件
tempfile = "3.0"

# 测试数据
test-case = "3.0"
```

## 4. 性能考虑

### 4.1 内存管理
- 使用 `Arc<T>``Rc<T>` 共享大型数据结构
- 实现 `Clone` trait 时优先使用引用计数
- 对于大型矩阵操作,考虑使用视图而非拷贝

### 4.2 并行计算
- 使用 `rayon` 进行数据并行
- 特征提取和匹配天然适合并行化
- 束调整等优化算法可以并行化雅可比矩阵计算

### 4.3 SIMD 优化
- 在关键路径使用 SIMD 指令
- 特征描述符计算和匹配是主要优化目标

## 5. 测试策略

### 5.1 单元测试
- 每个模块都有对应的测试文件
- 使用 `proptest` 进行属性测试
- 数学函数需要精度测试

### 5.2 集成测试
- 端到端的重建管道测试
- 使用标准数据集验证结果
- 性能回归测试

### 5.3 基准测试
- 使用 `criterion` 进行性能基准测试
- 与 C++ COLMAP 进行性能对比
- 内存使用情况监控

## 6. 文档策略

### 6.1 API 文档
- 所有公共接口都有详细的文档注释
- 包含使用示例和数学公式
- 使用 `cargo doc` 生成 HTML 文档

### 6.2 教程和指南
- 快速入门教程
- 高级使用指南
- 算法原理解释

---

**设计原则总结**:
1. **模块化**:清晰的模块边界,便于维护和测试
2. **类型安全**:充分利用 Rust 的类型系统防止错误
3. **性能优先**:在保证正确性的前提下追求最佳性能
4. **可扩展性**:接口设计支持未来功能扩展
5. **易用性**:提供简洁直观的 API 接口

这个架构设计为后续的具体实现提供了清晰的指导方针。