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
//! Template plan precomputation for ZNCC and SSD metrics.

use crate::image::ImageView;
use crate::util::{CorrMatchError, CorrMatchResult};
use std::sync::Arc;

/// Coordinate of a valid (unmasked) template pixel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ValidCoord {
    /// X coordinate within the template (column).
    pub x: u16,
    /// Y coordinate within the template (row).
    pub y: u16,
}

/// Precomputed statistics and zero-mean buffer for unmasked ZNCC matching.
pub struct TemplatePlan {
    width: usize,
    height: usize,
    mean: f32,
    inv_std: f32,
    var_t: f32,
    zero_mean: Vec<f32>,
}

impl TemplatePlan {
    /// Builds a plan from a template view.
    pub fn from_view(tpl: ImageView<'_, u8>) -> CorrMatchResult<Self> {
        let width = tpl.width();
        let height = tpl.height();
        let count = width
            .checked_mul(height)
            .ok_or(CorrMatchError::InvalidDimensions { width, height })?;

        let mut sum = 0.0f64;
        let mut sum_sq = 0.0f64;
        for y in 0..height {
            let row = tpl.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(tpl.stride())
                    .and_then(|v| v.checked_add(tpl.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: tpl.as_slice().len(),
                }
            })?;
            for &value in row {
                let v = value as f64;
                sum += v;
                sum_sq += v * v;
            }
        }

        let count_f = count as f64;
        let mean_f64 = sum / count_f;
        let variance = sum_sq / count_f - mean_f64 * mean_f64;
        if variance <= 1e-8 {
            return Err(CorrMatchError::DegenerateTemplate {
                reason: "zero variance",
            });
        }

        let mean = mean_f64 as f32;
        let inv_std = (1.0 / variance.sqrt()) as f32;
        let var_t = (variance * count_f) as f32;
        let mut zero_mean = Vec::with_capacity(count);
        for y in 0..height {
            let row = tpl.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(tpl.stride())
                    .and_then(|v| v.checked_add(tpl.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: tpl.as_slice().len(),
                }
            })?;
            for &value in row {
                zero_mean.push(value as f32 - mean);
            }
        }

        Ok(Self {
            width,
            height,
            mean,
            inv_std,
            var_t,
            zero_mean,
        })
    }

    /// Returns the template width in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the template height in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the mean intensity of the template.
    pub fn mean(&self) -> f32 {
        self.mean
    }

    /// Returns the inverse standard deviation of the template.
    pub fn inv_std(&self) -> f32 {
        self.inv_std
    }

    /// Returns the template variance term used by ZNCC.
    pub fn var_t(&self) -> f32 {
        self.var_t
    }

    /// Returns the zero-mean template buffer in row-major order.
    pub fn t_prime(&self) -> &[f32] {
        &self.zero_mean
    }

    /// Returns the zero-mean template buffer in row-major order.
    pub fn zero_mean(&self) -> &[f32] {
        &self.zero_mean
    }
}

/// Precomputed template buffer for SSD matching.
pub struct SsdTemplatePlan {
    width: usize,
    height: usize,
    data: Vec<f32>,
}

impl SsdTemplatePlan {
    /// Builds an SSD plan from a template view.
    pub fn from_view(tpl: ImageView<'_, u8>) -> CorrMatchResult<Self> {
        let width = tpl.width();
        let height = tpl.height();
        let count = width
            .checked_mul(height)
            .ok_or(CorrMatchError::InvalidDimensions { width, height })?;

        let mut data = Vec::with_capacity(count);
        for y in 0..height {
            let row = tpl.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(tpl.stride())
                    .and_then(|v| v.checked_add(tpl.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: tpl.as_slice().len(),
                }
            })?;
            for &value in row {
                data.push(value as f32);
            }
        }

        Ok(Self {
            width,
            height,
            data,
        })
    }

    /// Returns the template width in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the template height in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the template buffer in row-major order.
    pub fn data(&self) -> &[f32] {
        &self.data
    }
}

