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
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
//! 三角化算法实现

use crate::core::{
    Camera, CameraPose, Point2, Point3, Vector3, Result, ColmapError
};
use nalgebra::{Matrix4, SVD};

/// 三角化方法
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TriangulationMethod {
    /// 线性三角化(DLT)
    Linear,
    /// 迭代三角化
    Iterative,
    /// 中点法
    Midpoint,
}

/// 三角化配置
#[derive(Debug, Clone)]
pub struct TriangulationConfig {
    /// 三角化方法
    pub method: TriangulationMethod,
    /// 最小三角化角度(弧度)
    pub min_angle: f64,
    /// 最大重投影误差
    pub max_reprojection_error: f64,
    /// 迭代法的最大迭代次数
    pub max_iterations: usize,
    /// 收敛阈值
    pub convergence_threshold: f64,
}

impl Default for TriangulationConfig {
    fn default() -> Self {
        Self {
            method: TriangulationMethod::Linear,
            min_angle: 1.0_f64.to_radians(),
            max_reprojection_error: 4.0,
            max_iterations: 100,
            convergence_threshold: 1e-6,
        }
    }
}

/// 三角化结果
#[derive(Debug, Clone)]
pub struct TriangulationResult {
    /// 三角化的3D点
    pub point: Point3,
    /// 是否成功
    pub success: bool,
    /// 重投影误差
    pub reprojection_error: f64,
    /// 三角化角度
    pub triangulation_angle: f64,
}

/// 三角化器
#[derive(Debug)]
pub struct Triangulator {
    config: TriangulationConfig,
}

impl Triangulator {
    /// 创建新的三角化器
    pub fn new(config: TriangulationConfig) -> Self {
        Self { config }
    }

    /// 使用默认配置创建三角化器
    pub fn default() -> Self {
        Self::new(TriangulationConfig::default())
    }

    /// 三角化两个视图中的对应点
    pub fn triangulate_two_view(
        &self,
        camera1: &Camera,
        pose1: &CameraPose,
        point1: &Point2,
        camera2: &Camera,
        pose2: &CameraPose,
        point2: &Point2,
    ) -> Result<TriangulationResult> {
        // 检查三角化角度
        let angle = self.compute_triangulation_angle(
            camera1, pose1, point1,
            camera2, pose2, point2,
        )?;
        
        if angle < self.config.min_angle {
            return Ok(TriangulationResult {
                point: Point3::new(0.0, 0.0, 0.0),
                success: false,
                reprojection_error: f64::INFINITY,
                triangulation_angle: angle,
            });
        }

        // 根据配置选择三角化方法
        let point = match self.config.method {
            TriangulationMethod::Linear => {
                self.triangulate_linear(camera1, pose1, point1, camera2, pose2, point2)?
            },
            TriangulationMethod::Iterative => {
                self.triangulate_iterative(camera1, pose1, point1, camera2, pose2, point2)?
            },
            TriangulationMethod::Midpoint => {
                self.triangulate_midpoint(camera1, pose1, point1, camera2, pose2, point2)?
            },
        };

        // 计算重投影误差
        let error1 = self.compute_reprojection_error(camera1, pose1, &point, point1)?;
        let error2 = self.compute_reprojection_error(camera2, pose2, &point, point2)?;
        let reprojection_error = (error1 + error2) / 2.0;

        let success = reprojection_error < self.config.max_reprojection_error;

        Ok(TriangulationResult {
            point,
            success,
            reprojection_error,
            triangulation_angle: angle,
        })
    }

    /// 多视图三角化
    pub fn triangulate_multi_view(
        &self,
        observations: &[(Camera, CameraPose, Point2)],
    ) -> Result<TriangulationResult> {
        if observations.len() < 2 {
            return Err(ColmapError::Triangulation(
                "至少需要两个观测点进行三角化".to_string()
            ));
        }

        // 使用前两个观测进行初始三角化
        let (camera1, pose1, point1) = &observations[0];
        let (camera2, pose2, point2) = &observations[1];
        
        let mut result = self.triangulate_two_view(
            camera1, pose1, point1,
            camera2, pose2, point2,
        )?;

        if !result.success {
            return Ok(result);
        }

        // 如果有更多观测,使用迭代优化
        if observations.len() > 2 {
            result.point = self.refine_point_multi_view(&result.point, observations)?;
            
            // 重新计算重投影误差
            let mut total_error = 0.0;
            for (camera, pose, point) in observations {
                let error = self.compute_reprojection_error(camera, pose, &result.point, point)?;
                total_error += error;
            }
            result.reprojection_error = total_error / observations.len() as f64;
            result.success = result.reprojection_error < self.config.max_reprojection_error;
        }

        Ok(result)
    }

