corrmatch 0.1.0

CPU-first template matching with ZNCC/SSD and coarse-to-fine pyramid search
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
//! Precomputed template assets for coarse-to-fine search.
//!
//! Compiling template assets once amortizes the cost of building pyramids and
//! rotated variants across multiple match calls. Each cached rotation stores
//! precomputed masked plans (ZNCC and SSD) for fast score evaluation.
//! Rotated templates are cached lazily per level; each angle slot is populated
//! at most once and stored in a `OnceLock` for thread-safe reuse when parallel
//! search is introduced later.

mod angles;

pub use angles::AngleGrid;

use crate::image::pyramid::{downsample_u8_2x2_box, ImagePyramid};
use crate::image::{ImageView, OwnedImage};
use crate::template::rotate::rotate_u8_bilinear_masked;
use crate::template::{
    MaskedSsdTemplatePlan, MaskedTemplatePlan, SsdTemplatePlan, Template, TemplatePlan,
};
use crate::util::{CorrMatchError, CorrMatchResult};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
use std::sync::{Arc, OnceLock};

fn trim_degenerate_levels(levels: &mut Vec<OwnedImage>, min_dim: usize) -> CorrMatchResult<()> {
    let mut last_err: Option<CorrMatchError> = None;
    loop {
        let level = match levels.last() {
            Some(level) => level,
            None => {
                return Err(last_err.unwrap_or(CorrMatchError::DegenerateTemplate {
                    reason: "zero variance",
                }));
            }
        };

        if level.width() < min_dim || level.height() < min_dim {
            levels.pop();
            last_err = Some(CorrMatchError::DegenerateTemplate {
                reason: "template too small for rotation",
            });
            continue;
        }

        match TemplatePlan::from_view(level.view()) {
            Ok(_) => return Ok(()),
            Err(err @ CorrMatchError::DegenerateTemplate { .. }) => {
                levels.pop();
                last_err = Some(err);
            }
            Err(err) => return Err(err),
        }
    }
}

fn downsample_mask(mask: &[u8], width: usize, height: usize) -> CorrMatchResult<Vec<u8>> {
    let needed = width
        .checked_mul(height)
        .ok_or(CorrMatchError::InvalidDimensions { width, height })?;
    if mask.len() < needed {
        return Err(CorrMatchError::BufferTooSmall {
            needed,
            got: mask.len(),
        });
    }
    if mask.len() > needed {
        return Err(CorrMatchError::InvalidDimensions { width, height });
    }
    if width < 2 || height < 2 {
        return Err(CorrMatchError::InvalidDimensions { width, height });
    }

    let dst_width = width / 2;
    let dst_height = height / 2;
    let dst_len = dst_width
        .checked_mul(dst_height)
        .ok_or(CorrMatchError::InvalidDimensions {
            width: dst_width,
            height: dst_height,
        })?;
    let mut dst = vec![0u8; dst_len];

    for y in 0..dst_height {
        let row0 = &mask[(y * 2) * width..(y * 2) * width + width];
        let row1 = &mask[(y * 2 + 1) * width..(y * 2 + 1) * width + width];
        for x in 0..dst_width {
            let idx = 2 * x;
            let m = row0[idx] & row0[idx + 1] & row1[idx] & row1[idx + 1];
            dst[y * dst_width + x] = if m == 0 { 0 } else { 1 };
        }
    }

    Ok(dst)
}

fn rotate_downsample_to_level(
    base: ImageView<'_, u8>,
    angle: f32,
    fill: u8,
    level: usize,
) -> CorrMatchResult<(OwnedImage, Vec<u8>)> {
    let (mut img, mut mask) = rotate_u8_bilinear_masked(base, angle, fill);
    for _ in 0..level {
        let view = img.view();
        let next_img = downsample_u8_2x2_box(view)?;
        let next_mask = downsample_mask(&mask, view.width(), view.height())?;
        img = next_img;
        mask = next_mask;
    }
    Ok((img, mask))
}

