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
//! SIMD-accelerated kernels using the `wide` crate.
//!
//! This module provides SIMD-optimized kernel implementations for unmasked
//! ZNCC and SSD metrics. The inner template pixel loop is vectorized to
//! process 8 pixels at a time using `f32x8`.

use crate::candidate::topk::{Peak, TopK};
use crate::image::integral::IntegralImages;
use crate::kernel::{Kernel, ScanParams, ScanRoi};
use crate::template::{SsdTemplatePlan, TemplatePlan};
use crate::util::{CorrMatchError, CorrMatchResult};
use crate::ImageView;
use wide::f32x8;

const LANES: usize = 8;

/// Load 8 u8 values and convert to f32x8.
#[inline]
fn load_u8x8_as_f32x8(slice: &[u8]) -> f32x8 {
    f32x8::from([
        slice[0] as f32,
        slice[1] as f32,
        slice[2] as f32,
        slice[3] as f32,
        slice[4] as f32,
        slice[5] as f32,
        slice[6] as f32,
        slice[7] as f32,
    ])
}

/// Load 8 f32 values into f32x8.
#[inline]
fn load_f32x8(slice: &[f32]) -> f32x8 {
    f32x8::from([
        slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
    ])
}

/// Horizontal sum of f32x8.
#[inline]
fn hsum(v: f32x8) -> f32 {
    let arr = v.to_array();
    arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5] + arr[6] + arr[7]
}

/// SIMD-accelerated unmasked ZNCC kernel.
pub struct ZnccUnmaskedSimd;

impl ZnccUnmaskedSimd {
    /// Computes ZNCC score at a single position using SIMD.
    fn score_at_simd(
        image: ImageView<'_, u8>,
        tpl: &TemplatePlan,
        x: usize,
        y: usize,
        min_var_i: f32,
    ) -> f32 {
        let tpl_width = tpl.width();
        let tpl_height = tpl.height();
        let t_prime = tpl.t_prime();
        let var_t = tpl.var_t();
        let n = (tpl_width * tpl_height) as f32;

        let mut dot_vec = f32x8::ZERO;
        let mut sum_i_vec = f32x8::ZERO;
        let mut sum_i2_vec = f32x8::ZERO;

        let mut dot_s = 0.0f32;
        let mut sum_i_s = 0.0f32;
        let mut sum_i2_s = 0.0f32;

        let simd_end = tpl_width / LANES * LANES;

        for ty in 0..tpl_height {
            let img_row = match image.row(y + ty) {
                Some(row) => row,
                None => return f32::NEG_INFINITY,
            };
            let base = ty * tpl_width;

            // SIMD portion: process 8 pixels at a time
            let mut tx = 0;
            while tx < simd_end {
                let img_vals = load_u8x8_as_f32x8(&img_row[x + tx..]);
                let tpl_vals = load_f32x8(&t_prime[base + tx..]);

                dot_vec += tpl_vals * img_vals;
                sum_i_vec += img_vals;
                sum_i2_vec += img_vals * img_vals;

                tx += LANES;
            }

            // Scalar remainder
            while tx < tpl_width {
                let value = img_row[x + tx] as f32;
                let idx = base + tx;
                dot_s += t_prime[idx] * value;
                sum_i_s += value;
                sum_i2_s += value * value;
                tx += 1;
            }
        }

        // Horizontal reduction + scalar remainder
        let dot = hsum(dot_vec) + dot_s;
        let sum_i = hsum(sum_i_vec) + sum_i_s;
        let sum_i2 = hsum(sum_i2_vec) + sum_i2_s;

        let var_i = sum_i2 - (sum_i * sum_i) / n;
        if var_i <= min_var_i {
            return f32::NEG_INFINITY;
        }

        let denom = (var_t * var_i).sqrt();
        let score = dot / denom;
        if score.is_finite() {
            score
        } else {
            f32::NEG_INFINITY
        }
    }

    #[inline]
    fn dot_at_simd(
        image: ImageView<'_, u8>,
        t_prime: &[f32],
        tpl_width: usize,
        tpl_height: usize,
        x: usize,
        y: usize,
    ) -> f32 {
        let mut dot_vec = f32x8::ZERO;
        let mut dot_s = 0.0f32;
        let simd_end = tpl_width / LANES * LANES;

        for ty in 0..tpl_height {
            let img_row = image.row(y + ty).expect("row within bounds for scan");
            let base = ty * tpl_width;

            let mut tx = 0;
            while tx < simd_end {
                let img_vals = load_u8x8_as_f32x8(&img_row[x + tx..]);
                let tpl_vals = load_f32x8(&t_prime[base + tx..]);
                dot_vec += tpl_vals * img_vals;
                tx += LANES;
            }

            while tx < tpl_width {
                let value = img_row[x + tx] as f32;
                let idx = base + tx;
                dot_s += t_prime[idx] * value;
                tx += 1;
            }
        }

        hsum(dot_vec) + dot_s
    }