/// Precomputed masked statistics for ZNCC-style matching on rotated templates.
pub struct MaskedTemplatePlan {
    width: usize,
    height: usize,
    sum_w: f32,
    var_t: f32,
    mask: Arc<[u8]>,
    angle_deg: f32,
    /// Precomputed coordinates where mask is non-zero (for branch-free iteration).
    valid_coords: Vec<ValidCoord>,
    /// Precomputed t_prime values at valid coordinates only.
    valid_t_prime: Vec<f32>,
}

impl MaskedTemplatePlan {
    /// Builds a masked plan from a rotated template view and a binary mask.
    pub fn from_rotated_u8(
        rot: ImageView<'_, u8>,
        mask: Vec<u8>,
        angle_deg: f32,
    ) -> CorrMatchResult<Self> {
        Self::from_rotated_parts(rot, Arc::from(mask), angle_deg)
    }

    pub(crate) fn from_rotated_parts(
        rot: ImageView<'_, u8>,
        mask: Arc<[u8]>,
        angle_deg: f32,
    ) -> CorrMatchResult<Self> {
        let width = rot.width();
        let height = rot.height();
        if width > u16::MAX as usize || height > u16::MAX as usize {
            return Err(CorrMatchError::InvalidDimensions { width, height });
        }
        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 });
        }

        let mut sum_w_count = 0usize;
        let mut sum_wt = 0.0f32;
        for y in 0..height {
            let row = rot.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(rot.stride())
                    .and_then(|v| v.checked_add(rot.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: rot.as_slice().len(),
                }
            })?;
            for (x, &value) in row.iter().enumerate() {
                let idx = y * width + x;
                if mask[idx] != 0 {
                    sum_w_count += 1;
                    sum_wt += value as f32;
                }
            }
        }

        if sum_w_count == 0 {
            return Err(CorrMatchError::DegenerateTemplate {
                reason: "mask has no valid pixels",
            });
        }

        let sum_w = sum_w_count as f32;
        let mu_t = sum_wt / sum_w;
        let mut var_t = 0.0f32;
        let mut valid_coords = Vec::with_capacity(sum_w_count);
        let mut valid_t_prime = Vec::with_capacity(sum_w_count);
        for y in 0..height {
            let row = rot.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(rot.stride())
                    .and_then(|v| v.checked_add(rot.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: rot.as_slice().len(),
                }
            })?;
            for (x, &value) in row.iter().enumerate() {
                let idx = y * width + x;
                if mask[idx] == 0 {
                    continue;
                }
                let value = value as f32 - mu_t;
                valid_coords.push(ValidCoord {
                    x: x as u16,
                    y: y as u16,
                });
                valid_t_prime.push(value);
                var_t += value * value;
            }
        }

        if var_t <= 1e-8 {
            return Err(CorrMatchError::DegenerateTemplate {
                reason: "template variance too small",
            });
        }

        Ok(Self {
            width,
            height,
            sum_w,
            var_t,
            mask,
            angle_deg,
            valid_coords,
            valid_t_prime,
        })
    }

    /// Returns the template width in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the template height in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the sum of mask weights (count of valid pixels).
    pub fn sum_w(&self) -> f32 {
        self.sum_w
    }

    /// Returns the template variance term used by ZNCC.
    pub fn var_t(&self) -> f32 {
        self.var_t
    }

    /// Returns the binary mask buffer (0 or 1 per pixel).
    pub fn mask(&self) -> &[u8] {
        self.mask.as_ref()
    }

    /// Returns the rotation angle in degrees.
    pub fn angle_deg(&self) -> f32 {
        self.angle_deg
    }

    /// Returns precomputed coordinates where the mask is non-zero.
    ///
    /// Use with `valid_t_prime()` for branch-free iteration over valid pixels.
    pub fn valid_coords(&self) -> &[ValidCoord] {
        &self.valid_coords
    }

    /// Returns precomputed t_prime values at valid coordinates.
    ///
    /// This slice has the same length as `valid_coords()`.
    pub fn valid_t_prime(&self) -> &[f32] {
        &self.valid_t_prime
    }
}