/// Configuration for compiling template assets with rotation support.
#[derive(Clone, Debug)]
pub struct CompileConfig {
    /// Maximum pyramid levels to build.
    pub max_levels: usize,
    /// Coarse rotation step in degrees at level 0.
    pub coarse_step_deg: f32,
    /// Minimum rotation step in degrees across levels.
    pub min_step_deg: f32,
    /// Fill value used for out-of-bounds rotations.
    pub fill_value: u8,
    /// Precompute all rotations for the coarsest level.
    pub precompute_coarsest: bool,
}

impl Default for CompileConfig {
    fn default() -> Self {
        Self {
            max_levels: 6,
            coarse_step_deg: 10.0,
            min_step_deg: 0.5,
            fill_value: 0,
            precompute_coarsest: true,
        }
    }
}

impl CompileConfig {
    /// Validates the configuration, returning an error if any parameter is invalid.
    pub fn validate(&self) -> CorrMatchResult<()> {
        if self.max_levels == 0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "max_levels must be at least 1",
            });
        }
        if !self.coarse_step_deg.is_finite() || self.coarse_step_deg <= 0.0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "coarse_step_deg must be a positive finite value",
            });
        }
        if !self.min_step_deg.is_finite() || self.min_step_deg <= 0.0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "min_step_deg must be a positive finite value",
            });
        }
        if self.min_step_deg > self.coarse_step_deg {
            return Err(CorrMatchError::InvalidConfig {
                reason: "min_step_deg must not exceed coarse_step_deg",
            });
        }
        Ok(())
    }
}

/// Configuration for compiling template assets without rotation support.
#[derive(Clone, Debug)]
pub struct CompileConfigNoRot {
    /// Maximum pyramid levels to build.
    pub max_levels: usize,
}

impl Default for CompileConfigNoRot {
    fn default() -> Self {
        Self { max_levels: 6 }
    }
}

pub(crate) struct RotatedTemplate {
    angle_deg: f32,
    zncc: MaskedTemplatePlan,
    ssd: MaskedSsdTemplatePlan,
}

impl RotatedTemplate {
    pub(crate) fn zncc_plan(&self) -> &MaskedTemplatePlan {
        &self.zncc
    }

    pub(crate) fn ssd_plan(&self) -> &MaskedSsdTemplatePlan {
        &self.ssd
    }
}

struct LevelBank {
    grid: AngleGrid,
    slots: Vec<OnceLock<RotatedTemplate>>,
}

/// Compiled template assets with rotation support.
pub struct CompiledTemplateRot {
    levels: Vec<OwnedImage>,
    banks: Vec<LevelBank>,
    unmasked_zncc: Vec<TemplatePlan>,
    unmasked_ssd: Vec<SsdTemplatePlan>,
    cfg: CompileConfig,
}