    fn scan_range(
        image: ImageView<'_, u8>,
        tpl: &TemplatePlan,
        angle_idx: usize,
        roi: ScanRoi,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        if params.topk == 0 {
            return Ok(Vec::new());
        }

        let img_width = image.width();
        let img_height = image.height();
        let tpl_width = tpl.width();
        let tpl_height = tpl.height();

        if img_width < tpl_width || img_height < tpl_height {
            return Err(CorrMatchError::RoiOutOfBounds {
                x: 0,
                y: 0,
                width: tpl_width,
                height: tpl_height,
                img_width,
                img_height,
            });
        }

        let max_x = img_width - tpl_width;
        let max_y = img_height - tpl_height;
        let roi = match roi.clamp_inclusive(max_x, max_y) {
            Some(roi) => roi,
            None => return Ok(Vec::new()),
        };

        let var_t = tpl.var_t();
        if var_t <= 1e-8 {
            return Ok(Vec::new());
        }

        let mut topk_buf = TopK::new(params.topk);
        for y in roi.y0..=roi.y1 {
            for x in roi.x0..=roi.x1 {
                let score = Self::score_at_simd(image, tpl, x, y, params.min_var_i);
                if score.is_finite() && score >= params.min_score {
                    topk_buf.push(Peak {
                        x,
                        y,
                        score,
                        angle_idx,
                    });
                }
            }
        }

        Ok(topk_buf.into_sorted_desc())
    }

    fn scan_range_integral(
        image: ImageView<'_, u8>,
        tpl: &TemplatePlan,
        angle_idx: usize,
        roi: ScanRoi,
        params: ScanParams,
        integrals: &IntegralImages,
    ) -> CorrMatchResult<Vec<Peak>> {
        if params.topk == 0 {
            return Ok(Vec::new());
        }

        let img_width = image.width();
        let img_height = image.height();
        let tpl_width = tpl.width();
        let tpl_height = tpl.height();

        if img_width < tpl_width || img_height < tpl_height {
            return Err(CorrMatchError::RoiOutOfBounds {
                x: 0,
                y: 0,
                width: tpl_width,
                height: tpl_height,
                img_width,
                img_height,
            });
        }

        debug_assert_eq!(integrals.width(), img_width);
        debug_assert_eq!(integrals.height(), img_height);

        let max_x = img_width - tpl_width;
        let max_y = img_height - tpl_height;
        let roi = match roi.clamp_inclusive(max_x, max_y) {
            Some(roi) => roi,
            None => return Ok(Vec::new()),
        };

        let var_t = tpl.var_t();
        if var_t <= 1e-8 {
            return Ok(Vec::new());
        }
        let t_prime = tpl.t_prime();
        let n = (tpl_width * tpl_height) as f32;

        let mut topk_buf = TopK::new(params.topk);
        for y in roi.y0..=roi.y1 {
            for x in roi.x0..=roi.x1 {
                let sum_i = integrals.sum_rect(x, y, tpl_width, tpl_height);
                let sum_i2 = integrals.sumsq_rect(x, y, tpl_width, tpl_height);
                let var_i = sum_i2 - (sum_i * sum_i) / n;
                if var_i <= params.min_var_i {
                    continue;
                }

                let dot = Self::dot_at_simd(image, t_prime, tpl_width, tpl_height, x, y);
                let denom = (var_t * var_i).sqrt();
                let score = dot / denom;
                if score.is_finite() && score >= params.min_score {
                    topk_buf.push(Peak {
                        x,
                        y,
                        score,
                        angle_idx,
                    });
                }
            }
        }

        Ok(topk_buf.into_sorted_desc())
    }

    /// Scans the full valid placement range using integral-image variance pruning.
    pub(crate) fn scan_full_integral(
        image: ImageView<'_, u8>,
        tpl: &TemplatePlan,
        angle_idx: usize,
        params: ScanParams,
        integrals: &IntegralImages,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range_integral(
            image,
            tpl,
            angle_idx,
            ScanRoi::new(0, 0, usize::MAX, usize::MAX),
            params,
            integrals,
        )
    }

    /// Scans an ROI using integral-image variance pruning.
    pub(crate) fn scan_roi_integral(
        image: ImageView<'_, u8>,
        tpl: &TemplatePlan,
        angle_idx: usize,
        roi: ScanRoi,
        params: ScanParams,
        integrals: &IntegralImages,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range_integral(image, tpl, angle_idx, roi, params, integrals)
    }
}

impl Kernel for ZnccUnmaskedSimd {
    type Plan = TemplatePlan;