/// Precomputed masked buffer for SSD matching on rotated templates.
pub struct MaskedSsdTemplatePlan {
    width: usize,
    height: usize,
    mask: Arc<[u8]>,
    angle_deg: f32,
    /// Precomputed coordinates where mask is non-zero (for branch-free iteration).
    valid_coords: Vec<ValidCoord>,
    /// Precomputed template data values at valid coordinates only.
    valid_data: Vec<f32>,
}

impl MaskedSsdTemplatePlan {
    /// Builds a masked SSD plan from a rotated template view and a binary mask.
    pub fn from_rotated_u8(
        rot: ImageView<'_, u8>,
        mask: Vec<u8>,
        angle_deg: f32,
    ) -> CorrMatchResult<Self> {
        Self::from_rotated_parts(rot, Arc::from(mask), angle_deg)
    }

    pub(crate) fn from_rotated_parts(
        rot: ImageView<'_, u8>,
        mask: Arc<[u8]>,
        angle_deg: f32,
    ) -> CorrMatchResult<Self> {
        let width = rot.width();
        let height = rot.height();
        if width > u16::MAX as usize || height > u16::MAX as usize {
            return Err(CorrMatchError::InvalidDimensions { width, height });
        }
        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 });
        }

        let mut sum_w = 0usize;
        for y in 0..height {
            let row = rot.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(rot.stride())
                    .and_then(|v| v.checked_add(rot.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: rot.as_slice().len(),
                }
            })?;
            for (x, &_value) in row.iter().enumerate() {
                let idx = y * width + x;
                if mask[idx] != 0 {
                    sum_w += 1;
                }
            }
        }

        if sum_w == 0 {
            return Err(CorrMatchError::DegenerateTemplate {
                reason: "mask has no valid pixels",
            });
        }

        // Precompute valid coordinates for branch-free iteration in hot loops.
        let mut valid_coords = Vec::with_capacity(sum_w);
        let mut valid_data = Vec::with_capacity(sum_w);
        for y in 0..height {
            let row = rot.row(y).ok_or_else(|| {
                let needed = (y + 1)
                    .checked_mul(rot.stride())
                    .and_then(|v| v.checked_add(rot.width()))
                    .unwrap_or(usize::MAX);
                CorrMatchError::BufferTooSmall {
                    needed,
                    got: rot.as_slice().len(),
                }
            })?;
            for (x, &value) in row.iter().enumerate() {
                let idx = y * width + x;
                if mask[idx] == 0 {
                    continue;
                }
                valid_coords.push(ValidCoord {
                    x: x as u16,
                    y: y as u16,
                });
                valid_data.push(value as f32);
            }
        }

        Ok(Self {
            width,
            height,
            mask,
            angle_deg,
            valid_coords,
            valid_data,
        })
    }

    /// Returns the template width in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the template height in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the binary mask buffer (0 or 1 per pixel).
    pub fn mask(&self) -> &[u8] {
        self.mask.as_ref()
    }

    /// Returns the rotation angle in degrees.
    pub fn angle_deg(&self) -> f32 {
        self.angle_deg
    }

    /// Returns precomputed coordinates where the mask is non-zero.
    ///
    /// Use with `valid_data()` for branch-free iteration over valid pixels.
    pub fn valid_coords(&self) -> &[ValidCoord] {
        &self.valid_coords
    }

    /// Returns precomputed template data values at valid coordinates.
    ///
    /// This slice has the same length as `valid_coords()`.
    pub fn valid_data(&self) -> &[f32] {
        &self.valid_data
    }
}