use crate::error::{Result, ScanError};
use crate::input::{ImageInput, Limits, LumaImage, bt601, validate_buffer, validate_dims};
use crate::ladder::AlphaBackground;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Channel {
R,
G,
B,
}
#[derive(Debug, Clone)]
pub(crate) struct SourcePlanes {
pub luma: LumaImage,
rgb: Option<Vec<u8>>,
}
impl SourcePlanes {
pub(crate) fn luma_only(luma: LumaImage) -> Self {
Self { luma, rgb: None }
}
pub(crate) fn has_color(&self) -> bool {
self.rgb.is_some()
}
pub(crate) fn channel(&self, channel: Channel) -> Option<LumaImage> {
let rgb = self.rgb.as_ref()?;
let offset = match channel {
Channel::R => 0,
Channel::G => 1,
Channel::B => 2,
};
let data: Vec<u8> = rgb[offset..].iter().step_by(3).copied().collect();
Some(LumaImage::new(data, self.luma.width(), self.luma.height()))
}
}
pub(crate) struct NormalizedInput {
pub planes: SourcePlanes,
pub alpha: Option<crate::alpha::AlphaContext>,
}
#[cfg(test)]
pub(crate) fn normalize(input: &ImageInput<'_>, limits: &Limits) -> Result<SourcePlanes> {
normalize_with(input, limits, AlphaBackground::Auto).map(|normalized| normalized.planes)
}
pub(crate) fn normalize_with(
input: &ImageInput<'_>,
limits: &Limits,
alpha_background: AlphaBackground,
) -> Result<NormalizedInput> {
match *input {
ImageInput::Luma8 {
data,
width,
height,
} => {
let pixels = validate_dims(width, height, limits)?;
validate_buffer(data.len(), pixels)?;
Ok(NormalizedInput {
planes: SourcePlanes {
luma: LumaImage::new(data.to_vec(), width, height),
rgb: None,
},
alpha: None,
})
}
ImageInput::Rgba8 {
data,
width,
height,
} => {
let pixels = validate_dims(width, height, limits)?;
let bytes = pixels.checked_mul(4).ok_or(ScanError::PixelOverflow {
width,
height,
max_pixels: limits.max_pixels,
})?;
validate_buffer(data.len(), bytes)?;
Ok(flatten_or_drop(data, width, height, alpha_background, true))
}
ImageInput::Encoded(bytes) => {
let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| ScanError::InvalidImage {
details: e.to_string(),
})?;
let (width, height) =
reader
.into_dimensions()
.map_err(|e| ScanError::InvalidImage {
details: e.to_string(),
})?;
validate_dims(width, height, limits)?;
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| ScanError::InvalidImage {
details: e.to_string(),
})?;
let mut decode_limits = image::Limits::default();
decode_limits.max_image_width = Some(limits.max_dimension);
decode_limits.max_image_height = Some(limits.max_dimension);
decode_limits.max_alloc = Some(limits.max_pixels.saturating_mul(8));
reader.limits(decode_limits);
let img = reader.decode().map_err(|e| ScanError::InvalidImage {
details: e.to_string(),
})?;
if alpha_background != AlphaBackground::None && img.color().has_alpha() {
let colored = img.color().has_color();
let converted;
let rgba = if let Some(borrowed) = img.as_rgba8() {
borrowed
} else {
converted = img.to_rgba8();
&converted
};
if crate::alpha::has_transparency(rgba.as_raw()) {
let stats = crate::alpha::content_stats(rgba.as_raw());
let (w, h) = (rgba.width(), rgba.height());
return Ok(flatten(
rgba.as_raw(),
w,
h,
alpha_background,
colored,
&stats,
));
}
}
let rgb = img.color().has_color().then(|| img.to_rgb8().into_raw());
let luma = img.into_luma8();
let (w, h) = (luma.width(), luma.height());
Ok(NormalizedInput {
planes: SourcePlanes {
luma: LumaImage::new(luma.into_raw(), w, h),
rgb,
},
alpha: None,
})
}
}
}
fn flatten_or_drop(
data: &[u8],
width: u32,
height: u32,
mode: AlphaBackground,
colored: bool,
) -> NormalizedInput {
if mode != AlphaBackground::None && crate::alpha::has_transparency(data) {
let stats = crate::alpha::content_stats(data);
return flatten(data, width, height, mode, colored, &stats);
}
let mut luma = Vec::with_capacity(data.len() / 4);
let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
for px in data.as_chunks::<4>().0 {
luma.push(bt601(px[0], px[1], px[2]));
rgb.extend_from_slice(&px[..3]);
}
NormalizedInput {
planes: SourcePlanes {
luma: LumaImage::new(luma, width, height),
rgb: Some(rgb),
},
alpha: None,
}
}
fn flatten(
data: &[u8],
width: u32,
height: u32,
mode: AlphaBackground,
colored: bool,
stats: &crate::alpha::ContentStats,
) -> NormalizedInput {
let bg = match mode {
AlphaBackground::Auto => crate::alpha::auto_background(stats.content_luma),
AlphaBackground::White | AlphaBackground::None => [255; 3],
AlphaBackground::Black => [0; 3],
AlphaBackground::Custom(custom) => custom,
};
let pixels = data.len() / 4;
let mut luma = Vec::with_capacity(pixels);
let mut rgb = colored.then(|| Vec::with_capacity(pixels * 3));
let mut fg_luma = Vec::with_capacity(pixels);
let mut alpha_plane = Vec::with_capacity(pixels);
for px in data.as_chunks::<4>().0 {
let a = px[3];
let (r, g, b) = (
crate::alpha::composite(px[0], bg[0], a),
crate::alpha::composite(px[1], bg[1], a),
crate::alpha::composite(px[2], bg[2], a),
);
luma.push(bt601(r, g, b));
if let Some(rgb) = rgb.as_mut() {
rgb.extend_from_slice(&[r, g, b]);
}
fg_luma.push(bt601(px[0], px[1], px[2]));
alpha_plane.push(a);
}
let context =
crate::alpha::AlphaContext::new(alpha_plane, fg_luma, width, height, stats, mode, bg);
NormalizedInput {
planes: SourcePlanes {
luma: LumaImage::new(luma, width, height),
rgb,
},
alpha: Some(context),
}
}
#[expect(
clippy::cast_precision_loss,
reason = "counts/sums are bounded by Limits::max_pixels (64MP·255 < 2^52) — exact in f64"
)]
#[expect(
clippy::needless_range_loop,
reason = "t is simultaneously the histogram index AND the candidate threshold value"
)]
pub(crate) fn otsu_threshold(img: &LumaImage) -> LumaImage {
let histogram = histogram(img.data());
let total: u64 = img.data().len() as u64;
let weighted_sum: u64 = histogram
.iter()
.enumerate()
.map(|(value, &count)| value as u64 * count)
.sum();
let mut best_threshold = 0usize;
let mut best_variance = -1.0f64;
let mut background_count = 0u64;
let mut background_sum = 0u64;
for t in 0..256 {
background_count += histogram[t];
if background_count == 0 {
continue;
}
let foreground_count = total - background_count;
if foreground_count == 0 {
break;
}
background_sum += t as u64 * histogram[t];
let background_mean = background_sum as f64 / background_count as f64;
let foreground_mean = (weighted_sum - background_sum) as f64 / foreground_count as f64;
let separation = background_mean - foreground_mean;
let variance = background_count as f64 * foreground_count as f64 * separation * separation;
if variance > best_variance {
best_variance = variance;
best_threshold = t;
}
}
let threshold = u8::try_from(best_threshold).unwrap_or(u8::MAX);
let data = img
.data()
.iter()
.map(|&px| if px > threshold { 255 } else { 0 })
.collect();
LumaImage::new(data, img.width(), img.height())
}
pub(crate) fn invert(img: &LumaImage) -> LumaImage {
let data = img.data().iter().map(|&px| 255 - px).collect();
LumaImage::new(data, img.width(), img.height())
}
pub(crate) fn contrast_stretch(img: &LumaImage) -> LumaImage {
let Some((&first, rest)) = img.data().split_first() else {
return img.clone(); };
let (mut min, mut max) = (first, first);
for &px in rest {
min = min.min(px);
max = max.max(px);
}
if min == max {
return img.clone();
}
let range = u32::from(max - min);
let data = img
.data()
.iter()
.map(|&px| {
let stretched = u32::from(px - min) * 255 / range;
u8::try_from(stretched).unwrap_or(u8::MAX)
})
.collect();
LumaImage::new(data, img.width(), img.height())
}
#[expect(
clippy::cast_possible_truncation,
reason = "every u64 here is a pixel index bounded by the u32 source dimensions"
)]
pub(crate) fn downscale_to(img: &LumaImage, max_side: u32) -> LumaImage {
let (w, h) = (img.width(), img.height());
let longest = w.max(h);
if longest <= max_side {
return img.clone();
}
let new_w = (u64::from(w) * u64::from(max_side) / u64::from(longest)).max(1) as u32;
let new_h = (u64::from(h) * u64::from(max_side) / u64::from(longest)).max(1) as u32;
let src = img.data();
let mut data = Vec::with_capacity(new_w as usize * new_h as usize);
for oy in 0..new_h {
let y0 = (u64::from(oy) * u64::from(h) / u64::from(new_h)) as u32;
let y1 =
((u64::from(oy) + 1) * u64::from(h) / u64::from(new_h)).max(u64::from(y0) + 1) as u32;
for ox in 0..new_w {
let x0 = (u64::from(ox) * u64::from(w) / u64::from(new_w)) as u32;
let x1 = ((u64::from(ox) + 1) * u64::from(w) / u64::from(new_w)).max(u64::from(x0) + 1)
as u32;
let mut sum = 0u64;
for y in y0..y1 {
let row = y as usize * w as usize;
for x in x0..x1 {
sum += u64::from(src[row + x as usize]);
}
}
let count = u64::from(y1 - y0) * u64::from(x1 - x0);
data.push(u8::try_from(sum / count).unwrap_or(u8::MAX));
}
}
LumaImage::new(data, new_w, new_h)
}
pub(crate) fn contrast_boost(img: &LumaImage, contrast: f32, brightness: f32) -> LumaImage {
let data = img
.data()
.iter()
.map(|&px| {
let adjusted = ((f32::from(px) * brightness) - 128.0) * contrast + 128.0;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0.0..=255.0 on the previous line"
)]
{
adjusted.clamp(0.0, 255.0) as u8
}
})
.collect();
LumaImage::new(data, img.width(), img.height())
}
pub(crate) fn min_filter(img: &LumaImage, k: u32) -> LumaImage {
morph_filter(img, k, MorphPick::Min)
}
pub(crate) fn max_filter(img: &LumaImage, k: u32) -> LumaImage {
morph_filter(img, k, MorphPick::Max)
}
#[derive(Clone, Copy)]
enum MorphPick {
Min,
Max,
}
impl MorphPick {
#[inline]
fn dominates(self, candidate: u8, incumbent: u8) -> bool {
match self {
Self::Min => candidate <= incumbent,
Self::Max => candidate >= incumbent,
}
}
}
fn windowed_extremum_strided(
src: &[u8],
n: usize,
stride: usize,
r: usize,
pick: MorphPick,
deque: &mut Vec<usize>,
out: &mut [u8],
) {
deque.clear();
let mut head = 0usize;
for j in 0..=r.min(n - 1) {
let v = src[j * stride];
while deque.len() > head && pick.dominates(v, src[deque[deque.len() - 1] * stride]) {
deque.pop();
}
deque.push(j);
}
for i in 0..n {
let hi = (i + r).min(n - 1);
if i > 0 {
let prev_hi = (i - 1 + r).min(n - 1);
for j in (prev_hi + 1)..=hi {
let v = src[j * stride];
while deque.len() > head && pick.dominates(v, src[deque[deque.len() - 1] * stride])
{
deque.pop();
}
deque.push(j);
}
}
let lo = i.saturating_sub(r);
while deque[head] < lo {
head += 1;
}
out[i * stride] = src[deque[head] * stride];
}
}
fn morph_filter(img: &LumaImage, k: u32, pick: MorphPick) -> LumaImage {
let r = ((k.max(3) | 1) / 2) as usize; let (w, h) = (img.width() as usize, img.height() as usize);
let (rx, ry) = (r.min(w.saturating_sub(1)), r.min(h.saturating_sub(1)));
if rx == 0 && ry == 0 {
return img.clone();
}
let src = img.data();
let mut deque: Vec<usize> = Vec::with_capacity(2 * r + 2);
let mut horiz = vec![0u8; w * h];
for y in 0..h {
let row = &src[y * w..(y + 1) * w];
let out = &mut horiz[y * w..(y + 1) * w];
windowed_extremum_strided(row, w, 1, rx, pick, &mut deque, out);
}
let mut data = vec![0u8; w * h];
for x in 0..w {
windowed_extremum_strided(&horiz[x..], h, w, ry, pick, &mut deque, &mut data[x..]);
}
#[expect(
clippy::cast_possible_truncation,
reason = "w/h come from the source image's u32 dimensions"
)]
LumaImage::new(data, w as u32, h as u32)
}
pub(crate) fn gaussian_blur(img: &LumaImage, sigma: f32) -> LumaImage {
let Some(buffer) = image::ImageBuffer::<image::Luma<u8>, _>::from_raw(
img.width(),
img.height(),
img.data().to_vec(),
) else {
return img.clone();
};
let blurred = image::imageops::blur(&buffer, sigma);
let (w, h) = (blurred.width(), blurred.height());
LumaImage::new(blurred.into_raw(), w, h)
}
fn histogram(data: &[u8]) -> [u64; 256] {
let mut lanes = [[0u64; 256]; 4];
let (quads, rest) = data.as_chunks::<4>();
for quad in quads {
for (lane, &px) in lanes.iter_mut().zip(quad) {
lane[usize::from(px)] += 1;
}
}
for &px in rest {
lanes[0][usize::from(px)] += 1;
}
let mut histogram = [0u64; 256];
for lane in &lanes {
for (count, own) in histogram.iter_mut().zip(lane) {
*count += own;
}
}
histogram
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::input::{ImageInput, Limits};
fn luma(data: &[u8], w: u32, h: u32) -> LumaImage {
LumaImage::new(data.to_vec(), w, h)
}
#[test]
fn otsu_splits_a_bimodal_image_exactly() {
let img = luma(&[10, 10, 200, 200], 2, 2);
let out = otsu_threshold(&img);
assert_eq!(out.data(), &[0, 0, 255, 255]);
}
#[test]
fn min_filter_grows_dark_pixel_to_exact_kernel_block() {
let mut data = vec![255u8; 25];
data[12] = 0;
let out = min_filter(&luma(&data, 5, 5), 3);
let mut want = [255u8; 25];
for y in 1..=3 {
for x in 1..=3 {
want[y * 5 + x] = 0;
}
}
assert_eq!(out.data(), &want[..]);
}
#[test]
fn max_filter_is_the_exact_mirror_on_inverted_input() {
let mut data = vec![0u8; 25];
data[12] = 255;
let out = max_filter(&luma(&data, 5, 5), 3);
let mut want = [0u8; 25];
for y in 1..=3 {
for x in 1..=3 {
want[y * 5 + x] = 255;
}
}
assert_eq!(out.data(), &want[..]);
}
#[test]
fn morph_filter_runs_the_vertical_pass_on_single_column_images() {
let out = min_filter(&luma(&[200, 5, 200], 1, 3), 3);
assert_eq!(out.data(), &[5, 5, 5]);
let out = min_filter(&luma(&[42], 1, 1), 9);
assert_eq!(out.data(), &[42]);
}
#[test]
fn morph_filter_clamps_kernel_to_image_and_bumps_even_k() {
let mut data = vec![255u8; 9];
data[0] = 7;
let out = min_filter(&luma(&data, 3, 3), 4);
assert!(out.data().iter().all(|&p| p == 7), "{:?}", out.data());
let single = min_filter(&luma(&[9, 255], 2, 1), 1);
assert_eq!(single.data(), &[9, 9]);
}
fn morph_naive(img: &LumaImage, k: u32, pick: fn(u8, u8) -> u8) -> Vec<u8> {
let r = ((k.max(3) | 1) / 2) as usize;
let (w, h) = (img.width() as usize, img.height() as usize);
let (rx, ry) = (r.min(w.saturating_sub(1)), r.min(h.saturating_sub(1)));
if rx == 0 && ry == 0 {
return img.data().to_vec();
}
let src = img.data();
let mut horiz = vec![0u8; w * h];
for y in 0..h {
let row = &src[y * w..(y + 1) * w];
for x in 0..w {
let lo = x.saturating_sub(rx);
let hi = (x + rx).min(w - 1);
horiz[y * w + x] = row[lo..=hi].iter().copied().fold(row[x], pick);
}
}
let mut data = vec![0u8; w * h];
for y in 0..h {
let lo = y.saturating_sub(ry);
let hi = (y + ry).min(h - 1);
for x in 0..w {
let mut acc = horiz[lo * w + x];
for row in (lo + 1)..=hi {
acc = pick(acc, horiz[row * w + x]);
}
data[y * w + x] = acc;
}
}
data
}
#[test]
fn morph_deque_matches_naive_fold_exhaustively() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = |bound: u32| -> u32 {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as u32 % bound
};
for _ in 0..240 {
let w = 1 + next(40);
let h = 1 + next(40);
let k = 1 + next(23); #[expect(clippy::cast_possible_truncation, reason = "next(256) ∈ 0..256")]
let data: Vec<u8> = (0..w * h).map(|_| next(256) as u8).collect();
let img = luma(&data, w, h);
assert_eq!(
min_filter(&img, k).data(),
&morph_naive(&img, k, u8::min)[..],
"MIN mismatch w={w} h={h} k={k}"
);
assert_eq!(
max_filter(&img, k).data(),
&morph_naive(&img, k, u8::max)[..],
"MAX mismatch w={w} h={h} k={k}"
);
}
}
#[test]
fn otsu_flat_image_maps_to_white() {
let img = luma(&[128; 9], 3, 3);
let out = otsu_threshold(&img);
assert_eq!(out.data(), &[255; 9]);
}
#[test]
fn invert_is_exact() {
let img = luma(&[0, 128, 255], 3, 1);
let out = invert(&img);
assert_eq!(out.data(), &[255, 127, 0]);
}
#[test]
fn contrast_stretch_min_max_full_range() {
let img = luma(&[100, 150, 125], 3, 1);
let out = contrast_stretch(&img);
assert_eq!(out.data(), &[0, 255, 127]);
}
#[test]
fn contrast_stretch_flat_image_unchanged() {
let img = luma(&[7, 7, 7, 7], 2, 2);
let out = contrast_stretch(&img);
assert_eq!(out.data(), &[7, 7, 7, 7]);
}
#[test]
fn downscale_averages_blocks_exactly() {
#[rustfmt::skip]
let img = luma(&[
0, 0, 40, 40,
0, 0, 40, 40,
200, 200, 100, 100,
200, 200, 100, 100,
], 4, 4);
let out = downscale_to(&img, 2);
assert_eq!((out.width(), out.height()), (2, 2));
assert_eq!(out.data(), &[0, 40, 200, 100]);
}
#[test]
fn downscale_noop_when_already_small() {
let img = luma(&[1, 2, 3, 4], 2, 2);
let out = downscale_to(&img, 512);
assert_eq!(out.data(), img.data());
assert_eq!((out.width(), out.height()), (2, 2));
}
#[test]
fn contrast_boost_matches_v02_semantics() {
let img = luma(&[100, 200, 128], 3, 1);
let out = contrast_boost(&img, 2.0, 1.0);
assert_eq!(out.data(), &[72, 255, 128]);
}
#[test]
fn contrast_boost_brightness_applies_before_contrast() {
let img = luma(&[100], 1, 1);
let out = contrast_boost(&img, 2.0, 1.1);
assert_eq!(out.data(), &[92]);
}
#[test]
fn gaussian_blur_spreads_an_impulse_deterministically() {
let mut data = vec![0u8; 25];
data[12] = 255;
let img = luma(&data, 5, 5);
let a = gaussian_blur(&img, 1.0);
let b = gaussian_blur(&img, 1.0);
assert_eq!(a.data(), b.data(), "blur must be deterministic");
assert!(a.data()[12] < 255, "center spread out");
assert!(
a.data()[11] > 0 && a.data()[7] > 0,
"neighbors received mass"
);
assert_eq!((a.width(), a.height()), (5, 5));
}
#[test]
fn rgba_source_extracts_channels() {
let rgba = [255u8, 0, 0, 255, 0, 255, 0, 255];
let planes = normalize(&ImageInput::rgba8(&rgba, 2, 1), &Limits::default()).unwrap();
let r = planes.channel(Channel::R).expect("rgb retained");
assert_eq!(r.data(), &[255, 0]);
let g = planes.channel(Channel::G).expect("rgb retained");
assert_eq!(g.data(), &[0, 255]);
}
#[test]
fn encoded_color_source_extracts_channels_lazily() {
let mut img = image::RgbImage::new(2, 1);
img.put_pixel(0, 0, image::Rgb([0, 0, 255]));
img.put_pixel(1, 0, image::Rgb([255, 0, 0]));
let mut buf = Vec::new();
image::DynamicImage::ImageRgb8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
let planes = normalize(&ImageInput::encoded(&buf), &Limits::default()).unwrap();
let b = planes.channel(Channel::B).expect("color png has channels");
assert_eq!(b.data(), &[255, 0]);
}
#[test]
fn luma_source_has_no_channels() {
let data = [0u8, 255];
let planes = normalize(&ImageInput::luma8(&data, 2, 1), &Limits::default()).unwrap();
assert!(planes.channel(Channel::R).is_none());
assert_eq!(planes.luma.data(), &[0, 255]);
}
#[test]
fn otsu_unbalanced_classes_pin_the_variance_argmax() {
#[rustfmt::skip]
let img = luma(&[
40, 40, 40, 40,
40, 40, 40, 40,
120, 120, 120, 120,
200, 200, 200, 200,
], 4, 4);
let out = otsu_threshold(&img);
let want = [
0u8, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
];
assert_eq!(out.data(), &want[..]);
}
#[test]
fn otsu_variance_tie_keeps_the_lower_threshold() {
#[rustfmt::skip]
let img = luma(&[
40, 40, 40, 40,
40, 40, 120, 120,
120, 120, 200, 200,
200, 200, 200, 200,
], 4, 4);
let out = otsu_threshold(&img);
let want = [
0u8, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
assert_eq!(out.data(), &want[..]);
}
#[test]
fn otsu_uniform_zero_image_maps_to_black() {
let img = luma(&[0; 9], 3, 3);
let out = otsu_threshold(&img);
assert_eq!(out.data(), &[0; 9]);
}
#[test]
fn min_filter_closes_a_one_pixel_gap_and_dilates_the_dark_bar() {
let mut data = [255u8; 64];
data[3 * 8..4 * 8].copy_from_slice(&[255, 0, 0, 0, 255, 0, 0, 255]);
let out = min_filter(&luma(&data, 8, 8), 3);
let mut want = [255u8; 64];
for row in 2..=4 {
for col in 0..8 {
want[row * 8 + col] = 0;
}
}
assert_eq!(out.data(), &want[..]);
}
#[test]
fn max_filter_mirrors_the_gap_close_on_light_structures() {
let mut data = [0u8; 64];
data[3 * 8..4 * 8].copy_from_slice(&[0, 255, 255, 255, 0, 255, 255, 0]);
let out = max_filter(&luma(&data, 8, 8), 3);
let mut want = [0u8; 64];
for row in 2..=4 {
for col in 0..8 {
want[row * 8 + col] = 255;
}
}
assert_eq!(out.data(), &want[..]);
}
#[test]
fn morph_filter_on_a_uniform_field_is_identity() {
let img = luma(&[128u8; 64], 8, 8);
assert_eq!(min_filter(&img, 3).data(), img.data());
assert_eq!(max_filter(&img, 5).data(), img.data());
}
#[test]
fn downscale_odd_dimension_uses_uneven_boxes() {
#[rustfmt::skip]
let img = luma(&[
40, 40, 100, 100, 100,
40, 40, 100, 100, 100,
200, 200, 130, 130, 130,
200, 200, 130, 130, 130,
200, 200, 130, 130, 130,
], 5, 5);
let out = downscale_to(&img, 2);
assert_eq!((out.width(), out.height()), (2, 2));
assert_eq!(out.data(), &[40, 100, 200, 130]);
}
#[test]
fn downscale_truncates_the_box_mean() {
let img = luma(&[10, 20, 30, 41], 2, 2);
let out = downscale_to(&img, 1);
assert_eq!((out.width(), out.height()), (1, 1));
assert_eq!(out.data(), &[25]);
}
#[test]
fn has_color_reflects_the_source_kind() {
let rgba = [10u8, 20, 30, 255];
let planes = normalize(&ImageInput::rgba8(&rgba, 1, 1), &Limits::default()).unwrap();
assert!(planes.has_color(), "an rgba source retains color planes");
let planes = normalize(&ImageInput::luma8(&[7], 1, 1), &Limits::default()).unwrap();
assert!(!planes.has_color(), "a luma source has no color planes");
}
#[test]
fn otsu_two_pixel_split_needs_the_negative_variance_init() {
let img = luma(&[100, 101], 2, 1);
let out = otsu_threshold(&img);
assert_eq!(out.data(), &[0, 255]);
}
#[test]
fn otsu_argmax_weighs_class_balance_times_separation_squared() {
let img = luma(&[0, 0, 5, 5, 5, 20], 6, 1);
let out = otsu_threshold(&img);
assert_eq!(out.data(), &[0, 0, 0, 0, 0, 255]);
}
#[test]
fn windowed_extremum_oversized_radius_clamps_at_the_seed() {
let src = [7u8, 200, 3];
let mut deque = Vec::new();
let mut out = [0u8; 3];
windowed_extremum_strided(&src, 3, 1, 5, MorphPick::Min, &mut deque, &mut out);
assert_eq!(out, [3, 3, 3]);
windowed_extremum_strided(&src, 3, 1, 5, MorphPick::Max, &mut deque, &mut out);
assert_eq!(out, [200, 200, 200]);
}
#[test]
fn windowed_extremum_zero_radius_is_identity() {
let src = [9u8, 1, 5, 5, 2];
let mut deque = Vec::new();
let mut out = [0u8; 5];
windowed_extremum_strided(&src, 5, 1, 0, MorphPick::Min, &mut deque, &mut out);
assert_eq!(out, [9, 1, 5, 5, 2]);
windowed_extremum_strided(&src, 5, 1, 0, MorphPick::Max, &mut deque, &mut out);
assert_eq!(out, [9, 1, 5, 5, 2]);
}
#[test]
fn windowed_extremum_strided_slides_with_a_real_stride() {
let src = [50u8, 255, 40, 255, 60, 255, 45, 255, 10];
let mut deque = Vec::new();
let mut out = [0u8; 9];
windowed_extremum_strided(&src, 5, 2, 1, MorphPick::Min, &mut deque, &mut out);
assert_eq!(
[out[0], out[2], out[4], out[6], out[8]],
[40, 40, 40, 10, 10]
);
windowed_extremum_strided(&src, 5, 2, 1, MorphPick::Max, &mut deque, &mut out);
assert_eq!(
[out[0], out[2], out[4], out[6], out[8]],
[50, 60, 60, 60, 45]
);
}
#[test]
fn raw_rgba_flattens_only_transparency_under_a_flattening_mode() {
let scan = |data: &[u8], mode| {
normalize_with(&ImageInput::rgba8(data, 2, 1), &Limits::default(), mode).unwrap()
};
let straight = [bt601(10, 20, 30), bt601(200, 100, 50)];
let opaque = scan(&[10, 20, 30, 255, 200, 100, 50, 255], AlphaBackground::Auto);
assert!(
opaque.alpha.is_none(),
"an opaque frame keeps no alpha context"
);
assert_eq!(opaque.planes.luma.data(), straight);
let transparent = [10, 20, 30, 0, 200, 100, 50, 255];
let kept = scan(&transparent, AlphaBackground::None);
assert!(kept.alpha.is_none(), "`none` never flattens");
assert_eq!(kept.planes.luma.data(), straight);
let flattened = scan(&transparent, AlphaBackground::White);
assert!(
flattened.alpha.is_some(),
"`white` flattens a transparent frame"
);
assert_eq!(flattened.planes.luma.data(), [255, straight[1]]);
}
#[test]
fn flattened_rgba_retains_exact_rgb_capacity_and_pixels() {
let rgba = [10, 20, 30, 128].repeat(17);
let normalized = normalize_with(
&ImageInput::rgba8(&rgba, 17, 1),
&Limits::default(),
AlphaBackground::White,
)
.unwrap();
let rgb = normalized.planes.rgb.as_ref().unwrap();
assert_eq!(rgb.len(), 51);
assert_eq!(rgb.capacity(), 51);
assert_eq!(rgb.as_slice(), [132, 137, 142].repeat(17));
assert_eq!(normalized.planes.luma.width(), 17);
assert_eq!(normalized.planes.luma.height(), 1);
assert_eq!(normalized.planes.luma.data(), [136; 17]);
let alpha = normalized.alpha.unwrap().into_report(false, None);
assert_eq!(alpha.mode, crate::report::AlphaMode::White);
assert_eq!(alpha.background, "white");
assert_eq!(alpha.coverage.to_bits(), 1.0_f32.to_bits());
assert_eq!(alpha.content_luma, 18);
}
#[test]
fn the_histogram_counts_every_pixel_once_at_any_length() {
for len in 0..=13_usize {
let data: Vec<u8> = (0..len)
.map(|i| [7, 7, 200, 7, 0, 255, 200][i % 7])
.collect();
let mut want = [0u64; 256];
for &px in &data {
want[usize::from(px)] += 1;
}
assert_eq!(histogram(&data), want, "{len} pixels");
}
}
}