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
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
//! 特征匹配器模块
//! 
//! 提供统一的特征匹配接口,支持多种匹配算法

use crate::core::{Feature, ColmapError};
use std::collections::HashMap;

/// 特征匹配结果
#[derive(Debug, Clone)]
pub struct FeatureMatch {
    /// 第一个图像中的特征点索引
    pub query_idx: usize,
    /// 第二个图像中的特征点索引
    pub train_idx: usize,
    /// 匹配距离
    pub distance: f64,
    /// 匹配置信度
    pub confidence: f64,
}

impl FeatureMatch {
    /// 创建新的特征匹配
    pub fn new(query_idx: usize, train_idx: usize, distance: f64) -> Self {
        Self {
            query_idx,
            train_idx,
            distance,
            confidence: 1.0 / (1.0 + distance),
        }
    }
    
    /// 检查匹配是否有效
    pub fn is_valid(&self, max_distance: f64) -> bool {
        self.distance <= max_distance
    }
}

/// 特征匹配器的通用接口
pub trait FeatureMatcher: Send + Sync {
    /// 匹配两组特征点
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>, ColmapError>;
    
    /// 获取匹配器名称
    fn name(&self) -> &str;
    
    /// 获取匹配器参数
    fn params(&self) -> HashMap<String, f64>;
    
    /// 设置匹配器参数
    fn set_params(&mut self, params: HashMap<String, f64>) -> Result<(), ColmapError>;
}

/// 匹配器类型
#[derive(Debug, Clone, PartialEq)]
pub enum MatcherType {
    /// 暴力匹配器
    BruteForce,
    /// FLANN 匹配器
    Flann,
    /// 基于比值的匹配器
    RatioTest,
    /// 交叉检查匹配器
    CrossCheck,
}

/// 距离度量类型
#[derive(Debug, Clone, PartialEq)]
pub enum DistanceType {
    /// 欧几里得距离(L2)
    L2,
    /// 曼哈顿距离(L1)
    L1,
    /// 汉明距离(用于二进制描述符)
    Hamming,
    /// 余弦距离
    Cosine,
}

/// 匹配器配置
#[derive(Debug, Clone)]
pub struct MatcherConfig {
    /// 匹配器类型
    pub matcher_type: MatcherType,
    /// 距离度量类型
    pub distance_type: DistanceType,
    /// 最大匹配距离
    pub max_distance: f64,
    /// 比值测试阈值
    pub ratio_threshold: f64,
    /// 是否启用交叉检查
    pub cross_check: bool,
    /// 最大匹配数量
    pub max_matches: usize,
    /// 最小匹配置信度
    pub min_confidence: f64,
}

impl Default for MatcherConfig {
    fn default() -> Self {
        Self {
            matcher_type: MatcherType::BruteForce,
            distance_type: DistanceType::L2,
            max_distance: 0.7,
            ratio_threshold: 0.8,
            cross_check: true,
            max_matches: 1000,
            min_confidence: 0.1,
        }
    }
}

/// 匹配器工厂
pub struct MatcherFactory;

impl MatcherFactory {
    /// 创建特征匹配器
    pub fn create(config: &MatcherConfig) -> Result<Box<dyn FeatureMatcher>, ColmapError> {
        match config.matcher_type {
            MatcherType::BruteForce => {
                Ok(Box::new(BruteForceMatcher::new(config)?))
            },
            MatcherType::Flann => {
                Ok(Box::new(FlannMatcher::new(config)?))
            },
            MatcherType::RatioTest => {
                Ok(Box::new(RatioTestMatcher::new(config)?))
            },
            MatcherType::CrossCheck => {
                Ok(Box::new(CrossCheckMatcher::new(config)?))
            },
        }
    }
}

/// 暴力匹配器
pub struct BruteForceMatcher {
    config: MatcherConfig,
}

impl BruteForceMatcher {
    pub fn new(config: &MatcherConfig) -> Result<Self, ColmapError> {
        Ok(Self {
            config: config.clone(),
        })
    }
    