    /// 线性三角化(DLT方法)
    fn triangulate_linear(
        &self,
        camera1: &Camera,
        pose1: &CameraPose,
        point1: &Point2,
        camera2: &Camera,
        pose2: &CameraPose,
        point2: &Point2,
    ) -> Result<Point3> {
        // 构建投影矩阵
        let p1 = self.build_projection_matrix(camera1, pose1)?;
        let p2 = self.build_projection_matrix(camera2, pose2)?;

        // 归一化图像坐标
        let norm1 = camera1.image_to_normalized(point1)?;
        let norm2 = camera2.image_to_normalized(point2)?;

        // 构建线性方程组 AX = 0
        let mut a = Matrix4::zeros();
        
        // 第一个相机的约束
        a.set_row(0, &(norm1.x * p1.row(2) - p1.row(0)));
        a.set_row(1, &(norm1.y * p1.row(2) - p1.row(1)));
        
        // 第二个相机的约束
        a.set_row(2, &(norm2.x * p2.row(2) - p2.row(0)));
        a.set_row(3, &(norm2.y * p2.row(2) - p2.row(1)));

        // 使用SVD求解
        let svd = SVD::new(a, true, true);
        let v = svd.v_t.ok_or_else(|| ColmapError::Triangulation(
            "SVD分解失败".to_string()
        ))?;
        
        let solution = v.row(3);
        
        if solution[3].abs() < 1e-10 {
            return Err(ColmapError::Triangulation(
                "齐次坐标的w分量接近零".to_string()
            ));
        }

        Ok(Point3::new(
            solution[0] / solution[3],
            solution[1] / solution[3],
            solution[2] / solution[3],
        ))
    }

    /// 迭代三角化
    fn triangulate_iterative(
        &self,
        camera1: &Camera,
        pose1: &CameraPose,
        point1: &Point2,
        camera2: &Camera,
        pose2: &CameraPose,
        point2: &Point2,
    ) -> Result<Point3> {
        // 先用线性方法获得初始估计
        let mut point = self.triangulate_linear(camera1, pose1, point1, camera2, pose2, point2)?;

        // 迭代优化
        for _ in 0..self.config.max_iterations {
            let old_point = point;
            
            // 计算雅可比矩阵和残差
            let (jacobian, residual) = self.compute_jacobian_and_residual(
                &point,
                &[(camera1.clone(), pose1.clone(), *point1),
                  (camera2.clone(), pose2.clone(), *point2)],
            )?;

            // 求解线性系统
            let jtj = jacobian.transpose() * &jacobian;
            let jtr = jacobian.transpose() * residual;
            
            let svd = SVD::new(jtj, true, true);
            let delta = svd.solve(&jtr, 1e-10).map_err(|_| ColmapError::Triangulation(
                "无法求解线性系统".to_string()
            ))?;

            // 更新点坐标
            point.coords += delta;

            // 检查收敛
            if (point - old_point).norm() < self.config.convergence_threshold {
                break;
            }
        }

        Ok(point)
    }

    /// 中点法三角化
    fn triangulate_midpoint(
        &self,
        camera1: &Camera,
        pose1: &CameraPose,
        point1: &Point2,
        camera2: &Camera,
        pose2: &CameraPose,
        point2: &Point2,
    ) -> Result<Point3> {
        // 获取相机中心和射线方向
        let center1 = pose1.translation;
        let center2 = pose2.translation;
        
        let ray1 = self.compute_ray_direction(camera1, pose1, point1)?;
        let ray2 = self.compute_ray_direction(camera2, pose2, point2)?;

        // 计算两条射线的最近点
        let center1_point = Point3::new(center1.x, center1.y, center1.z);
        let center2_point = Point3::new(center2.x, center2.y, center2.z);
        let (t1, t2) = self.compute_closest_points_on_rays(&center1_point, &ray1, &center2_point, &ray2)?;
        
        let point1_on_ray = center1 + t1 * ray1;
        let point2_on_ray = center2 + t2 * ray2;
        
        // 返回中点
        let midpoint = (point1_on_ray + point2_on_ray) / 2.0;
        Ok(Point3::new(midpoint.x, midpoint.y, midpoint.z))
    }

    /// 计算三角化角度
    fn compute_triangulation_angle(
        &self,
        camera1: &Camera,
        pose1: &CameraPose,
        point1: &Point2,
        camera2: &Camera,
        pose2: &CameraPose,
        point2: &Point2,
    ) -> Result<f64> {
        let _center1 = pose1.translation;
        let _center2 = pose2.translation;
        
        let ray1 = self.compute_ray_direction(camera1, pose1, point1)?;
        let ray2 = self.compute_ray_direction(camera2, pose2, point2)?;
        
        let cos_angle = ray1.dot(&ray2) / (ray1.norm() * ray2.norm());
        Ok(cos_angle.acos())
    }

    /// 计算射线方向
    fn compute_ray_direction(
        &self,
        camera: &Camera,
        pose: &CameraPose,
        point: &Point2,
    ) -> Result<Vector3> {
        let normalized = camera.image_to_normalized(point)?;
        let ray_camera = Vector3::new(normalized.x, normalized.y, 1.0).normalize();
        Ok(pose.rotation * ray_camera)
    }

