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
//! Search strategies for locating template matches.
//!
//! The scan module provides baseline scalar ZNCC evaluation helpers.

mod coarse;
mod refine;
pub(crate) mod scan;

use crate::bank::CompiledTemplate;
use crate::image::integral::IntegralImages;
use crate::image::pyramid::ImagePyramid;
use crate::search::coarse::{
    coarse_search_level, coarse_search_level_unmasked, coarse_search_level_unmasked_zncc_integral,
};
#[cfg(feature = "rayon")]
use crate::search::coarse::{coarse_search_level_par, coarse_search_level_unmasked_par};
use crate::search::refine::{
    refine_final_match, refine_final_match_unmasked, refine_to_finer_level_batch,
    refine_to_finer_level_unmasked, refine_to_finer_level_unmasked_zncc_integral, Candidate,
};
#[cfg(feature = "rayon")]
use crate::search::refine::{refine_to_finer_level_par, refine_to_finer_level_unmasked_par};
use crate::util::{CorrMatchError, CorrMatchResult};
use crate::ImageView;

/// Matching metric selector.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Metric {
    /// Zero-mean normalized cross-correlation (higher is better, roughly [-1, 1]).
    Zncc,
    /// Sum of squared differences (reported as negative SSE, higher is better).
    Ssd,
}

/// Controls whether rotation is searched.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RotationMode {
    /// Skip rotation and use the unmasked fast path.
    Disabled,
    /// Enable rotation search using masked kernels.
    Enabled,
}

/// Configuration for the coarse-to-fine matcher pipeline.
#[derive(Clone, Debug)]
pub struct MatchConfig {
    /// Matching metric to use.
    pub metric: Metric,
    /// Whether rotation search is enabled.
    pub rotation: RotationMode,
    /// Enables parallel search when the `rayon` feature is available.
    ///
    /// When the feature is disabled, this flag is ignored and execution stays sequential.
    pub parallel: bool,
    /// Maximum pyramid levels to build for the image.
    pub max_image_levels: usize,
    /// Beam width kept per level after merge and NMS.
    pub beam_width: usize,
    /// Top-M peaks per angle at the coarsest level.
    ///
    /// Ignored when rotation is disabled.
    pub per_angle_topk: usize,
    /// Spatial NMS radius in pixels for the current level.
    pub nms_radius: usize,
    /// Refinement ROI radius in pixels for the current level.
    pub roi_radius: usize,
    /// Angle neighborhood half-range in multiples of the grid step.
    ///
    /// Ignored when rotation is disabled.
    pub angle_half_range_steps: usize,
    /// Minimum variance for image patches.
    ///
    /// Ignored for SSD.
    pub min_var_i: f32,
    /// Minimum score threshold (discard below this value).
    pub min_score: f32,
}

impl Default for MatchConfig {
    fn default() -> Self {
        Self {
            metric: Metric::Zncc,
            rotation: RotationMode::Disabled,
            parallel: false,
            max_image_levels: 6,
            beam_width: 8,
            per_angle_topk: 3,
            nms_radius: 6,
            roi_radius: 8,
            angle_half_range_steps: 1,
            min_var_i: 1e-8,
            min_score: f32::NEG_INFINITY,
        }
    }
}

impl MatchConfig {
    /// Validates the configuration, returning an error if any parameter is invalid.
    pub fn validate(&self) -> CorrMatchResult<()> {
        if self.beam_width == 0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "beam_width must be at least 1",
            });
        }
        if self.per_angle_topk == 0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "per_angle_topk must be at least 1",
            });
        }
        if self.max_image_levels == 0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "max_image_levels must be at least 1",
            });
        }
        if !self.min_var_i.is_finite() || self.min_var_i < 0.0 {
            return Err(CorrMatchError::InvalidConfig {
                reason: "min_var_i must be a non-negative finite value",
            });
        }
        if !self.min_score.is_finite() && self.min_score != f32::NEG_INFINITY {
            return Err(CorrMatchError::InvalidConfig {
                reason: "min_score must be finite or NEG_INFINITY",
            });
        }
        #[cfg(not(feature = "rayon"))]
        if self.parallel {
            return Err(CorrMatchError::ParallelUnavailable);
        }
        Ok(())
    }

    pub(crate) fn use_parallel(&self) -> bool {
        self.parallel && cfg!(feature = "rayon")
    }
}

/// Match result for the finest pyramid level.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Match {
    /// Refined top-left x coordinate of the template placement (level 0).
    pub x: f32,
    /// Refined top-left y coordinate of the template placement (level 0).
    pub y: f32,
    /// Estimated rotation angle in degrees.
    pub angle_deg: f32,
    /// Score for the chosen metric (ZNCC in [-1, 1], SSD as negative SSE).
    pub score: f32,
}