    /// 计算描述符距离
    fn compute_distance(&self, desc1: &[u8], desc2: &[u8]) -> f64 {
        match self.config.distance_type {
            DistanceType::L2 => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
                    .sum::<f64>().sqrt()
            },
            DistanceType::L1 => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (*a as f64 - *b as f64).abs())
                    .sum::<f64>()
            },
            DistanceType::Hamming => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (a ^ b).count_ones() as f64)
                    .sum::<f64>()
            },
            DistanceType::Cosine => {
                let dot_product: f64 = desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| *a as f64 * *b as f64)
                    .sum();
                let norm1: f64 = desc1.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
                let norm2: f64 = desc2.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
                
                if norm1 == 0.0 || norm2 == 0.0 {
                    1.0
                } else {
                    1.0 - (dot_product / (norm1 * norm2))
                }
            },
        }
    }
}

impl FeatureMatcher for BruteForceMatcher {
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>, ColmapError> {
        let mut matches = Vec::new();
        
        // 暴力匹配:对每个特征点找到最佳匹配
        for (i, feat1) in features1.iter().enumerate() {
            if feat1.descriptor.is_empty() {
                continue;
            }
            
            let mut best_distance = f64::INFINITY;
            let mut best_idx = None;
            
            for (j, feat2) in features2.iter().enumerate() {
                if feat2.descriptor.is_empty() || feat1.descriptor.len() != feat2.descriptor.len() {
                    continue;
                }
                
                let distance = self.compute_distance(&feat1.descriptor, &feat2.descriptor);
                
                if distance < best_distance && distance <= self.config.max_distance {
                    best_distance = distance;
                    best_idx = Some(j);
                }
            }
            
            if let Some(j) = best_idx {
                let match_result = FeatureMatch::new(i, j, best_distance);
                if match_result.confidence >= self.config.min_confidence {
                    matches.push(match_result);
                }
            }
        }
        
        // 按距离排序并限制匹配数量
        matches.sort_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap());
        matches.truncate(self.config.max_matches);
        
        Ok(matches)
    }
    
    fn name(&self) -> &str {
        "BruteForce"
    }
    
    fn params(&self) -> HashMap<String, f64> {
        let mut params = HashMap::new();
        params.insert("max_distance".to_string(), self.config.max_distance);
        params.insert("max_matches".to_string(), self.config.max_matches as f64);
        params.insert("min_confidence".to_string(), self.config.min_confidence);
        params
    }
    
    fn set_params(&mut self, params: HashMap<String, f64>) -> Result<(), ColmapError> {
        for (key, value) in params {
            match key.as_str() {
                "max_distance" => self.config.max_distance = value,
                "max_matches" => self.config.max_matches = value as usize,
                "min_confidence" => self.config.min_confidence = value,
                _ => return Err(ColmapError::InvalidParameter(format!("Unknown parameter: {}", key))),
            }
        }
        Ok(())
    }
}

/// FLANN 匹配器
pub struct FlannMatcher {
    config: MatcherConfig,
}

impl FlannMatcher {
    pub fn new(config: &MatcherConfig) -> Result<Self, ColmapError> {
        Ok(Self {
            config: config.clone(),
        })
    }
}

impl FeatureMatcher for FlannMatcher {
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>, ColmapError> {
        let mut matches = Vec::new();
        
        // 使用 KD-tree 或近似最近邻搜索的简化实现
        for (i, feat1) in features1.iter().enumerate() {
            if feat1.descriptor.is_empty() {
                continue;
            }
            
            let mut best_distance = f64::INFINITY;
            let mut best_idx = None;
            
            for (j, feat2) in features2.iter().enumerate() {
                if feat2.descriptor.is_empty() || feat1.descriptor.len() != feat2.descriptor.len() {
                    continue;
                }
                
                let distance = self.compute_distance(&feat1.descriptor, &feat2.descriptor);
                
                if distance < best_distance && distance <= self.config.max_distance {
                    best_distance = distance;
                    best_idx = Some(j);
                }
            }
            
            if let Some(j) = best_idx {
                let match_result = FeatureMatch::new(i, j, best_distance);
                if match_result.confidence >= self.config.min_confidence {
                    matches.push(match_result);
                }
            }
        }
        
        // 限制匹配数量
        matches.sort_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap());
        matches.truncate(self.config.max_matches);
        
        Ok(matches)
    }
    
    fn name(&self) -> &str {
        "FLANN"
    }
    
    fn params(&self) -> HashMap<String, f64> {
        let mut params = HashMap::new();
        params.insert("max_distance".to_string(), self.config.max_distance);
        params.insert("max_matches".to_string(), self.config.max_matches as f64);
        params.insert("min_confidence".to_string(), self.config.min_confidence);
        params
    }
    
    fn set_params(&mut self, params: HashMap<String, f64>) -> Result<(), ColmapError> {
        for (key, value) in params {
            match key.as_str() {
                "max_distance" => self.config.max_distance = value,
                "max_matches" => self.config.max_matches = value as usize,
                "min_confidence" => self.config.min_confidence = value,
                _ => return Err(ColmapError::InvalidParameter(format!("Unknown parameter: {}", key))),
            }
        }
        Ok(())
    }
}

