|
| 1 | +//! Dominant gradient-orientation estimation. |
| 2 | +//! |
| 3 | +//! A linear barcode is the most orientation-coherent texture there is: every bar edge |
| 4 | +//! points the gradient along the *reading* axis, so the gradient-orientation histogram |
| 5 | +//! of a barcode crop has one overwhelming peak (modulo 180° — a gradient cannot tell a |
| 6 | +//! code from its upside-down self). [`dominant_gradient_angle`] measures that peak and |
| 7 | +//! how dominant it is, letting a scanning pipeline *derotate* a crop whose code is not |
| 8 | +//! within its scanline sweep instead of blindly re-scanning at every angle. |
| 9 | +
|
| 10 | +use crate::image::GrayFrame; |
| 11 | + |
| 12 | +/// Histogram bins across the half-circle: 3° per bin. |
| 13 | +const BINS: usize = 60; |
| 14 | + |
| 15 | +/// Minimum squared gradient magnitude for a pixel to vote; rejects sensor noise and |
| 16 | +/// flat background so the histogram is built from real edges. |
| 17 | +const MIN_MAG2: f32 = 24.0 * 24.0; |
| 18 | + |
| 19 | +/// Fraction of total edge energy that must fall within ±2 bins (±7.5°) of the peak for |
| 20 | +/// the orientation to count as *dominant*. Barcodes score far above this; text, matrix |
| 21 | +/// codes and scene texture spread their energy and fall below. |
| 22 | +const MIN_COHERENCE: f32 = 0.4; |
| 23 | + |
| 24 | +/// Estimate the dominant edge orientation of `frame` in radians, in `(-π/2, π/2]`, |
| 25 | +/// measured from the +x axis — for a barcode this is the *reading* direction (bars are |
| 26 | +/// perpendicular to it). Returns `None` when the texture has no sufficiently dominant |
| 27 | +/// orientation (nothing bar-like to derotate for). |
| 28 | +pub fn dominant_gradient_angle(frame: &GrayFrame<'_>) -> Option<f32> { |
| 29 | + let w = frame.width(); |
| 30 | + let h = frame.height(); |
| 31 | + if w < 8 || h < 8 { |
| 32 | + return None; |
| 33 | + } |
| 34 | + |
| 35 | + // Histogram of gradient orientation mod π, weighted by squared magnitude. |
| 36 | + let mut hist = [0.0f32; BINS]; |
| 37 | + let mut total = 0.0f32; |
| 38 | + for y in 1..h - 1 { |
| 39 | + for x in 1..w - 1 { |
| 40 | + let gx = f32::from(frame.get_unchecked(x + 1, y)) |
| 41 | + - f32::from(frame.get_unchecked(x - 1, y)); |
| 42 | + let gy = f32::from(frame.get_unchecked(x, y + 1)) |
| 43 | + - f32::from(frame.get_unchecked(x, y - 1)); |
| 44 | + let mag2 = gx * gx + gy * gy; |
| 45 | + if mag2 < MIN_MAG2 { |
| 46 | + continue; |
| 47 | + } |
| 48 | + let a = gy.atan2(gx).rem_euclid(core::f32::consts::PI); |
| 49 | + let bin = ((a / core::f32::consts::PI) * BINS as f32) as usize % BINS; |
| 50 | + hist[bin] += mag2; |
| 51 | + total += mag2; |
| 52 | + } |
| 53 | + } |
| 54 | + if total <= 0.0 { |
| 55 | + return None; |
| 56 | + } |
| 57 | + |
| 58 | + // Light circular 1-2-1 smoothing so the peak does not split across a bin edge. |
| 59 | + let mut smooth = [0.0f32; BINS]; |
| 60 | + for i in 0..BINS { |
| 61 | + let l = hist[(i + BINS - 1) % BINS]; |
| 62 | + let r = hist[(i + 1) % BINS]; |
| 63 | + smooth[i] = 0.25 * l + 0.5 * hist[i] + 0.25 * r; |
| 64 | + } |
| 65 | + let peak = (0..BINS) |
| 66 | + .max_by(|&a, &b| smooth[a].partial_cmp(&smooth[b]).unwrap()) |
| 67 | + .unwrap(); |
| 68 | + |
| 69 | + // Coherence: energy near the peak vs everywhere. Uses the raw histogram so the |
| 70 | + // smoothing above cannot inflate it. |
| 71 | + let near: f32 = (-2i32..=2) |
| 72 | + .map(|d| hist[(peak as i32 + d).rem_euclid(BINS as i32) as usize]) |
| 73 | + .sum(); |
| 74 | + if near / total < MIN_COHERENCE { |
| 75 | + return None; |
| 76 | + } |
| 77 | + |
| 78 | + // Sub-bin angle: circular mean over the peak neighbourhood in double-angle space |
| 79 | + // (which keeps 0 and π identified, exactly the mod-π symmetry of orientations). |
| 80 | + let (mut sx, mut sy) = (0.0f64, 0.0f64); |
| 81 | + for d in -2i32..=2 { |
| 82 | + let i = (peak as i32 + d).rem_euclid(BINS as i32) as usize; |
| 83 | + let centre = (i as f64 + 0.5) / BINS as f64 * core::f64::consts::PI; |
| 84 | + sx += f64::from(hist[i]) * (2.0 * centre).cos(); |
| 85 | + sy += f64::from(hist[i]) * (2.0 * centre).sin(); |
| 86 | + } |
| 87 | + if sx == 0.0 && sy == 0.0 { |
| 88 | + return None; |
| 89 | + } |
| 90 | + let mut angle = (sy.atan2(sx) / 2.0) as f32; // (-π/2, π/2] |
| 91 | + if angle <= -core::f32::consts::FRAC_PI_2 { |
| 92 | + angle += core::f32::consts::PI; |
| 93 | + } |
| 94 | + Some(angle) |
| 95 | +} |
| 96 | + |
| 97 | +#[cfg(test)] |
| 98 | +mod tests { |
| 99 | + use super::*; |
| 100 | + use crate::image::GrayImage; |
| 101 | + |
| 102 | + /// Bars of period 8 px perpendicular to `angle` (so the *reading* axis is `angle`), |
| 103 | + /// with soft (tanh-profile, ~1 px) edges. A camera never delivers hard staircase |
| 104 | + /// edges — real optics blur every transition — and aliased steps would put |
| 105 | + /// spurious diagonal energy into the gradient histogram that no real capture has. |
| 106 | + fn bars(angle: f32) -> GrayImage { |
| 107 | + let (s, c) = angle.sin_cos(); |
| 108 | + let mut img = GrayImage::new(128, 128); |
| 109 | + for y in 0..128 { |
| 110 | + for x in 0..128 { |
| 111 | + // Position along the reading axis, phase within the 2-bar period. |
| 112 | + let t = c * x as f32 + s * y as f32; |
| 113 | + let ph = (t / 8.0).rem_euclid(2.0); |
| 114 | + // Distance (px) to the nearest bar edge; dark half is ph < 1. |
| 115 | + let d = ph.min((1.0 - ph).abs()).min(2.0 - ph) * 8.0; |
| 116 | + let soft = (d / 1.2).tanh(); |
| 117 | + let side = if ph < 1.0 { -1.0 } else { 1.0 }; |
| 118 | + img.set(x, y, (127.5 + 127.4 * side * soft).round() as u8); |
| 119 | + } |
| 120 | + } |
| 121 | + img |
| 122 | + } |
| 123 | + |
| 124 | + #[test] |
| 125 | + fn recovers_bar_orientation() { |
| 126 | + for deg in [0.0f32, 20.0, 45.0, 90.0, -30.0, -75.0] { |
| 127 | + let angle = deg.to_radians(); |
| 128 | + let img = bars(angle); |
| 129 | + let got = dominant_gradient_angle(&img.as_frame()) |
| 130 | + .unwrap_or_else(|| panic!("no orientation for {deg}°")); |
| 131 | + // Compare modulo π. |
| 132 | + let mut diff = (got - angle).rem_euclid(core::f32::consts::PI); |
| 133 | + if diff > core::f32::consts::FRAC_PI_2 { |
| 134 | + diff = core::f32::consts::PI - diff; |
| 135 | + } |
| 136 | + assert!( |
| 137 | + diff.to_degrees() < 4.0, |
| 138 | + "angle {deg}°: got {:.1}° (diff {:.1}°)", |
| 139 | + got.to_degrees(), |
| 140 | + diff.to_degrees() |
| 141 | + ); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + #[test] |
| 146 | + fn rejects_isotropic_texture() { |
| 147 | + // A checkerboard has equal horizontal and vertical edge energy. |
| 148 | + let mut img = GrayImage::filled(96, 96, 255); |
| 149 | + for y in 0..96 { |
| 150 | + for x in 0..96 { |
| 151 | + if (x / 6 + y / 6) % 2 == 0 { |
| 152 | + img.set(x, y, 0); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + assert!(dominant_gradient_angle(&img.as_frame()).is_none()); |
| 157 | + } |
| 158 | +} |
0 commit comments