/// Matcher that runs coarse-to-fine search using a compiled template.
pub struct Matcher {
    compiled: CompiledTemplate,
    cfg: MatchConfig,
}

impl Matcher {
    /// Creates a matcher with default configuration.
    pub fn new(compiled: CompiledTemplate) -> Self {
        Self {
            compiled,
            cfg: MatchConfig::default(),
        }
    }

    /// Replaces the matcher configuration.
    ///
    /// Use `try_with_config` for validation of the configuration.
    pub fn with_config(mut self, cfg: MatchConfig) -> Self {
        self.cfg = cfg;
        self
    }

    /// Replaces the matcher configuration with validation.
    ///
    /// Returns an error if the configuration is invalid.
    pub fn try_with_config(mut self, cfg: MatchConfig) -> CorrMatchResult<Self> {
        cfg.validate()?;
        self.cfg = cfg;
        Ok(self)
    }

    /// Matches a template against an image and returns the best candidate.
    ///
    /// When rotation is disabled, angle-related settings are ignored.
    pub fn match_image(&self, image: ImageView<'_, u8>) -> CorrMatchResult<Match> {
        let _span = trace_span!(
            "match_image",
            width = image.width(),
            height = image.height()
        )
        .entered();

        self.cfg.validate()?;
        let seeds = self.match_candidates(image)?;
        let best = seeds[0];
        let refined = match self.cfg.rotation {
            RotationMode::Enabled => refine_final_match(image, &self.compiled, 0, best, &self.cfg),
            RotationMode::Disabled => {
                refine_final_match_unmasked(image, &self.compiled, 0, best, &self.cfg)
            }
        };
        Ok(refined.unwrap_or(Match {
            x: best.x as f32,
            y: best.y as f32,
            angle_deg: best.angle_deg,
            score: best.score,
        }))
    }

    /// Matches a template against an image and returns up to `k` best candidates.
    ///
    /// Results are returned in descending score order and include the same
    /// refinement steps as `match_image`.
    pub fn match_image_topk(
        &self,
        image: ImageView<'_, u8>,
        k: usize,
    ) -> CorrMatchResult<Vec<Match>> {
        self.cfg.validate()?;
        if k == 0 {
            return Ok(Vec::new());
        }

        // For top-k queries, we may need to keep more coarse candidates than the
        // default config provides, otherwise the early TopK buffer can be
        // dominated by a single broad peak and miss other true instances.
        let search_cfg = self.cfg_for_topk(k);
        let seeds = self.match_candidates_with_cfg(image, &search_cfg)?;

        let mut out = Vec::with_capacity(seeds.len());
        for cand in seeds {
            let refined = match search_cfg.rotation {
                RotationMode::Enabled => {
                    refine_final_match(image, &self.compiled, 0, cand, &search_cfg)
                }
                RotationMode::Disabled => {
                    refine_final_match_unmasked(image, &self.compiled, 0, cand, &search_cfg)
                }
            };
            out.push(refined.unwrap_or(Match {
                x: cand.x as f32,
                y: cand.y as f32,
                angle_deg: cand.angle_deg,
                score: cand.score,
            }));
        }

        out.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        if out.len() > k {
            out.truncate(k);
        }
        Ok(out)
    }

    fn match_candidates(&self, image: ImageView<'_, u8>) -> CorrMatchResult<Vec<Candidate>> {
        self.match_candidates_with_cfg(image, &self.cfg)
    }

    fn cfg_for_topk(&self, k: usize) -> MatchConfig {
        if k <= 1 {
            return self.cfg.clone();
        }

        let mut cfg = self.cfg.clone();
        cfg.beam_width = cfg.beam_width.max(k);

        // Oversample top-k per angle so that after NMS we still retain multiple
        // distinct peaks. Rotation-disabled uses a single angle, so we can be
        // more aggressive without blowing up work across angles.
        let oversample = match cfg.rotation {
            RotationMode::Disabled => 8,
            RotationMode::Enabled => 4,
        };
        cfg.per_angle_topk = cfg
            .per_angle_topk
            .max(cfg.beam_width.saturating_mul(oversample));
        cfg
    }