impl CompiledTemplateRot {
    /// Compiles template assets for matching with rotation support.
    pub fn compile(tpl: &Template, cfg: CompileConfig) -> CorrMatchResult<Self> {
        let _span = trace_span!(
            "compile_template",
            rotation = true,
            max_levels = cfg.max_levels
        )
        .entered();

        let pyramid = ImagePyramid::build_u8(tpl.view(), cfg.max_levels)?;
        let mut levels = pyramid.into_levels();
        trim_degenerate_levels(&mut levels, 3)?;

        let mut unmasked_zncc = Vec::with_capacity(levels.len());
        let mut unmasked_ssd = Vec::with_capacity(levels.len());
        for level in levels.iter() {
            unmasked_zncc.push(TemplatePlan::from_view(level.view())?);
            unmasked_ssd.push(SsdTemplatePlan::from_view(level.view())?);
        }

        let mut banks = Vec::with_capacity(levels.len());
        let coarsest_idx = levels.len().saturating_sub(1);
        for (level_idx, _level) in levels.iter().enumerate() {
            let shift = coarsest_idx.saturating_sub(level_idx);
            let factor = (1u64.checked_shl(shift as u32).unwrap_or(u64::MAX)) as f32;
            let step = (cfg.coarse_step_deg / factor).max(cfg.min_step_deg);
            let grid = AngleGrid::full(step)?;
            let slots = (0..grid.len()).map(|_| OnceLock::new()).collect();
            banks.push(LevelBank { grid, slots });
        }

        if cfg.precompute_coarsest {
            let coarsest_idx = levels.len().saturating_sub(1);
            let base = levels.first().ok_or(CorrMatchError::IndexOutOfBounds {
                index: 0,
                len: levels.len(),
                context: "level",
            })?;
            let coarsest = levels
                .get(coarsest_idx)
                .ok_or(CorrMatchError::IndexOutOfBounds {
                    index: coarsest_idx,
                    len: levels.len(),
                    context: "level",
                })?;
            if let Some(bank) = banks.get_mut(coarsest_idx) {
                let _precompute_span =
                    trace_span!("precompute_rotations", count = bank.grid.len()).entered();

                #[cfg(feature = "rayon")]
                {
                    // Parallel precomputation of rotated templates
                    let angles: Vec<(usize, f32)> = bank.grid.iter().enumerate().collect();
                    let results: Vec<CorrMatchResult<(usize, RotatedTemplate)>> = angles
                        .into_par_iter()
                        .map(|(idx, angle)| {
                            let (rotated_img, mask) = rotate_downsample_to_level(
                                base.view(),
                                angle,
                                cfg.fill_value,
                                coarsest_idx,
                            )?;
                            debug_assert_eq!(rotated_img.width(), coarsest.width());
                            debug_assert_eq!(rotated_img.height(), coarsest.height());
                            let mask: Arc<[u8]> = Arc::from(mask);
                            let zncc_plan = MaskedTemplatePlan::from_rotated_parts(
                                rotated_img.view(),
                                mask.clone(),
                                angle,
                            )?;
                            let ssd_plan = MaskedSsdTemplatePlan::from_rotated_parts(
                                rotated_img.view(),
                                mask,
                                angle,
                            )?;
                            let rotated = RotatedTemplate {
                                angle_deg: angle,
                                zncc: zncc_plan,
                                ssd: ssd_plan,
                            };
                            Ok((idx, rotated))
                        })
                        .collect();

                    // Store results (checking for errors)
                    for result in results {
                        let (idx, rotated) = result?;
                        let _ = bank.slots[idx].set(rotated);
                    }
                }

                #[cfg(not(feature = "rayon"))]
                {
                    // Sequential precomputation
                    for (idx, angle) in bank.grid.iter().enumerate() {
                        let (rotated_img, mask) = rotate_downsample_to_level(
                            base.view(),
                            angle,
                            cfg.fill_value,
                            coarsest_idx,
                        )?;
                        debug_assert_eq!(rotated_img.width(), coarsest.width());
                        debug_assert_eq!(rotated_img.height(), coarsest.height());
                        let mask: Arc<[u8]> = Arc::from(mask);
                        let zncc_plan = MaskedTemplatePlan::from_rotated_parts(
                            rotated_img.view(),
                            mask.clone(),
                            angle,
                        )?;
                        let ssd_plan = MaskedSsdTemplatePlan::from_rotated_parts(
                            rotated_img.view(),
                            mask,
                            angle,
                        )?;
                        let rotated = RotatedTemplate {
                            angle_deg: angle,
                            zncc: zncc_plan,
                            ssd: ssd_plan,
                        };
                        let _ = bank.slots[idx].set(rotated);
                    }
                }
            }
        }

        Ok(Self {
            levels,
            banks,
            unmasked_zncc,
            unmasked_ssd,
            cfg,
        })
    }

    /// Returns the number of pyramid levels.
    pub fn num_levels(&self) -> usize {
        self.levels.len()
    }

    /// Returns the width and height for a pyramid level.
    pub fn level_size(&self, level: usize) -> Option<(usize, usize)> {
        self.levels
            .get(level)
            .map(|img| (img.width(), img.height()))
    }

    /// Returns the angle grid for a pyramid level.
    pub fn angle_grid(&self, level: usize) -> Option<&AngleGrid> {
        self.banks.get(level).map(|bank| &bank.grid)
    }

