fovea 0.5.1

A high-precision, type-safe computer vision library guaranteeing absolute image correctness at compile time
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
632
633
634
635
636
637
638
use crate::common::Size;
use core::fmt;

/// Errors returned by fallible image operations.
///
/// This type represents data-dependent failures — situations where the
/// operation is well-formed but the supplied data doesn't meet the
/// requirements. The crate uses a three-tier error handling convention:
/// `Option` for absence, `Result<T, Error>` for data-dependent failure,
/// and `panic!` for programmer bugs.
///
/// # Tier summary
///
/// | Tier | Type | When |
/// |------|------|------|
/// | 1 | `Option` | Absence — query found nothing (e.g. `get()` out of bounds) |
/// | 2 | `Result<T, Error>` | Data failure — caller-supplied data doesn't fit |
/// | 3 | `panic!` | Programmer bug — violated precondition (e.g. output size mismatch) |
///
/// # Examples
///
/// ```
/// use fovea::Error;
/// use fovea::Size;
///
/// let err = Error::LengthMismatch { expected: 100, actual: 50 };
/// assert_eq!(
///     err.to_string(),
///     "length mismatch: expected 100 elements, got 50"
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// Two images that must have identical dimensions do not.
    ///
    /// Returned by [`combine_images`](crate::transform::combine_images),
    /// [`zip_pixels`](crate::image::zip_pixels), and similar functions
    /// that operate on image pairs.
    SizeMismatch {
        /// The dimensions of the first / reference image.
        expected: Size,
        /// The dimensions of the second image that does not match.
        actual: Size,
    },

    /// A data buffer's element count does not match the required
    /// dimensions.
    ///
    /// Returned by [`Image::from_vec`](crate::image::sequential::Image::from_vec),
    /// [`ImageRef::new`](crate::image::sequential::ImageRef::new), and similar
    /// constructors where `data.len() != width * height`.
    LengthMismatch {
        /// The number of elements required (`width * height`, or
        /// `width * height * pixel_size` for byte constructors).
        expected: usize,
        /// The number of elements actually provided.
        actual: usize,
    },

    /// The number of image planes does not match the pixel type's
    /// channel count.
    ///
    /// Returned by [`ImagePlanes::try_from_planes`](crate::image::ImagePlanes::try_from_planes).
    ChannelCountMismatch {
        /// The channel count required by the pixel type.
        expected: usize,
        /// The number of planes actually provided.
        actual: usize,
    },

    /// The requested `pyr_up` target is not a size whose `pyr_down`
    /// result is the source image's size.
    ///
    /// Returned by [`pyr_up`](crate::transform::pyr_up) when
    /// `target.width ∉ {2·w − 1, 2·w}` or
    /// `target.height ∉ {2·h − 1, 2·h}` for a `w`×`h` source image.
    /// Because `pyr_down` uses ceiling division, both the odd and the
    /// even parent dimension are valid targets — anything else cannot
    /// be the parent of this image.
    InvalidPyrUpTarget {
        /// The dimensions of the source image being upsampled.
        source: Size,
        /// The rejected target dimensions.
        target: Size,
    },

    /// A pyramid was constructed from an empty level list.
    ///
    /// Returned by
    /// [`LevelChain::try_from_levels`](crate::image::LevelChain::try_from_levels) —
    /// a pyramid always contains at least one level.
    EmptyPyramid,

    /// Pyramid levels are not ordered finest to coarsest.
    ///
    /// Returned by
    /// [`LevelChain::try_from_levels`](crate::image::LevelChain::try_from_levels)
    /// when a level is larger than its predecessor along either axis.
    /// Levels must be non-increasing in both width and height (equal sizes
    /// are allowed — same-size levels occur in scale stacks and sub-band
    /// decompositions). Levels are never reordered automatically: a wrong
    /// order is reported, not silently normalized.
    PyramidLevelOrder {
        /// Index of the first level that violates the ordering.
        index: usize,
        /// The dimensions of the preceding level.
        previous: Size,
        /// The dimensions of the offending level.
        current: Size,
    },

    /// Pyramid levels do not halve from one level to the next.
    ///
    /// Returned by [`Dyadic::try_new`](crate::image::Dyadic::try_new) when a
    /// level's size is not its predecessor's ceiling-halved size along both
    /// axes, which is the relation [`pyr_down`](crate::transform::pyr_down)
    /// produces. A chain may be perfectly well ordered and still not be
    /// dyadic: equal-size neighbours and a chain that shrinks by some other
    /// factor both pass
    /// [`LevelChain::try_from_levels`](crate::image::LevelChain::try_from_levels)
    /// on purpose. Because the relation holds between two runtime sizes,
    /// this is a recoverable error, not a panic.
    NotDyadic {
        /// Index of the first level that does not halve its predecessor.
        index: usize,
        /// The dimensions of the preceding level.
        parent: Size,
        /// The dimensions of the offending level.
        child: Size,
    },

    /// A computed value violates a parameter type's invariant.
    ///
    /// Returned by the `try_new` constructors of the invariant-carrying
    /// parameter types — [`Sigma`](crate::Sigma),
    /// [`PixelDistance`](crate::PixelDistance),
    /// [`Tolerance`](crate::Tolerance),
    /// [`OddWindowSide`](crate::OddWindowSide),
    /// [`HysteresisThresholds`](crate::analyze::threshold::HysteresisThresholds),
    /// [`Clamp`](crate::transform::Clamp),
    /// [`Harris`](crate::features::detect::Harris),
    /// [`SegmentTest`](crate::features::detect::SegmentTest),
    /// [`NmsRadius`](crate::features::detect::NmsRadius),
    /// [`PeakValue`](crate::analyze::quality::PeakValue),
    /// [`BayerGains`](crate::transform::BayerGains) and their kin — and by
    /// validating functions whose parameter is a plain value. What
    /// "invalid" means is the type's own invariant: a sign or finiteness
    /// condition for the float parameters, a parity or at-least-one
    /// condition for the integer ones, an ordering relation between two
    /// values for the pairs. The constructor's documentation states it.
    ///
    /// This is the *computed-value* path, for parameters derived from data
    /// at run time. A literal parameter does not need it: the types carry
    /// `const fn new -> Option` constructors, and where a literal is the
    /// normal input, a matching literal macro ([`sigma!`](crate::sigma),
    /// [`pixel_distance!`](crate::pixel_distance),
    /// [`tolerance!`](crate::tolerance), [`window!`](crate::window),
    /// [`harris!`](crate::harris), [`peak!`](crate::peak)) that rejects a
    /// bad literal at compile time.
    ///
    /// The contained string describes the specific reason. Treat it as
    /// human-readable diagnostic text, not as a stable machine-readable
    /// tag.
    InvalidParameter(String),

    /// The template is larger than the image in one or both dimensions.
    ///
    /// Returned by [`match_template`](crate::transform::match_template) when
    /// the template does not fit inside the image.
    TemplateTooLarge {
        /// The dimensions of the source image.
        image_size: Size,
        /// The dimensions of the template that does not fit.
        template_size: Size,
    },

    /// The template has zero width or height.
    ///
    /// Returned by [`match_template`](crate::transform::match_template) and
    /// [`match_template_into`](crate::transform::match_template_into) —
    /// an empty template (for example a degenerate user crop) has no
    /// defined score.
    EmptyTemplate {
        /// The dimensions of the degenerate template.
        template_size: Size,
    },

    /// A caller-supplied binning strategy contains invalid parameters.
    ///
    /// Returned by [`histogram`](crate::analyze::histogram::histogram()) when
    /// the strategy's `validate()` rejects its own configuration — for
    /// example, `LinearBins` with `min >= max`, non-finite bounds, a
    /// `bin_count` of zero, or `CustomBins` whose edges are not strictly
    /// increasing.
    ///
    /// The contained string describes the specific reason. Treat it as
    /// human-readable diagnostic text, not as a stable machine-readable
    /// tag.
    InvalidBinningStrategy(String),

    /// The chosen accumulator type cannot hold the worst-case sum for an
    /// image of this size.
    ///
    /// Returned by
    /// [`integral_image`](crate::analyze::integral::integral_image),
    /// [`integral_image_into`](crate::analyze::integral::integral_image_into),
    /// [`integral_squared_image`](crate::analyze::integral::integral_squared_image),
    /// and
    /// [`integral_squared_image_into`](crate::analyze::integral::integral_squared_image_into)
    /// when the O(1) pre-flight overflow check fails.
    ///
    /// `required_capacity` is the theoretical worst-case sum given the
    /// source image dimensions and pixel type. `accumulator_capacity` is
    /// the maximum value the accumulator pixel can hold (per channel,
    /// for multi-channel accumulators). Both are expressed as `u128`
    /// for a uniform representation across integer and floating-point
    /// accumulators (for floats, the capacity is the exact-integer range
    /// of the underlying float type, e.g. `2^53` for `f64`).
    AccumulatorOverflow {
        /// Worst-case sum the chosen accumulator would have to hold,
        /// expressed as `u128`. Set to `u128::MAX` if the worst-case
        /// computation itself overflowed `u128`.
        required_capacity: u128,
        /// Maximum value the accumulator type can hold, as `u128`.
        accumulator_capacity: u128,
    },

    /// The binary image contains more connected components than the
    /// chosen [`LabelPixel`](crate::pixel::LabelPixel) type can encode.
    ///
    /// Returned by
    /// [`connected_components`](crate::analyze::components::connected_components)
    /// and
    /// [`connected_components_into`](crate::analyze::components::connected_components_into)
    /// when pass 1 would allocate the `(label_capacity + 1)`-th
    /// provisional label. This is a Tier 2 / data-dependent error:
    /// a pre-flight check is impossible without running the labeling pass.
    ///
    /// `label_capacity` is `L::MAX_LABEL` for the chosen label type — the
    /// largest distinct foreground label it can represent. Callers can
    /// retry with a wider label type (e.g. `Label32` if a hypothetical
    /// narrower `Label16` overflowed).
    LabelOverflow {
        /// `MAX_LABEL` of the chosen label pixel type — the maximum
        /// foreground label the type can represent.
        label_capacity: u32,
    },
}