    fn match_candidates_with_cfg(
        &self,
        image: ImageView<'_, u8>,
        cfg: &MatchConfig,
    ) -> CorrMatchResult<Vec<Candidate>> {
        if matches!(self.compiled, CompiledTemplate::Unrotated(_))
            && cfg.rotation == RotationMode::Enabled
        {
            return Err(CorrMatchError::RotationUnavailable {
                reason: "rotation enabled but template compiled without angle banks",
            });
        }

        let use_parallel = cfg.use_parallel();
        let pyramid = ImagePyramid::build_u8(image, cfg.max_image_levels)?;
        let num_levels = pyramid.levels().len().min(self.compiled.num_levels());

        let _span = trace_span!(
            "coarse_to_fine",
            levels = num_levels,
            parallel = use_parallel
        )
        .entered();
        if num_levels == 0 {
            return Err(CorrMatchError::InvalidDimensions {
                width: image.width(),
                height: image.height(),
            });
        }

        let use_integral =
            !use_parallel && cfg.rotation == RotationMode::Disabled && cfg.metric == Metric::Zncc;
        let integrals = if use_integral {
            let mut out = Vec::with_capacity(num_levels);
            for level in 0..num_levels {
                let view = pyramid
                    .level(level)
                    .ok_or(CorrMatchError::IndexOutOfBounds {
                        index: level,
                        len: pyramid.levels().len(),
                        context: "image level",
                    })?;
                out.push(IntegralImages::from_u8(view)?);
            }
            Some(out)
        } else {
            None
        };

        let coarsest = num_levels - 1;
        let coarse_view = pyramid
            .level(coarsest)
            .ok_or(CorrMatchError::IndexOutOfBounds {
                index: coarsest,
                len: pyramid.levels().len(),
                context: "image level",
            })?;
        let mut seeds = match cfg.rotation {
            RotationMode::Enabled => {
                if use_parallel {
                    #[cfg(feature = "rayon")]
                    {
                        coarse_search_level_par(coarse_view, &self.compiled, coarsest, cfg)?
                    }
                    #[cfg(not(feature = "rayon"))]
                    {
                        coarse_search_level(coarse_view, &self.compiled, coarsest, cfg)?
                    }
                } else {
                    coarse_search_level(coarse_view, &self.compiled, coarsest, cfg)?
                }
            }
            RotationMode::Disabled => {
                if use_parallel {
                    #[cfg(feature = "rayon")]
                    {
                        coarse_search_level_unmasked_par(
                            coarse_view,
                            &self.compiled,
                            coarsest,
                            cfg,
                        )?
                    }
                    #[cfg(not(feature = "rayon"))]
                    {
                        coarse_search_level_unmasked(coarse_view, &self.compiled, coarsest, cfg)?
                    }
                } else if use_integral {
                    let integrals = integrals
                        .as_ref()
                        .expect("integrals built for unmasked ZNCC");
                    coarse_search_level_unmasked_zncc_integral(
                        coarse_view,
                        &self.compiled,
                        coarsest,
                        cfg,
                        &integrals[coarsest],
                    )?
                } else {
                    coarse_search_level_unmasked(coarse_view, &self.compiled, coarsest, cfg)?
                }
            }
        };
        if seeds.is_empty() {
            return Err(CorrMatchError::NoCandidates {
                reason: "no coarse candidates",
            });
        }

        for level in (0..coarsest).rev() {
            let level_view = pyramid
                .level(level)
                .ok_or(CorrMatchError::IndexOutOfBounds {
                    index: level,
                    len: pyramid.levels().len(),
                    context: "image level",
                })?;
            seeds = match cfg.rotation {
                RotationMode::Enabled => {
                    if use_parallel {
                        #[cfg(feature = "rayon")]
                        {
                            refine_to_finer_level_par(
                                level_view,
                                &self.compiled,
                                level,
                                &seeds,
                                cfg,
                            )?
                        }
                        #[cfg(not(feature = "rayon"))]
                        {
                            // Use batch processing for cache locality in sequential mode
                            refine_to_finer_level_batch(
                                level_view,
                                &self.compiled,
                                level,
                                &seeds,
                                cfg,
                            )?
                        }
                    } else {
                        // Use batch processing for cache locality
                        refine_to_finer_level_batch(level_view, &self.compiled, level, &seeds, cfg)?
                    }
                }
                RotationMode::Disabled => {
                    if use_parallel {
                        #[cfg(feature = "rayon")]
                        {
                            refine_to_finer_level_unmasked_par(
                                level_view,
                                &self.compiled,
                                level,
                                &seeds,
                                cfg,
                            )?
                        }
                        #[cfg(not(feature = "rayon"))]
                        {
                            refine_to_finer_level_unmasked(
                                level_view,
                                &self.compiled,
                                level,
                                &seeds,
                                cfg,
                            )?
                        }
                    } else if use_integral {
                        let integrals = integrals
                            .as_ref()
                            .expect("integrals built for unmasked ZNCC");
                        refine_to_finer_level_unmasked_zncc_integral(
                            level_view,
                            &self.compiled,
                            level,
                            &seeds,
                            cfg,
                            &integrals[level],
                        )?
                    } else {
                        refine_to_finer_level_unmasked(
                            level_view,
                            &self.compiled,
                            level,
                            &seeds,
                            cfg,
                        )?
                    }
                }
            };
            if seeds.is_empty() {
                return Err(CorrMatchError::NoCandidates {
                    reason: "no candidates after refinement",
                });
            }
        }

        Ok(seeds)
    }
}