    /// Returns an unmasked ZNCC template plan for a given level.
    pub fn unmasked_zncc_plan(&self, level: usize) -> CorrMatchResult<&TemplatePlan> {
        self.unmasked_zncc
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.unmasked_zncc.len(),
                context: "level",
            })
    }

    /// Returns an unmasked SSD template plan for a given level.
    pub fn unmasked_ssd_plan(&self, level: usize) -> CorrMatchResult<&SsdTemplatePlan> {
        self.unmasked_ssd
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.unmasked_ssd.len(),
                context: "level",
            })
    }

    pub(crate) fn rotated(
        &self,
        level: usize,
        angle_idx: usize,
    ) -> CorrMatchResult<&RotatedTemplate> {
        let bank = self
            .banks
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.banks.len(),
                context: "level",
            })?;
        let slot = bank
            .slots
            .get(angle_idx)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: angle_idx,
                len: bank.slots.len(),
                context: "angle_idx",
            })?;
        let level_img = self
            .levels
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.levels.len(),
                context: "level",
            })?;
        let angle = bank.grid.angle_at(angle_idx);
        if let Some(rotated) = slot.get() {
            debug_assert!((rotated.angle_deg - angle).abs() < 1e-6);
            debug_assert_eq!(rotated.zncc.width(), level_img.width());
            debug_assert_eq!(rotated.zncc.height(), level_img.height());
            return Ok(rotated);
        }
        let base = self
            .levels
            .first()
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: 0,
                len: self.levels.len(),
                context: "level",
            })?;
        let (rotated_img, mask) =
            rotate_downsample_to_level(base.view(), angle, self.cfg.fill_value, level)?;
        debug_assert_eq!(rotated_img.width(), level_img.width());
        debug_assert_eq!(rotated_img.height(), level_img.height());
        let mask: Arc<[u8]> = Arc::from(mask);
        let zncc_plan =
            MaskedTemplatePlan::from_rotated_parts(rotated_img.view(), mask.clone(), angle)?;
        let ssd_plan = MaskedSsdTemplatePlan::from_rotated_parts(rotated_img.view(), mask, angle)?;
        let rotated = RotatedTemplate {
            angle_deg: angle,
            zncc: zncc_plan,
            ssd: ssd_plan,
        };
        let _ = slot.set(rotated);
        Ok(slot.get().expect("rotated template should be initialized"))
    }
}

/// Compiled template assets without rotation support.
pub struct CompiledTemplateNoRot {
    levels: Vec<OwnedImage>,
    unmasked_zncc: Vec<TemplatePlan>,
    unmasked_ssd: Vec<SsdTemplatePlan>,
}

impl CompiledTemplateNoRot {
    /// Compiles template assets without rotation support.
    pub fn compile(tpl: &Template, cfg: CompileConfigNoRot) -> CorrMatchResult<Self> {
        let _span = trace_span!(
            "compile_template",
            rotation = false,
            max_levels = cfg.max_levels
        )
        .entered();

        let pyramid = ImagePyramid::build_u8(tpl.view(), cfg.max_levels)?;
        let mut levels = pyramid.into_levels();
        trim_degenerate_levels(&mut levels, 1)?;

        let mut unmasked_zncc = Vec::with_capacity(levels.len());
        let mut unmasked_ssd = Vec::with_capacity(levels.len());
        for level in levels.iter() {
            unmasked_zncc.push(TemplatePlan::from_view(level.view())?);
            unmasked_ssd.push(SsdTemplatePlan::from_view(level.view())?);
        }

        Ok(Self {
            levels,
            unmasked_zncc,
            unmasked_ssd,
        })
    }

    /// Returns the number of pyramid levels.
    pub fn num_levels(&self) -> usize {
        self.levels.len()
    }

    /// Returns the width and height for a pyramid level.
    pub fn level_size(&self, level: usize) -> Option<(usize, usize)> {
        self.levels
            .get(level)
            .map(|img| (img.width(), img.height()))
    }

    /// Returns an unmasked ZNCC template plan for a given level.
    pub fn unmasked_zncc_plan(&self, level: usize) -> CorrMatchResult<&TemplatePlan> {
        self.unmasked_zncc
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.unmasked_zncc.len(),
                context: "level",
            })
    }

    /// Returns an unmasked SSD template plan for a given level.
    pub fn unmasked_ssd_plan(&self, level: usize) -> CorrMatchResult<&SsdTemplatePlan> {
        self.unmasked_ssd
            .get(level)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: level,
                len: self.unmasked_ssd.len(),
                context: "level",
            })
    }
}