impl FlannMatcher {
    /// 计算描述符距离
    fn compute_distance(&self, desc1: &[u8], desc2: &[u8]) -> f64 {
        match self.config.distance_type {
            DistanceType::L2 => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
                    .sum::<f64>().sqrt()
            },
            DistanceType::L1 => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (*a as f64 - *b as f64).abs())
                    .sum::<f64>()
            },
            DistanceType::Hamming => {
                desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| (a ^ b).count_ones() as f64)
                    .sum::<f64>()
            },
            DistanceType::Cosine => {
                let dot_product: f64 = desc1.iter().zip(desc2.iter())
                    .map(|(a, b)| *a as f64 * *b as f64)
                    .sum();
                let norm1: f64 = desc1.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
                let norm2: f64 = desc2.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
                
                if norm1 == 0.0 || norm2 == 0.0 {
                    1.0
                } else {
                    1.0 - (dot_product / (norm1 * norm2))
                }
            },
        }
    }
}

/// 比值测试匹配器
pub struct RatioTestMatcher {
    config: MatcherConfig,
    base_matcher: BruteForceMatcher,
}

impl RatioTestMatcher {
    pub fn new(config: &MatcherConfig) -> Result<Self, ColmapError> {
        let base_matcher = BruteForceMatcher::new(config)?;
        
        Ok(Self {
            config: config.clone(),
            base_matcher,
        })
    }
}

impl FeatureMatcher for RatioTestMatcher {
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>, ColmapError> {
        let mut matches = Vec::new();
        
        // 对每个特征点找到两个最佳匹配
        for (i, feat1) in features1.iter().enumerate() {
            if feat1.descriptor.is_empty() {
                continue;
            }
            
            let mut distances: Vec<(usize, f64)> = Vec::new();
            
            for (j, feat2) in features2.iter().enumerate() {
                if feat2.descriptor.is_empty() || feat1.descriptor.len() != feat2.descriptor.len() {
                    continue;
                }
                
                let distance = self.base_matcher.compute_distance(&feat1.descriptor, &feat2.descriptor);
                distances.push((j, distance));
            }
            
            // 按距离排序
            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            
            // 比值测试:最佳匹配距离 / 次佳匹配距离 < 阈值
            if distances.len() >= 2 {
                let best_distance = distances[0].1;
                let second_best_distance = distances[1].1;
                
                if best_distance <= self.config.max_distance &&
                   best_distance / second_best_distance < self.config.ratio_threshold {
                    let match_result = FeatureMatch::new(i, distances[0].0, best_distance);
                    if match_result.confidence >= self.config.min_confidence {
                        matches.push(match_result);
                    }
                }
            }
        }
        
        // 限制匹配数量
        matches.sort_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap());
        matches.truncate(self.config.max_matches);
        
        Ok(matches)
    }
    
    fn name(&self) -> &str {
        "RatioTest"
    }
    
    fn params(&self) -> HashMap<String, f64> {
        let mut params = self.base_matcher.params();
        params.insert("ratio_threshold".to_string(), self.config.ratio_threshold);
        params
    }
    
    fn set_params(&mut self, params: HashMap<String, f64>) -> Result<(), ColmapError> {
        if let Some(&ratio) = params.get("ratio_threshold") {
            self.config.ratio_threshold = ratio;
        }
        self.base_matcher.set_params(params)
    }
}

/// 交叉检查匹配器
pub struct CrossCheckMatcher {
    config: MatcherConfig,
    base_matcher: BruteForceMatcher,
}

impl CrossCheckMatcher {
    pub fn new(config: &MatcherConfig) -> Result<Self, ColmapError> {
        let base_matcher = BruteForceMatcher::new(config)?;
        
        Ok(Self {
            config: config.clone(),
            base_matcher,
        })
    }
}