    /// 计算两条射线上的最近点参数
    fn compute_closest_points_on_rays(
        &self,
        origin1: &Point3,
        dir1: &Vector3,
        origin2: &Point3,
        dir2: &Vector3,
    ) -> Result<(f64, f64)> {
        let w = origin1 - origin2;
        let a = dir1.dot(dir1);
        let b = dir1.dot(dir2);
        let c = dir2.dot(dir2);
        let d = dir1.dot(&w);
        let e = dir2.dot(&w);
        
        let denom = a * c - b * b;
        if denom.abs() < 1e-10 {
            return Err(ColmapError::Triangulation(
                "射线平行,无法三角化".to_string()
            ));
        }
        
        let t1 = (b * e - c * d) / denom;
        let t2 = (a * e - b * d) / denom;
        
        Ok((t1, t2))
    }

    /// 构建投影矩阵
    fn build_projection_matrix(&self, camera: &Camera, pose: &CameraPose) -> Result<nalgebra::Matrix3x4<f64>> {
        let k = camera.calibration_matrix();
        let rt = pose.to_matrix3x4();
        Ok(k * rt)
    }

    /// 计算重投影误差
    fn compute_reprojection_error(
        &self,
        camera: &Camera,
        pose: &CameraPose,
        point3d: &Point3,
        observed: &Point2,
    ) -> Result<f64> {
        // 需要先设置相机姿态
        let mut temp_camera = camera.clone();
        temp_camera.set_pose(pose.clone());
        let projected = temp_camera.world_to_image(point3d)?;
        let dx = projected.x - observed.x;
        let dy = projected.y - observed.y;
        Ok((dx * dx + dy * dy).sqrt())
    }

    /// 多视图点优化
    fn refine_point_multi_view(
        &self,
        initial_point: &Point3,
        observations: &[(Camera, CameraPose, Point2)],
    ) -> Result<Point3> {
        let mut point = *initial_point;
        
        for _ in 0..self.config.max_iterations {
            let old_point = point;
            
            let (jacobian, residual) = self.compute_jacobian_and_residual(&point, observations)?;
            
            let jtj = jacobian.transpose() * &jacobian;
            let jtr = jacobian.transpose() * residual;
            
            let svd = SVD::new(jtj, true, true);
            let delta = svd.solve(&jtr, 1e-10).map_err(|_| ColmapError::Triangulation(
                "无法求解线性系统".to_string()
            ))?;

            point.coords += delta;

            if (point - old_point).norm() < self.config.convergence_threshold {
                break;
            }
        }
        
        Ok(point)
    }

    /// 计算雅可比矩阵和残差
    fn compute_jacobian_and_residual(
        &self,
        point: &Point3,
        observations: &[(Camera, CameraPose, Point2)],
    ) -> Result<(nalgebra::DMatrix<f64>, nalgebra::DVector<f64>)> {
        let num_observations = observations.len();
        let mut jacobian = nalgebra::DMatrix::zeros(2 * num_observations, 3);
        let mut residual = nalgebra::DVector::zeros(2 * num_observations);
        
        for (i, (camera, pose, observed)) in observations.iter().enumerate() {
            // 需要先设置相机姿态
            let mut temp_camera = camera.clone();
            temp_camera.set_pose(pose.clone());
            let projected = temp_camera.world_to_image(point)?;
            
            // 残差
            residual[2 * i] = projected.x - observed.x;
            residual[2 * i + 1] = projected.y - observed.y;
            
            // 雅可比矩阵(简化实现)
            let eps = 1e-6;
            for j in 0..3 {
                let mut point_plus = *point;
                point_plus[j] += eps;
                // 需要先设置相机姿态
                let mut temp_camera = camera.clone();
                temp_camera.set_pose(pose.clone());
                let projected_plus = temp_camera.world_to_image(&point_plus)?;
                
                jacobian[(2 * i, j)] = (projected_plus.x - projected.x) / eps;
                jacobian[(2 * i + 1, j)] = (projected_plus.y - projected.y) / eps;
            }
        }
        
        Ok((jacobian, residual))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_triangulator_creation() {
        let triangulator = Triangulator::default();
        assert_eq!(triangulator.config.method, TriangulationMethod::Linear);
    }

    #[test]
    fn test_triangulation_config() {
        let config = TriangulationConfig {
            method: TriangulationMethod::Iterative,
            min_angle: 2.0_f64.to_radians(),
            max_reprojection_error: 2.0,
            max_iterations: 50,
            convergence_threshold: 1e-8,
        };
        
        let triangulator = Triangulator::new(config);
        assert_eq!(triangulator.config.method, TriangulationMethod::Iterative);
        assert_eq!(triangulator.config.max_iterations, 50);
    }
}