/// Compiled template assets for rotated or unrotated matching.
///
/// Use `Template::compile`/`CompiledTemplate::compile_rotated` when rotation
/// search is required, or `CompiledTemplate::compile_unrotated` for the fast
/// translation-only path.
pub enum CompiledTemplate {
    /// Rotation-enabled assets.
    Rotated(CompiledTemplateRot),
    /// Rotation-disabled assets.
    Unrotated(CompiledTemplateNoRot),
}

impl CompiledTemplate {
    /// Compiles rotation-enabled template assets.
    pub fn compile_rotated(tpl: &Template, cfg: CompileConfig) -> CorrMatchResult<Self> {
        Ok(Self::Rotated(CompiledTemplateRot::compile(tpl, cfg)?))
    }

    /// Compiles rotation-disabled template assets.
    pub fn compile_unrotated(tpl: &Template, cfg: CompileConfigNoRot) -> CorrMatchResult<Self> {
        Ok(Self::Unrotated(CompiledTemplateNoRot::compile(tpl, cfg)?))
    }

    /// Compiles rotation-enabled template assets (backwards-compatible default).
    pub fn compile(tpl: &Template, cfg: CompileConfig) -> CorrMatchResult<Self> {
        Self::compile_rotated(tpl, cfg)
    }

    /// Returns the number of pyramid levels.
    pub fn num_levels(&self) -> usize {
        match self {
            Self::Rotated(rot) => rot.num_levels(),
            Self::Unrotated(unrot) => unrot.num_levels(),
        }
    }

    /// Returns the width and height for a pyramid level.
    pub fn level_size(&self, level: usize) -> Option<(usize, usize)> {
        match self {
            Self::Rotated(rot) => rot.level_size(level),
            Self::Unrotated(unrot) => unrot.level_size(level),
        }
    }

    /// Returns the angle grid for a pyramid level.
    pub fn angle_grid(&self, level: usize) -> Option<&AngleGrid> {
        match self {
            Self::Rotated(rot) => rot.angle_grid(level),
            Self::Unrotated(_) => None,
        }
    }

    /// Returns an unmasked ZNCC template plan for a given level.
    pub fn unmasked_zncc_plan(&self, level: usize) -> CorrMatchResult<&TemplatePlan> {
        match self {
            Self::Rotated(rot) => rot.unmasked_zncc_plan(level),
            Self::Unrotated(unrot) => unrot.unmasked_zncc_plan(level),
        }
    }

    /// Returns an unmasked SSD template plan for a given level.
    pub fn unmasked_ssd_plan(&self, level: usize) -> CorrMatchResult<&SsdTemplatePlan> {
        match self {
            Self::Rotated(rot) => rot.unmasked_ssd_plan(level),
            Self::Unrotated(unrot) => unrot.unmasked_ssd_plan(level),
        }
    }

    /// Returns the rotated template entry for a given level and angle.
    pub(crate) fn rotated(
        &self,
        level: usize,
        angle_idx: usize,
    ) -> CorrMatchResult<&RotatedTemplate> {
        match self {
            Self::Rotated(rot) => rot.rotated(level, angle_idx),
            Self::Unrotated(_) => Err(CorrMatchError::RotationUnavailable {
                reason: "compiled without rotation support",
            }),
        }
    }

    /// Returns a masked ZNCC template plan for a given level and angle.
    pub fn rotated_zncc_plan(
        &self,
        level: usize,
        angle_idx: usize,
    ) -> CorrMatchResult<&MaskedTemplatePlan> {
        Ok(self.rotated(level, angle_idx)?.zncc_plan())
    }

    /// Returns a masked SSD template plan for a given level and angle.
    pub fn rotated_ssd_plan(
        &self,
        level: usize,
        angle_idx: usize,
    ) -> CorrMatchResult<&MaskedSsdTemplatePlan> {
        Ok(self.rotated(level, angle_idx)?.ssd_plan())
    }
}