// `std::error::Error` is implemented manually (not via `thiserror`) to
// avoid pulling in a derive dependency for the core crate. The default
// blanket `source()` (returns `None`) is correct for every variant: no
// `Error` value wraps another `Error`. If we ever add a wrapping variant
// we must override `source` for it.
impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::SizeMismatch { expected, actual } => {
                write!(
                    f,
                    "size mismatch: expected {}x{}, got {}x{}",
                    expected.width, expected.height, actual.width, actual.height
                )
            }
            Error::LengthMismatch { expected, actual } => {
                write!(
                    f,
                    "length mismatch: expected {} elements, got {}",
                    expected, actual
                )
            }
            Error::ChannelCountMismatch { expected, actual } => {
                write!(
                    f,
                    "channel count mismatch: expected {} channels, got {}",
                    expected, actual
                )
            }
            Error::InvalidPyrUpTarget { source, target } => {
                write!(
                    f,
                    "invalid pyr_up target: {}x{} is not a size whose pyr_down is {}x{}",
                    target.width, target.height, source.width, source.height
                )
            }
            Error::EmptyPyramid => {
                write!(
                    f,
                    "empty pyramid: a pyramid must contain at least one level"
                )
            }
            Error::PyramidLevelOrder {
                index,
                previous,
                current,
            } => {
                write!(
                    f,
                    "pyramid level order: level {} is {}x{}, larger than its \
                     predecessor {}x{} (levels must be finest to coarsest)",
                    index, current.width, current.height, previous.width, previous.height
                )
            }
            Error::NotDyadic {
                index,
                parent,
                child,
            } => {
                write!(
                    f,
                    "not dyadic: level {} is {}x{}, but its predecessor {}x{} halves to \
                     {}x{} (every level must be ceil(parent / 2) along both axes)",
                    index,
                    child.width,
                    child.height,
                    parent.width,
                    parent.height,
                    parent.width / 2 + parent.width % 2,
                    parent.height / 2 + parent.height % 2
                )
            }
            Error::InvalidParameter(reason) => {
                write!(f, "invalid parameter: {}", reason)
            }
            Error::EmptyTemplate { template_size } => {
                write!(
                    f,
                    "empty template: {}x{} has zero width or height",
                    template_size.width, template_size.height
                )
            }
            Error::TemplateTooLarge {
                image_size,
                template_size,
            } => {
                write!(
                    f,
                    "template {}x{} is larger than image {}x{}",
                    template_size.width, template_size.height, image_size.width, image_size.height
                )
            }
            Error::InvalidBinningStrategy(reason) => {
                write!(f, "invalid binning strategy: {}", reason)
            }
            Error::AccumulatorOverflow {
                required_capacity,
                accumulator_capacity,
            } => {
                write!(
                    f,
                    "accumulator overflow: image requires capacity for {}, \
                     but accumulator can hold at most {}",
                    required_capacity, accumulator_capacity
                )
            }
            Error::LabelOverflow { label_capacity } => {
                write!(
                    f,
                    "label overflow: image contains more components than the \
                     chosen label type can represent (capacity = {})",
                    label_capacity
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_size_mismatch() {
        let err = Error::SizeMismatch {
            expected: Size::new(640, 480),
            actual: Size::new(320, 240),
        };
        assert_eq!(
            err.to_string(),
            "size mismatch: expected 640x480, got 320x240"
        );
    }

    #[test]
    fn display_length_mismatch() {
        let err = Error::LengthMismatch {
            expected: 100,
            actual: 50,
        };
        assert_eq!(
            err.to_string(),
            "length mismatch: expected 100 elements, got 50"
        );
    }

    #[test]
    fn display_channel_count_mismatch() {
        let err = Error::ChannelCountMismatch {
            expected: 3,
            actual: 2,
        };
        assert_eq!(
            err.to_string(),
            "channel count mismatch: expected 3 channels, got 2"
        );
    }

    #[test]
    fn error_is_clone() {
        let err = Error::LengthMismatch {
            expected: 10,
            actual: 5,
        };
        let cloned = err.clone();
        assert_eq!(err, cloned);
    }

    #[test]
    fn error_is_debug() {
        let err = Error::SizeMismatch {
            expected: Size::new(10, 10),
            actual: Size::new(5, 5),
        };
        let debug = format!("{:?}", err);
        assert!(debug.contains("SizeMismatch"));
    }

    #[test]
    fn error_equality() {
        let a = Error::LengthMismatch {
            expected: 100,
            actual: 50,
        };
        let b = Error::LengthMismatch {
            expected: 100,
            actual: 50,
        };
        let c = Error::LengthMismatch {
            expected: 100,
            actual: 99,
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn display_invalid_pyr_up_target() {
        let err = Error::InvalidPyrUpTarget {
            source: Size::new(4, 4),
            target: Size::new(9, 8),
        };
        assert_eq!(
            err.to_string(),
            "invalid pyr_up target: 9x8 is not a size whose pyr_down is 4x4"
        );
    }

    #[test]
    fn invalid_pyr_up_target_equality_and_clone() {
        let a = Error::InvalidPyrUpTarget {
            source: Size::new(4, 4),
            target: Size::new(9, 8),
        };
        let b = a.clone();
        let c = Error::InvalidPyrUpTarget {
            source: Size::new(4, 4),
            target: Size::new(6, 8),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn display_empty_pyramid() {
        assert_eq!(
            Error::EmptyPyramid.to_string(),
            "empty pyramid: a pyramid must contain at least one level"
        );
    }

    #[test]
    fn display_pyramid_level_order() {
        let err = Error::PyramidLevelOrder {
            index: 2,
            previous: Size::new(4, 3),
            current: Size::new(8, 6),
        };
        assert_eq!(
            err.to_string(),
            "pyramid level order: level 2 is 8x6, larger than its \
             predecessor 4x3 (levels must be finest to coarsest)"
        );
    }

    #[test]
    fn display_not_dyadic() {
        let err = Error::NotDyadic {
            index: 1,
            parent: Size::new(101, 68),
            child: Size::new(30, 34),
        };
        assert_eq!(
            err.to_string(),
            "not dyadic: level 1 is 30x34, but its predecessor 101x68 halves to \
             51x34 (every level must be ceil(parent / 2) along both axes)"
        );
    }

    #[test]
    fn display_invalid_parameter() {
        let err = Error::InvalidParameter("sigma must be positive, got -1".to_string());
        assert_eq!(
            err.to_string(),
            "invalid parameter: sigma must be positive, got -1"
        );
    }

    #[test]
    fn display_empty_template() {
        let err = Error::EmptyTemplate {
            template_size: Size::new(0, 5),
        };
        assert_eq!(
            err.to_string(),
            "empty template: 0x5 has zero width or height"
        );
    }

    #[test]
    fn display_template_too_large() {
        let err = Error::TemplateTooLarge {
            image_size: Size::new(10, 10),
            template_size: Size::new(20, 15),
        };
        assert_eq!(err.to_string(), "template 20x15 is larger than image 10x10");
    }

    #[test]
    fn different_variants_not_equal() {
        let size_err = Error::SizeMismatch {
            expected: Size::new(10, 10),
            actual: Size::new(5, 5),
        };
        let length_err = Error::LengthMismatch {
            expected: 100,
            actual: 25,
        };
        assert_ne!(size_err, length_err);
    }

    #[test]
    fn display_invalid_binning_strategy() {
        let err = Error::InvalidBinningStrategy("min >= max".to_string());
        assert_eq!(err.to_string(), "invalid binning strategy: min >= max");
    }

    #[test]
    fn display_accumulator_overflow() {
        let err = Error::AccumulatorOverflow {
            required_capacity: 4_278_190_080,
            accumulator_capacity: 4_294_967_295,
        };
        assert_eq!(
            err.to_string(),
            "accumulator overflow: image requires capacity for 4278190080, \
             but accumulator can hold at most 4294967295"
        );
    }

    #[test]
    fn accumulator_overflow_equality_and_clone() {
        let a = Error::AccumulatorOverflow {
            required_capacity: 100,
            accumulator_capacity: 50,
        };
        let b = a.clone();
        let c = Error::AccumulatorOverflow {
            required_capacity: 100,
            accumulator_capacity: 51,
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn display_label_overflow() {
        let err = Error::LabelOverflow {
            label_capacity: u32::MAX,
        };
        assert_eq!(
            err.to_string(),
            "label overflow: image contains more components than the chosen label type \
             can represent (capacity = 4294967295)"
        );
    }

    #[test]
    fn label_overflow_equality_and_clone() {
        let a = Error::LabelOverflow {
            label_capacity: 255,
        };
        let b = a.clone();
        let c = Error::LabelOverflow {
            label_capacity: 65_535,
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn invalid_binning_strategy_equality_and_clone() {
        let a = Error::InvalidBinningStrategy("bin_count == 0".to_string());
        let b = a.clone();
        let c = Error::InvalidBinningStrategy("non-finite edge".to_string());
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn error_implements_std_error_trait() {
        // P1-4: `Error` must integrate with the std error ecosystem so
        // it can be boxed into `Box<dyn std::error::Error>` and used with
        // `?` against `Box<dyn Error + Send + Sync>` sinks.
        fn assert_error<E: std::error::Error>() {}
        assert_error::<Error>();

        let err: Box<dyn std::error::Error> = Box::new(Error::LengthMismatch {
            expected: 10,
            actual: 5,
        });
        // Display reachable through the trait object.
        assert!(err.to_string().contains("length mismatch"));
        // No wrapped source (no Error variant wraps another error today).
        assert!(err.source().is_none());
    }
}