crates/korp-map-quality/src/compare.rs
//! **Visual regression**: a candidate render against the saved baseline image of the same
//! view. Two numbers: the share of pixels that changed by more than a tolerance (per
//! channel), and the mean SSIM over 8×8 blocks of luma (perceptual: structure moved, not
//! just a colour shift). Either over its threshold flags the view, and a side-by-side
//! image (baseline | candidate | where they differ) is written for eyes.
use serde::{Deserialize, Serialize};
use crate::metrics::{Hud, Rgb};
/// Thresholds.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Thresholds {
/// A pixel differs when a channel moved more than this.
pub pixel_tol: u8,
/// Flag when more than this % of pixels differ.
pub max_diff_pct: f64,
/// Flag when the mean block SSIM falls under this.
pub min_ssim: f64,
}
impl Default for Thresholds {
fn default() -> Self {
Self {
pixel_tol: 32,
max_diff_pct: 2.0,
min_ssim: 0.95,
}
}
}
/// One view's comparison.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Compared {
pub view: String,
pub diff_pct: f64,
pub ssim: f64,
pub flagged: bool,
pub note: Option<String>,
}
fn luma(p: [u8; 3]) -> f64 {
0.299 * f64::from(p[0]) + 0.587 * f64::from(p[1]) + 0.114 * f64::from(p[2])
}
/// Compare two images of the same size (HUD excluded).
#[must_use]
pub fn compare(view: &str, a: &Rgb, b: &Rgb, hud: &Hud, t: &Thresholds) -> Compared {
let mut c = Compared {
view: view.into(),
..Compared::default()
};
if a.width != b.width || a.height != b.height {
c.flagged = true;
c.note = Some(format!(
"size {}x{} vs {}x{}",
a.width, a.height, b.width, b.height
));
return c;
}
let (w, h) = (a.width as usize, a.height as usize);
let (mut n, mut d) = (0usize, 0usize);
for i in 0..w * h {
if hud.hides(a.width, a.height, (i % w) as u32, (i / w) as u32) {
continue;
}
n += 1;
if a.px[i]
.iter()
.zip(b.px[i])
.any(|(&x, y)| x.abs_diff(y) > t.pixel_tol)
{
d += 1;
}
}
c.diff_pct = if n == 0 {
0.0
} else {
100.0 * d as f64 / n as f64
};
// Block SSIM, 8×8, non-overlapping, on luma.
let (c1, c2) = ((0.01f64 * 255.0).powi(2), (0.03f64 * 255.0).powi(2));
let (mut sum, mut blocks) = (0.0, 0usize);
for by in (0..h.saturating_sub(7)).step_by(8) {
for bx in (0..w.saturating_sub(7)).step_by(8) {
if hud.hides(a.width, a.height, bx as u32, by as u32)
|| hud.hides(a.width, a.height, bx as u32 + 7, by as u32 + 7)
{
continue;
}
let (mut ma, mut mb, mut va, mut vb, mut cov) = (0.0, 0.0, 0.0, 0.0, 0.0);
for y in by..by + 8 {
for x in bx..bx + 8 {
let (p, q) = (luma(a.px[y * w + x]), luma(b.px[y * w + x]));
ma += p;
mb += q;
}
}
ma /= 64.0;
mb /= 64.0;
for y in by..by + 8 {
for x in bx..bx + 8 {
let (p, q) = (luma(a.px[y * w + x]) - ma, luma(b.px[y * w + x]) - mb);
va += p * p;
vb += q * q;
cov += p * q;
}
}
va /= 63.0;
vb /= 63.0;
cov /= 63.0;
sum += ((2.0 * ma * mb + c1) * (2.0 * cov + c2))
/ ((ma * ma + mb * mb + c1) * (va + vb + c2));
blocks += 1;
}
}
c.ssim = if blocks == 0 {
1.0
} else {
sum / blocks as f64
};
c.flagged = c.diff_pct > t.max_diff_pct || c.ssim < t.min_ssim;
c
}
/// Half-size side-by-side: baseline | candidate | difference (changed pixels red over a
/// dimmed baseline).
#[must_use]
pub fn two_up(a: &Rgb, b: &Rgb, t: &Thresholds) -> Rgb {
let (w, h) = (
a.width.min(b.width) as usize,
a.height.min(b.height) as usize,
);
let (hw, hh) = (w / 2, h / 2);
let gap = 8;
let ow = hw * 3 + gap * 2;
let mut px = vec![[255u8, 255, 255]; ow * hh];
let at = |img: &Rgb, x: usize, y: usize| img.px[y * img.width as usize + x];
for y in 0..hh {
for x in 0..hw {
let (sx, sy) = (x * 2, y * 2);
let avg = |img: &Rgb| {
let mut s = [0u32; 3];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = at(img, sx + dx, sy + dy);
for k in 0..3 {
s[k] += u32::from(p[k]);
}
}
[(s[0] / 4) as u8, (s[1] / 4) as u8, (s[2] / 4) as u8]
};
let (pa, pb) = (avg(a), avg(b));
px[y * ow + x] = pa;
px[y * ow + hw + gap + x] = pb;
let changed = [(0, 0), (1, 0), (0, 1), (1, 1)].iter().any(|&(dx, dy)| {
at(a, sx + dx, sy + dy)
.iter()
.zip(at(b, sx + dx, sy + dy))
.any(|(&p, q)| p.abs_diff(q) > t.pixel_tol)
});
px[y * ow + 2 * (hw + gap) + x] = if changed {
[255, 40, 40]
} else {
[pa[0] / 3, pa[1] / 3, pa[2] / 3]
};
}
}
Rgb {
width: ow as u32,
height: hh as u32,
px,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn img(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 3]) -> Rgb {
Rgb {
width: w,
height: h,
px: (0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.map(|(x, y)| f(x, y))
.collect(),
}
}
#[test]
fn identical_images_pass_and_a_moved_shape_flags() {
let hud = Hud {
top: 0,
bottom: 0,
badge: [0, 0, 0, 0],
};
let t = Thresholds::default();
let a = img(64, 64, |x, y| {
if (x / 8 + y / 8) % 2 == 0 {
[200, 200, 200]
} else {
[20, 20, 20]
}
});
let same = compare("v", &a, &a.clone(), &hud, &t);
assert_eq!(same.diff_pct, 0.0);
assert!((same.ssim - 1.0).abs() < 1e-9 && !same.flagged);
let b = img(64, 64, |x, y| {
if ((x + 4) / 8 + y / 8) % 2 == 0 {
[200, 200, 200]
} else {
[20, 20, 20]
}
});
let moved = compare("v", &a, &b, &hud, &t);
assert!(
moved.flagged && moved.diff_pct > 40.0 && moved.ssim < 0.6,
"{moved:?}"
);
let up = two_up(&a, &b, &t);
assert_eq!(up.width, 32 * 3 + 16);
}
#[test]
fn a_faint_tint_is_not_a_regression() {
let hud = Hud {
top: 0,
bottom: 0,
badge: [0, 0, 0, 0],
};
let a = img(32, 32, |x, _| [x as u8 * 4, 90, 40]);
let b = img(32, 32, |x, _| [x as u8 * 4 + 3, 92, 40]);
let c = compare("v", &a, &b, &hud, &Thresholds::default());
assert!(!c.flagged, "{c:?}");
}
}