//! The face crop both phones hand their face model (DECISIONS.md question 5: //! HyperFace-50k now, our own HyperFace-trained model later): five points in, //! the ArcFace 112 × 112 layout out, computed here so an iPhone and an Android //! phone feed the model the same pixels for the same face. //! //! - **Points:** eyes (the one on the picture's left first), nose tip, mouth //! corners (left first), each `x, y` as a share of the picture's width and //! height, origin top left: what the iPhone's `AlbumsAnalysis.fivePoints` //! and ML Kit's landmarks give once normalised. //! - **Fit:** the least-squares similarity (scale, rotation, shift; never a //! mirror) taking the five points onto [`TEMPLATE`] (Umeyama), as the //! iPhone's `AlbumsAlign` does. //! - **Sampling:** each output pixel's centre is taken back through the fit //! and read bilinearly from the picture (pixel centres at `i + 0.5`); //! outside the picture is black. /// ArcFace's five points in a 112 × 112 crop. pub const TEMPLATE: [(f32, f32); 5] = [(38.2946, 51.6963), (73.5318, 51.5014), (56.0252, 71.7366), (41.5493, 92.3655), (70.7299, 92.2041)]; pub const SIDE: u32 = 112; /// `dst = [c −s; s c]·src + (tx, ty)`. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Similarity { pub c: f32, pub s: f32, pub tx: f32, pub ty: f32, } /// The fit from the points (in pixels) onto the template scaled to `side`. /// `None` for points that cannot be a face: not finite, fewer than five, all /// in one place, or eyes not apart. pub fn fit(points_px: &[(f32, f32)], side: u32) -> Option { if points_px.len() != 5 || points_px.iter().any(|(x, y)| !x.is_finite() || !y.is_finite()) { return None; } let (ex, ey) = (points_px[1].0 - points_px[0].0, points_px[1].1 - points_px[0].1); if (ex * ex + ey * ey).sqrt() < 1.0 { return None; } let scale = side as f32 / SIDE as f32; let dst: Vec<(f32, f32)> = TEMPLATE.iter().map(|(x, y)| (x * scale, y * scale)).collect(); let mean = |p: &[(f32, f32)]| (p.iter().map(|q| q.0).sum::() / 5.0, p.iter().map(|q| q.1).sum::() / 5.0); let (ms, md) = (mean(points_px), mean(&dst)); let (mut a, mut b, mut norm) = (0f32, 0f32, 0f32); for i in 0..5 { let (sx, sy) = (points_px[i].0 - ms.0, points_px[i].1 - ms.1); let (dx, dy) = (dst[i].0 - md.0, dst[i].1 - md.1); a += sx * dx + sy * dy; b += sx * dy - sy * dx; norm += sx * sx + sy * sy; } if norm <= 0.0 { return None; } let (c, s) = (a / norm, b / norm); if c * c + s * s <= f32::EPSILON { return None; } Some(Similarity { c, s, tx: md.0 - (c * ms.0 - s * ms.1), ty: md.1 - (s * ms.0 + c * ms.1) }) } /// The aligned crop: `pixels` is the picture row by row from the top with /// `channels` bytes a pixel (3: RGB, 4: RGBA); `points` are the five points /// as shares of width and height (x0, y0, … x4, y4). Answers RGB bytes, /// `side` × `side`, row by row from the top. pub fn align(pixels: &[u8], width: u32, height: u32, channels: usize, points: &[f32; 10], side: u32) -> Option> { if !(channels == 3 || channels == 4) || width == 0 || height == 0 || side == 0 || pixels.len() != width as usize * height as usize * channels { return None; } let (w, h) = (width as f32, height as f32); let src: Vec<(f32, f32)> = (0..5).map(|i| (points[2 * i] * w, points[2 * i + 1] * h)).collect(); let t = fit(&src, side)?; // the inverse of [c −s; s c]: [c s; −s c] / (c² + s²) let d = t.c * t.c + t.s * t.s; let n = side as usize; let mut out = vec![0u8; n * n * 3]; let read = |x: i64, y: i64, k: usize| -> f32 { if x < 0 || y < 0 || x >= width as i64 || y >= height as i64 { 0.0 } else { pixels[(y as usize * width as usize + x as usize) * channels + k] as f32 } }; for oy in 0..n { for ox in 0..n { let (u, v) = (ox as f32 + 0.5 - t.tx, oy as f32 + 0.5 - t.ty); let sx = (t.c * u + t.s * v) / d - 0.5; let sy = (-t.s * u + t.c * v) / d - 0.5; let (x0, y0) = (sx.floor(), sy.floor()); let (fx, fy) = (sx - x0, sy - y0); let (x0, y0) = (x0 as i64, y0 as i64); for k in 0..3 { let top = read(x0, y0, k) * (1.0 - fx) + read(x0 + 1, y0, k) * fx; let bottom = read(x0, y0 + 1, k) * (1.0 - fx) + read(x0 + 1, y0 + 1, k) * fx; out[(oy * n + ox) * 3 + k] = (top * (1.0 - fy) + bottom * fy).round().clamp(0.0, 255.0) as u8; } } } Some(out) } #[cfg(test)] mod tests { use super::*; /// A picture with a smooth pattern: each channel a different slope. fn picture(w: u32, h: u32) -> Vec { let mut p = Vec::with_capacity((w * h * 4) as usize); for y in 0..h { for x in 0..w { p.extend_from_slice(&[(x * 255 / w.max(1)) as u8, (y * 255 / h.max(1)) as u8, ((x + y) * 255 / (w + h)) as u8, 255]); } } p } fn template_points(w: f32, h: f32, map: impl Fn(f32, f32) -> (f32, f32)) -> [f32; 10] { let mut out = [0f32; 10]; for (i, (x, y)) in TEMPLATE.iter().enumerate() { let (px, py) = map(*x, *y); out[2 * i] = px / w; out[2 * i + 1] = py / h; } out } #[test] fn a_face_already_in_place_comes_back_as_it_was() { let pic = picture(112, 112); let crop = align(&pic, 112, 112, 4, &template_points(112.0, 112.0, |x, y| (x, y)), SIDE).unwrap(); for i in 0..112 * 112 { assert_eq!(&crop[3 * i..3 * i + 3], &pic[4 * i..4 * i + 3]); } } #[test] fn a_turned_and_larger_face_is_brought_back_to_the_template() { // the face drawn twice as large, turned 30°, somewhere in a 400 × 300 picture let (w, h) = (400u32, 300u32); let (ang, k, ox, oy) = (30f32.to_radians(), 2.0f32, 150.0f32, 40.0f32); let to_pic = |x: f32, y: f32| (k * (ang.cos() * x - ang.sin() * y) + ox, k * (ang.sin() * x + ang.cos() * y) + oy); let points = template_points(w as f32, h as f32, to_pic); let t = fit(&(0..5).map(|i| (points[2 * i] * w as f32, points[2 * i + 1] * h as f32)).collect::>(), SIDE).unwrap(); // the fit undoes the turn and the scale exactly assert!((t.c - ang.cos() / k).abs() < 1e-4 && (t.s + ang.sin() / k).abs() < 1e-4, "{t:?}"); // and each template point lands where the face's point was drawn let pic = picture(w, h); let crop = align(&pic, w, h, 4, &points, SIDE).unwrap(); for (x, y) in TEMPLATE { let (px, py) = to_pic(x, y); let (sx, sy) = (px as usize, py as usize); let want = &pic[(sy * w as usize + sx) * 4..(sy * w as usize + sx) * 4 + 3]; let got = &crop[(y as usize * 112 + x as usize) * 3..(y as usize * 112 + x as usize) * 3 + 3]; for c in 0..3 { assert!((want[c] as i32 - got[c] as i32).abs() <= 3, "at {x},{y}: {want:?} vs {got:?}"); } } } #[test] fn rgb_and_rgba_give_the_same_crop_and_other_sides_scale_the_template() { let pic = picture(200, 160); let rgb: Vec = pic.chunks(4).flat_map(|p| [p[0], p[1], p[2]]).collect(); let pts = template_points(200.0, 160.0, |x, y| (x * 1.3 + 20.0, y * 1.3 + 5.0)); assert_eq!(align(&pic, 200, 160, 4, &pts, SIDE), align(&rgb, 200, 160, 3, &pts, SIDE)); assert_eq!(align(&pic, 200, 160, 4, &pts, 224).unwrap().len(), 224 * 224 * 3); } #[test] fn impossible_points_make_no_crop() { let pic = picture(100, 100); assert!(align(&pic, 100, 100, 4, &[0.5; 10], SIDE).is_none(), "all in one place"); let mut nan = template_points(100.0, 100.0, |x, y| (x, y)); nan[3] = f32::NAN; assert!(align(&pic, 100, 100, 4, &nan, SIDE).is_none()); assert!(align(&pic[..10], 100, 100, 4, &template_points(100.0, 100.0, |x, y| (x, y)), SIDE).is_none(), "pixels do not fill the picture"); } }