    fn score_at(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        x: usize,
        y: usize,
        min_var_i: f32,
    ) -> f32 {
        let img_width = image.width();
        let img_height = image.height();
        let tpl_width = plan.width();
        let tpl_height = plan.height();

        if img_width < tpl_width || img_height < tpl_height {
            return f32::NEG_INFINITY;
        }
        if x > img_width - tpl_width || y > img_height - tpl_height {
            return f32::NEG_INFINITY;
        }

        Self::score_at_simd(image, plan, x, y, min_var_i)
    }

    fn scan_full(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        angle_idx: usize,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range(
            image,
            plan,
            angle_idx,
            ScanRoi::new(0, 0, usize::MAX, usize::MAX),
            params,
        )
    }

    fn scan_roi(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        angle_idx: usize,
        x0: usize,
        y0: usize,
        x1: usize,
        y1: usize,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range(image, plan, angle_idx, ScanRoi::new(x0, y0, x1, y1), params)
    }
}

/// SIMD-accelerated unmasked SSD kernel.
pub struct SsdUnmaskedSimd;

impl SsdUnmaskedSimd {
    /// Computes SSD score at a single position using SIMD.
    fn score_at_simd(image: ImageView<'_, u8>, tpl: &SsdTemplatePlan, x: usize, y: usize) -> f32 {
        let tpl_width = tpl.width();
        let tpl_height = tpl.height();
        let data = tpl.data();

        let mut sse_vec = f32x8::ZERO;
        let mut sse_s = 0.0f32;

        let simd_end = tpl_width / LANES * LANES;

        for ty in 0..tpl_height {
            let img_row = match image.row(y + ty) {
                Some(row) => row,
                None => return f32::NEG_INFINITY,
            };
            let base = ty * tpl_width;

            // SIMD portion
            let mut tx = 0;
            while tx < simd_end {
                let img_vals = load_u8x8_as_f32x8(&img_row[x + tx..]);
                let tpl_vals = load_f32x8(&data[base + tx..]);
                let diff = img_vals - tpl_vals;
                sse_vec += diff * diff;
                tx += LANES;
            }

            // Scalar remainder
            while tx < tpl_width {
                let value = img_row[x + tx] as f32;
                let diff = value - data[base + tx];
                sse_s += diff * diff;
                tx += 1;
            }
        }

        let sse = hsum(sse_vec) + sse_s;
        if sse.is_finite() {
            -sse
        } else {
            f32::NEG_INFINITY
        }
    }

    fn scan_range(
        image: ImageView<'_, u8>,
        tpl: &SsdTemplatePlan,
        angle_idx: usize,
        roi: ScanRoi,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        if params.topk == 0 {
            return Ok(Vec::new());
        }

        let img_width = image.width();
        let img_height = image.height();
        let tpl_width = tpl.width();
        let tpl_height = tpl.height();

        if img_width < tpl_width || img_height < tpl_height {
            return Err(CorrMatchError::RoiOutOfBounds {
                x: 0,
                y: 0,
                width: tpl_width,
                height: tpl_height,
                img_width,
                img_height,
            });
        }

        let max_x = img_width - tpl_width;
        let max_y = img_height - tpl_height;
        let roi = match roi.clamp_inclusive(max_x, max_y) {
            Some(roi) => roi,
            None => return Ok(Vec::new()),
        };

        let mut topk_buf = TopK::new(params.topk);
        for y in roi.y0..=roi.y1 {
            for x in roi.x0..=roi.x1 {
                let score = Self::score_at_simd(image, tpl, x, y);
                if score.is_finite() && score >= params.min_score {
                    topk_buf.push(Peak {
                        x,
                        y,
                        score,
                        angle_idx,
                    });
                }
            }
        }

        Ok(topk_buf.into_sorted_desc())
    }
}

impl Kernel for SsdUnmaskedSimd {
    type Plan = SsdTemplatePlan;

    fn score_at(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        x: usize,
        y: usize,
        _min_var_i: f32,
    ) -> f32 {
        let img_width = image.width();
        let img_height = image.height();
        let tpl_width = plan.width();
        let tpl_height = plan.height();

        if img_width < tpl_width || img_height < tpl_height {
            return f32::NEG_INFINITY;
        }
        if x > img_width - tpl_width || y > img_height - tpl_height {
            return f32::NEG_INFINITY;
        }

        Self::score_at_simd(image, plan, x, y)
    }

    fn scan_full(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        angle_idx: usize,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range(
            image,
            plan,
            angle_idx,
            ScanRoi::new(0, 0, usize::MAX, usize::MAX),
            params,
        )
    }

    fn scan_roi(
        image: ImageView<'_, u8>,
        plan: &Self::Plan,
        angle_idx: usize,
        x0: usize,
        y0: usize,
        x1: usize,
        y1: usize,
        params: ScanParams,
    ) -> CorrMatchResult<Vec<Peak>> {
        Self::scan_range(image, plan, angle_idx, ScanRoi::new(x0, y0, x1, y1), params)
    }
}