impl FeatureMatcher for CrossCheckMatcher {
    fn match_features(
        &self,
        features1: &[Feature],
        features2: &[Feature],
    ) -> Result<Vec<FeatureMatch>, ColmapError> {
        // 正向匹配:features1 -> features2
        let forward_matches = self.base_matcher.match_features(features1, features2)?;
        
        // 反向匹配:features2 -> features1
        let backward_matches = self.base_matcher.match_features(features2, features1)?;
        
        // 交叉检查:只保留双向一致的匹配
        let mut cross_checked_matches = Vec::new();
        
        for forward_match in forward_matches {
            // 检查是否存在对应的反向匹配
            for backward_match in &backward_matches {
                if backward_match.query_idx == forward_match.train_idx &&
                   backward_match.train_idx == forward_match.query_idx {
                    // 使用较小的距离作为最终距离
                    let final_distance = forward_match.distance.min(backward_match.distance);
                    let cross_match = FeatureMatch::new(
                        forward_match.query_idx,
                        forward_match.train_idx,
                        final_distance,
                    );
                    
                    if cross_match.confidence >= self.config.min_confidence {
                        cross_checked_matches.push(cross_match);
                    }
                    break;
                }
            }
        }
        
        // 限制匹配数量
        cross_checked_matches.sort_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap());
        cross_checked_matches.truncate(self.config.max_matches);
        
        Ok(cross_checked_matches)
    }
    
    fn name(&self) -> &str {
        "CrossCheck"
    }
    
    fn params(&self) -> HashMap<String, f64> {
        self.base_matcher.params()
    }
    
    fn set_params(&mut self, params: HashMap<String, f64>) -> Result<(), ColmapError> {
        self.base_matcher.set_params(params)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Feature;
    use nalgebra::Point2;
    
    fn create_test_features() -> Vec<Feature> {
        vec![
            Feature {
                point: Point2::new(10.0, 20.0),
                descriptor: vec![1, 2, 3, 4],
                response: 0.8,
                angle: 0.0,
                octave: 0,
                scale: 1.0,
                point3d_id: None,
            },
            Feature {
                point: Point2::new(30.0, 40.0),
                descriptor: vec![5, 6, 7, 8],
                response: 0.9,
                angle: 0.0,
                octave: 0,
                scale: 1.0,
                point3d_id: None,
            },
        ]
    }
    
    #[test]
    fn test_feature_match_creation() {
        let match_result = FeatureMatch::new(0, 1, 0.5);
        assert_eq!(match_result.query_idx, 0);
        assert_eq!(match_result.train_idx, 1);
        assert_eq!(match_result.distance, 0.5);
        assert!(match_result.is_valid(1.0));
        assert!(!match_result.is_valid(0.3));
    }
    
    #[test]
    fn test_matcher_config_default() {
        let config = MatcherConfig::default();
        assert_eq!(config.matcher_type, MatcherType::BruteForce);
        assert_eq!(config.distance_type, DistanceType::L2);
        assert_eq!(config.max_distance, 0.7);
        assert_eq!(config.ratio_threshold, 0.8);
    }
    
    #[test]
    fn test_matcher_factory() {
        let config = MatcherConfig::default();
        let matcher = MatcherFactory::create(&config);
        assert!(matcher.is_ok());
        assert_eq!(matcher.unwrap().name(), "BruteForce");
    }
    
    #[test]
    fn test_brute_force_matcher_creation() {
        let config = MatcherConfig::default();
        let matcher = BruteForceMatcher::new(&config);
        assert!(matcher.is_ok());
    }
    
    #[test]
    fn test_brute_force_matching() {
        let config = MatcherConfig {
            max_distance: 10.0,
            ..Default::default()
        };
        let matcher = BruteForceMatcher::new(&config).unwrap();
        
        let features1 = create_test_features();
        let features2 = create_test_features();
        
        let matches = matcher.match_features(&features1, &features2);
        assert!(matches.is_ok());
        
        let matches = matches.unwrap();
        assert!(!matches.is_empty());
    }
    
    #[test]
    fn test_distance_computation() {
        let config = MatcherConfig {
            distance_type: DistanceType::L2,
            ..Default::default()
        };
        let matcher = BruteForceMatcher::new(&config).unwrap();
        
        let desc1 = vec![1, 2, 3, 4];
        let desc2 = vec![1, 2, 3, 4];
        let distance = matcher.compute_distance(&desc1, &desc2);
        assert_eq!(distance, 0.0);
        
        let desc3 = vec![2, 3, 4, 5];
        let distance = matcher.compute_distance(&desc1, &desc3);
        assert!(distance > 0.0);
    }
}