mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 18:04:15 +00:00
Merge origin/main into feat/cutover-remaining-codecs
This commit is contained in:
@@ -5,13 +5,13 @@ use super::params::{Method, Mode, TraceParams};
|
||||
use super::pipeline::TracedPath;
|
||||
#[cfg(test)]
|
||||
use super::pipeline::{bw_tones, left_out};
|
||||
#[cfg(test)]
|
||||
use super::quantize;
|
||||
use super::raster::{Raster, TraceError};
|
||||
use super::{
|
||||
AtomicUsize, Crack, Loop, Ordering, PathData, Quantized, TRANSPARENT, TracedGradient, TracedShape, centerline, contour, fit, logo, shapes,
|
||||
trace_mask,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use super::{denoise, quantize};
|
||||
|
||||
/// What tracing one colour layer needs.
|
||||
pub(crate) struct Layers<'a> {
|
||||
@@ -1005,7 +1005,10 @@ impl Layers<'_> {
|
||||
pub(crate) fn shift_probe(img: &Raster, params: &TraceParams) -> Vec<[f64; 4]> {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let mut q = quantize(img, params);
|
||||
denoise(&mut q.labels, w, h, params.noise as usize);
|
||||
let labs = super::quantize::palette_labs(&q.palette);
|
||||
let source =
|
||||
super::quantize::Source { labs: &labs, rgba: &img.rgba, blended: &[], gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) };
|
||||
super::quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &[], Some(&source));
|
||||
let n = q.palette.len();
|
||||
let rank: Vec<usize> = (0..n).collect();
|
||||
let gradients = vec![None; n];
|
||||
|
||||
@@ -82,8 +82,10 @@ pub struct TraceParams {
|
||||
pub paths: f64,
|
||||
/// Corners 0–100: higher keeps more corners.
|
||||
pub corners: f64,
|
||||
/// Noise: areas smaller than this many pixels are ignored. (Flat Logo mode: areas smaller than
|
||||
/// `noise / 10` pixels of the source image.)
|
||||
/// Noise: areas smaller than this many pixels are ignored: each joins the color it shares the
|
||||
/// longest border with, or, when that color is far from its own, the color beside it nearest
|
||||
/// its source pixels. (Flat Logo mode: areas smaller than `noise / 10` pixels of the source
|
||||
/// image.)
|
||||
pub noise: u32,
|
||||
pub method: Method,
|
||||
/// Ignore Color: drop the areas of one colour (no background shape): white, unless
|
||||
@@ -244,10 +246,10 @@ pub fn preset(name: &str) -> Option<TraceParams> {
|
||||
"high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping),
|
||||
"low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping),
|
||||
"3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting),
|
||||
"6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting),
|
||||
"16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting),
|
||||
"6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting),
|
||||
"16 colors" => color(16, 50.0, 50.0, 8, Method::Abutting),
|
||||
"shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d },
|
||||
"black and white logo" => bw(128, 50.0, 75.0, 25, true),
|
||||
"black and white logo" => bw(128, 50.0, 75.0, 5, true),
|
||||
"sketched art" => bw(150, 50.0, 50.0, 20, false),
|
||||
"silhouettes" => bw(200, 50.0, 50.0, 90, false),
|
||||
"line art" => bw(128, 50.0, 75.0, 20, false),
|
||||
|
||||
@@ -250,9 +250,11 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
|
||||
let (mut q, rare) = quantize::quantize_keeping(without.as_ref().unwrap_or(img), params);
|
||||
go_on()?;
|
||||
// The semi-transparent edge of a cut-out image traces as the color beside it.
|
||||
if matches!(params.mode, Mode::Color | Mode::Grayscale) {
|
||||
quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale);
|
||||
}
|
||||
let blended = if matches!(params.mode, Mode::Color | Mode::Grayscale) {
|
||||
quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
drop(without);
|
||||
// Each gradient is a palette entry of its own (its colour: the gradient's middle).
|
||||
let mut gradients: Vec<Option<TracedGradient>> = vec![None; q.palette.len()];
|
||||
@@ -270,7 +272,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
|
||||
drop(grays);
|
||||
// Noise clears specks, not the regions of a rare colour Automatic kept on purpose.
|
||||
let keep: Vec<bool> = q.palette.iter().map(|c| rare.contains(c)).collect();
|
||||
quantize::denoise_keeping(&mut q.labels, w, h, params.noise as usize, &keep);
|
||||
// A speck far from the color around it joins the color beside it nearest its own pixels.
|
||||
let labs = quantize::palette_labs(&q.palette);
|
||||
let source =
|
||||
quantize::Source { labs: &labs, rgba: &img.rgba, blended: &blended, gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) };
|
||||
quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &keep, Some(&source));
|
||||
drop(blended);
|
||||
go_on()?;
|
||||
// Ignore Color, background only: the labels traced, with the ignored color's areas that reach
|
||||
// the edge left out. Its other areas are traced with the rest. Edges are still placed by
|
||||
|
||||
@@ -11,7 +11,9 @@ mod rare;
|
||||
use cut_edge::{choosing_pixels, compact, settled, settled_wide, settles_wide};
|
||||
pub(crate) use cut_edge::{continuous_tone, settle_cut_edges};
|
||||
pub use denoise::denoise;
|
||||
#[cfg(test)]
|
||||
pub(crate) use denoise::denoise_keeping;
|
||||
pub(crate) use denoise::{Source, denoise_nearest};
|
||||
pub use palette::FULL_TONE_MAX;
|
||||
use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library};
|
||||
#[cfg(test)]
|
||||
@@ -296,6 +298,11 @@ fn oklab(c: [f64; 3]) -> [f64; 3] {
|
||||
]
|
||||
}
|
||||
|
||||
/// [`oklab`] of each palette color.
|
||||
pub(crate) fn palette_labs(palette: &[[u8; 3]]) -> Vec<[f64; 3]> {
|
||||
palette.iter().map(|c| oklab(c.map(f64::from))).collect()
|
||||
}
|
||||
|
||||
/// [`oklab`] of an sRGB colour, for the tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] {
|
||||
|
||||
@@ -594,12 +594,15 @@ pub(super) fn compact(mut labels: Vec<u16>, palette: Vec<[u8; 3]>) -> Quantized
|
||||
/// when one of the fully opaque pixels it reaches has it, or when its color is a blend of none of
|
||||
/// them, as with a thin semi-transparent outline of another color. Pixels outside the image do not
|
||||
/// count as transparent. With `gray` (Grayscale), a pixel's color is its gray (see [`luma`]).
|
||||
pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) {
|
||||
/// Returns which cut-edge pixels are a blend of the color of a fully opaque pixel they reach (see
|
||||
/// [`edge_blend_of`]), whether or not they took that color (empty when `q` does not match `img`).
|
||||
pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> Vec<bool> {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let px = img.rgba.as_chunks::<4>().0;
|
||||
if q.labels.len() != w * h || px.len() != w * h {
|
||||
return;
|
||||
return Vec::new();
|
||||
}
|
||||
let mut blended = vec![false; w * h];
|
||||
let color = |p: &[u8; 4]| if gray { [luma(*p); 3] } else { [p[0], p[1], p[2]] };
|
||||
let edge = cut_edge(img);
|
||||
let mut changed = false;
|
||||
@@ -627,6 +630,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) {
|
||||
}
|
||||
}
|
||||
});
|
||||
blended[i] = !near.is_empty();
|
||||
if keep || near.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -641,6 +645,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) {
|
||||
if changed {
|
||||
*q = compact(std::mem::take(&mut q.labels), std::mem::take(&mut q.palette));
|
||||
}
|
||||
blended
|
||||
}
|
||||
|
||||
/// Calls `visit` with the index of each fully opaque pixel of `img` within two pixels of the pixel
|
||||
|
||||
@@ -4,20 +4,59 @@ use super::rare::RARE_ISLAND;
|
||||
/// Merge whole 4-connected regions, smallest first, into their most common neighbouring label.
|
||||
/// The merge order does not depend on `min_area`: a higher threshold continues the same sequence
|
||||
/// instead of splitting a region already merged at a lower threshold. Transparency is a barrier.
|
||||
/// It reads only the labels. A trace also reads the image, and a speck far from the color around
|
||||
/// it joins the color beside it nearest its pixels instead.
|
||||
pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) {
|
||||
denoise_keeping(labels, w, h, min_area, &[]);
|
||||
}
|
||||
|
||||
/// How far apart (Oklab × 100) a small region's color and the color it shares the longest
|
||||
/// border with must be before it merges into the color beside it that is nearest its source
|
||||
/// pixels instead (among those with at least [`NEAREST_BORDER`] of the longest border): a dark
|
||||
/// speck on the edge of a light area joins the dark outline beside it, not the light area.
|
||||
pub(crate) const NEAREST_APART: f64 = 10.0;
|
||||
|
||||
/// See [`NEAREST_APART`].
|
||||
pub(crate) const NEAREST_BORDER: f64 = 0.1;
|
||||
|
||||
/// The fewest pixels a region needs for [`NEAREST_APART`] to apply when two or more colors tie
|
||||
/// for its longest border. Such a lone pixel merges by border alone: on an anti-aliased corner it
|
||||
/// holds a mix of the colors on both sides, and joining the nearer one can cut the corner off a
|
||||
/// shape.
|
||||
pub(crate) const NEAREST_PIXELS: u32 = 2;
|
||||
|
||||
/// The colors [`denoise_nearest`] compares a small region with.
|
||||
pub(crate) struct Source<'a> {
|
||||
/// Each label's color in Oklab × 100 ([`super::palette_labs`]).
|
||||
pub labs: &'a [[f64; 3]],
|
||||
/// The prepared image the labels were made from, 4 bytes a pixel.
|
||||
pub rgba: &'a [u8],
|
||||
/// The pixels along a cut edge that [`super::settle_cut_edges`] finds to be the color of an opaque pixel beside
|
||||
/// them blended with the transparent background. They are not read.
|
||||
pub blended: &'a [bool],
|
||||
/// Whether the labels are grays (Grayscale, Black and White): the pixels are compared as their gray
|
||||
/// ([`super::luma`]).
|
||||
pub gray: bool,
|
||||
}
|
||||
|
||||
/// [`denoise`], except that a region of a label `keep` marks (a rare colour kept on purpose, see
|
||||
/// [`rare_colours`]) that is at least [`RARE_ISLAND`] pixels stays whatever `min_area` is: Noise
|
||||
/// clears specks, not a colour's only regions. Smaller regions of it go as any other.
|
||||
pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) {
|
||||
denoise_nearest(labels, w, h, min_area, keep, None);
|
||||
}
|
||||
|
||||
/// [`denoise_keeping`]; with `source`, a region below `min_area` whose color is at least
|
||||
/// [`NEAREST_APART`] from the color it shares the longest border with merges into the color
|
||||
/// beside it nearest its source pixels, averaged, among those sharing at least [`NEAREST_BORDER`]
|
||||
/// of the longest border ([`NEAREST_PIXELS`] limits this for a single pixel). Every region below
|
||||
/// `min_area` still goes.
|
||||
pub(crate) fn denoise_nearest(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool], source: Option<&Source>) {
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
// Every index below is a `u32`, so a pixel costs 8 bytes and a region 18 instead of a `Vec<usize>` per region. An image
|
||||
// of `u32::MAX` pixels or more (far above the decoder's cap) is left as it is.
|
||||
const NONE: u32 = u32::MAX;
|
||||
if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize {
|
||||
return;
|
||||
}
|
||||
@@ -66,14 +105,8 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area:
|
||||
colour.push(label);
|
||||
parent.push(id);
|
||||
}
|
||||
fn find(parent: &mut [u32], mut a: u32) -> u32 {
|
||||
while parent[a as usize] != a {
|
||||
let up = parent[parent[a as usize] as usize];
|
||||
parent[a as usize] = up;
|
||||
a = up;
|
||||
}
|
||||
a
|
||||
}
|
||||
// Only when it can be read: the labels' colors and the source pixels must cover every label and every pixel.
|
||||
let source = source.filter(|s| colour.iter().all(|&c| (c as usize) < s.labs.len()) && labels.len().checked_mul(4) == Some(s.rgba.len()));
|
||||
// Only regions below `min_area` are ever taken from the queue; a larger one ends the loop.
|
||||
let mut pending: BinaryHeap<_> =
|
||||
(0..size.len() as u32).filter(|&id| (size[id as usize] as usize) < min_area).map(|id| Reverse((size[id as usize], id))).collect();
|
||||
@@ -110,9 +143,24 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area:
|
||||
by_colour.clear();
|
||||
by_colour.extend(borders.iter().map(|&(other, border)| (colour[other as usize], border)));
|
||||
merge_counts(&mut by_colour);
|
||||
let Some(&(chosen, _)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else {
|
||||
let Some(&(mut chosen, longest)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else {
|
||||
continue; // an opaque island surrounded only by transparency stays intact
|
||||
};
|
||||
if let Some(source) = source
|
||||
&& (area >= NEAREST_PIXELS || by_colour.iter().filter(|&&(_, border)| border == longest).count() == 1)
|
||||
&& let Some(own) = source.labs.get(colour[id as usize] as usize)
|
||||
&& distance(own, source.labs.get(chosen as usize)) >= NEAREST_APART
|
||||
&& let Some(mean) = mean_lab(head[id as usize], &next, source)
|
||||
{
|
||||
let to = |c: u16| distance(&mean, source.labs.get(c as usize));
|
||||
if let Some(&(nearest, _)) = by_colour
|
||||
.iter()
|
||||
.filter(|&&(_, border)| border as f64 >= NEAREST_BORDER * longest as f64)
|
||||
.min_by(|a, b| to(a.0).total_cmp(&to(b.0)).then(b.1.cmp(&a.1)))
|
||||
{
|
||||
chosen = nearest;
|
||||
}
|
||||
}
|
||||
// All adjacent regions of the chosen colour become connected by this merge. Absorb
|
||||
// them together, keeping the largest one as the survivor.
|
||||
let Some(target) = borders
|
||||
@@ -143,6 +191,46 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area:
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a pixel list, and the region of a transparent pixel.
|
||||
const NONE: u32 = u32::MAX;
|
||||
|
||||
/// The root of `a` in the union-find `parent`, halving the paths on the way.
|
||||
fn find(parent: &mut [u32], mut a: u32) -> u32 {
|
||||
while parent[a as usize] != a {
|
||||
let up = parent[parent[a as usize] as usize];
|
||||
parent[a as usize] = up;
|
||||
a = up;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// The source pixels of the list that starts at `first` (linked through `next`), averaged, in Oklab × 100, read as
|
||||
/// `source` says, leaving out the blended cut-edge pixels. `None` when every pixel is one of them.
|
||||
fn mean_lab(first: u32, next: &[u32], source: &Source) -> Option<[f64; 3]> {
|
||||
let (mut sum, mut n) = ([0.0f64; 3], 0u32);
|
||||
let mut pixel = first;
|
||||
while pixel != NONE {
|
||||
let blended = source.blended.get(pixel as usize).copied().unwrap_or(false);
|
||||
if !blended && let Some(&[r, g, b, a]) = source.rgba.get(pixel as usize * 4..pixel as usize * 4 + 4) {
|
||||
let p = if source.gray { [f64::from(super::luma([r, g, b, a])); 3] } else { [r, g, b].map(f64::from) };
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
pixel = next.get(pixel as usize).copied().unwrap_or(NONE);
|
||||
}
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(super::oklab(sum.map(|s| s / f64::from(n))))
|
||||
}
|
||||
|
||||
/// The distance between two colors in Oklab × 100; infinite when `q` is missing.
|
||||
fn distance(p: &[f64; 3], q: Option<&[f64; 3]>) -> f64 {
|
||||
q.map_or(f64::INFINITY, |q| (0..3).map(|k| (p[k] - q[k]).powi(2)).sum::<f64>().sqrt())
|
||||
}
|
||||
|
||||
/// Sort `(key, count)` pairs and add up the counts of equal keys.
|
||||
fn merge_counts<K: Ord + Copy>(pairs: &mut Vec<(K, usize)>) {
|
||||
pairs.sort_unstable_by_key(|p| p.0);
|
||||
@@ -285,6 +373,185 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A light ground, a dark ink, a tone barely darker than the ground and a dark brown close to the ink.
|
||||
const GROUND_INK_TONE_BROWN: [[u8; 3]; 4] = [[235, 225, 210], [30, 25, 20], [228, 218, 203], [50, 42, 35]];
|
||||
|
||||
/// `labels` denoised at `min_area`, reading the source image that paints each label its palette color.
|
||||
fn denoised_nearest(labels: &[u16], w: usize, h: usize, min_area: usize) -> Vec<u16> {
|
||||
let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN);
|
||||
let rgba: Vec<u8> =
|
||||
labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect();
|
||||
let mut out = labels.to_vec();
|
||||
denoise_nearest(&mut out, w, h, min_area, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false }));
|
||||
out
|
||||
}
|
||||
|
||||
/// A ground with a dark line two pixels wide down column 12 and 13, and a 2 × 2 speck of `speck` at (10, 10) that
|
||||
/// touches the line on one side and the ground on three.
|
||||
fn speck_beside_a_line(speck: u16) -> (Vec<u16>, usize, usize) {
|
||||
let (w, h) = (30, 30);
|
||||
let mut labels = vec![0u16; w * h];
|
||||
for y in 0..h {
|
||||
labels[y * w + 12] = 1;
|
||||
labels[y * w + 13] = 1;
|
||||
}
|
||||
for (x, y) in SPECK {
|
||||
labels[y * w + x] = speck;
|
||||
}
|
||||
(labels, w, h)
|
||||
}
|
||||
|
||||
const SPECK: [(usize, usize); 4] = [(10, 10), (11, 10), (10, 11), (11, 11)];
|
||||
|
||||
/// A dark speck mostly on the light ground but touching a dark line joins the line, the color nearest it, not the
|
||||
/// ground it shares more border with.
|
||||
#[test]
|
||||
fn a_dark_speck_beside_a_dark_line_joins_the_line() {
|
||||
let (labels, w, h) = speck_beside_a_line(3);
|
||||
let out = denoised_nearest(&labels, w, h, 15);
|
||||
for (x, y) in SPECK {
|
||||
assert_eq!(out[y * w + x], 1, "({x}, {y})");
|
||||
}
|
||||
let mut blind = labels.clone();
|
||||
denoise_keeping(&mut blind, w, h, 15, &[]);
|
||||
assert_eq!(blind[10 * w + 10], 0, "by border alone it joins the ground");
|
||||
}
|
||||
|
||||
/// A speck whose color is close to the color it shares the longest border with joins that color, as before,
|
||||
/// even though another color touches it.
|
||||
#[test]
|
||||
fn a_speck_close_to_its_longest_border_color_joins_it() {
|
||||
let (labels, w, h) = speck_beside_a_line(2);
|
||||
let out = denoised_nearest(&labels, w, h, 15);
|
||||
let mut blind = labels.clone();
|
||||
denoise_keeping(&mut blind, w, h, 15, &[]);
|
||||
assert_eq!(out, blind);
|
||||
assert_eq!(out[10 * w + 10], 0);
|
||||
}
|
||||
|
||||
/// A color that touches the speck along less than a tenth of its longest border is not chosen, however near.
|
||||
#[test]
|
||||
fn a_color_with_a_short_border_is_not_chosen() {
|
||||
let (w, h) = (30, 30);
|
||||
let mut labels = vec![0u16; w * h];
|
||||
// A 3 × 3 speck of brown in the ground, and a line of ink 16 pixels long (above Noise) that touches the speck at
|
||||
// one pixel edge.
|
||||
for y in 10..13 {
|
||||
for x in 10..13 {
|
||||
labels[y * w + x] = 3;
|
||||
}
|
||||
}
|
||||
for x in 13..29 {
|
||||
labels[10 * w + x] = 1;
|
||||
}
|
||||
// The brown speck has 11 pixel edges against the ground and 1 against the ink: 1 < 0.1 × 11.
|
||||
let out = denoised_nearest(&labels, w, h, 15);
|
||||
assert_eq!(out[11 * w + 11], 0);
|
||||
assert!(out[10 * w + 13..10 * w + 29].iter().all(|&l| l == 1), "the line stays");
|
||||
}
|
||||
|
||||
/// A lone pixel tied between two colors for its longest border merges by border alone, even when the other
|
||||
/// color is nearer its source pixel.
|
||||
#[test]
|
||||
fn a_lone_pixel_tied_between_colors_merges_by_border() {
|
||||
let (w, h) = (20, 20);
|
||||
// Ground in the top-left, ink everywhere else, and one brown pixel at the corner with two edges on each.
|
||||
let mut labels: Vec<u16> = (0..w * h).map(|i| u16::from(i % w >= 11 || i / w >= 11)).collect();
|
||||
labels[10 * w + 10] = 3;
|
||||
let out = denoised_nearest(&labels, w, h, 5);
|
||||
let mut blind = labels.clone();
|
||||
denoise_keeping(&mut blind, w, h, 5, &[]);
|
||||
assert_eq!(out, blind);
|
||||
assert_eq!(out[10 * w + 10], 0);
|
||||
// With the ground one column wider the pixel has three edges on the ground and one on the ink: no longer tied,
|
||||
// it joins the ink, the color nearest it.
|
||||
for y in 0..11 {
|
||||
labels[y * w + 11] = 0;
|
||||
}
|
||||
let out = denoised_nearest(&labels, w, h, 5);
|
||||
assert_eq!(out[10 * w + 10], 1);
|
||||
}
|
||||
|
||||
/// Every region below Noise still goes: the nearest-color merge only changes where it goes.
|
||||
#[test]
|
||||
fn noise_still_removes_every_region_below_it() {
|
||||
let (w, h) = (60, 50);
|
||||
for seed in 1..6 {
|
||||
let labels = noisy(w, h, 4, 0, seed);
|
||||
for min_area in [2, 3, 5, 8, 15, 25] {
|
||||
let out = denoised_nearest(&labels, w, h, min_area);
|
||||
let mut seen = vec![false; w * h];
|
||||
for start in 0..w * h {
|
||||
if seen[start] {
|
||||
continue;
|
||||
}
|
||||
seen[start] = true;
|
||||
let mut stack = vec![start];
|
||||
let mut count = 0;
|
||||
while let Some(i) = stack.pop() {
|
||||
count += 1;
|
||||
let (x, y) = (i % w, i / w);
|
||||
for j in [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if !seen[j] && out[j] == out[i] {
|
||||
seen[j] = true;
|
||||
stack.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(count >= min_area, "seed {seed}, Noise {min_area}: a region of {count} pixels at {start}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Without colors or a source image for every label and pixel, every region merges as it always did.
|
||||
#[test]
|
||||
fn a_source_that_does_not_cover_the_labels_is_not_read() {
|
||||
let (labels, w, h) = speck_beside_a_line(3);
|
||||
let mut blind = labels.clone();
|
||||
denoise_keeping(&mut blind, w, h, 15, &[]);
|
||||
let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN[..2]);
|
||||
// Every pixel ink: read, the speck would join the line.
|
||||
let rgba: Vec<u8> = (0..w * h).flat_map(|_| [30, 25, 20, 255]).collect();
|
||||
let mut out = labels.clone();
|
||||
denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false }));
|
||||
assert_eq!(out, blind);
|
||||
let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN);
|
||||
let mut out = labels.clone();
|
||||
denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba[4..], blended: &[], gray: false }));
|
||||
assert_eq!(out, blind);
|
||||
let mut out = labels.clone();
|
||||
denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false }));
|
||||
assert_eq!(out[10 * w + 10], 1, "a source that covers them is read");
|
||||
}
|
||||
|
||||
/// A speck made only of cut-edge pixels that are the color beside them blended with the transparent background
|
||||
/// merges by border alone.
|
||||
#[test]
|
||||
fn a_speck_of_blended_cut_edge_pixels_merges_by_border() {
|
||||
let (labels, w, h) = speck_beside_a_line(3);
|
||||
let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN);
|
||||
let rgba: Vec<u8> =
|
||||
labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect();
|
||||
let mut blended = vec![false; w * h];
|
||||
for (x, y) in SPECK {
|
||||
blended[y * w + x] = true;
|
||||
}
|
||||
let mut out = labels.clone();
|
||||
denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false }));
|
||||
let mut blind = labels.clone();
|
||||
denoise_keeping(&mut blind, w, h, 15, &[]);
|
||||
assert_eq!(out, blind);
|
||||
// One pixel that is not such a blend is enough to read it.
|
||||
blended[10 * w + 10] = false;
|
||||
let mut out = labels.clone();
|
||||
denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false }));
|
||||
assert_eq!(out[10 * w + 10], 1);
|
||||
}
|
||||
|
||||
/// A minimum so large that regions keep merging into big ones.
|
||||
#[test]
|
||||
fn compact_denoise_matches_the_reference_with_a_large_min_area() {
|
||||
|
||||
@@ -716,13 +716,35 @@ fn a_cut_out_edge_in_grayscale_ties_by_its_gray() {
|
||||
let t = TRANSPARENT;
|
||||
let q = Quantized { labels: vec![0, 2, 1, t, t, t], palette: vec![[50, 50, 50], [150, 150, 150], [90, 90, 90]] };
|
||||
let mut gray = q.clone();
|
||||
crate::quantize::settle_cut_edges(&mut gray, &img, true);
|
||||
let marked = crate::quantize::settle_cut_edges(&mut gray, &img, true);
|
||||
assert_eq!(gray.palette.get(gray.labels[1] as usize), Some(&[50, 50, 50]));
|
||||
assert_eq!(marked, [false, true, false, false, false, false], "the edge pixel is marked as a blend");
|
||||
let mut color = q;
|
||||
crate::quantize::settle_cut_edges(&mut color, &img, false);
|
||||
assert_eq!(color.palette.get(color.labels[1] as usize), Some(&[150, 150, 150]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_out_edge_pixel_already_of_the_color_beside_it_is_marked_when_a_blend_of_it() {
|
||||
// A semi-transparent dark red edge pixel between opaque red and blue pixels, already labeled red: it keeps red,
|
||||
// and is marked as a blend for Noise. A purple one labeled red is a blend of neither pixel's color alone and is
|
||||
// not marked.
|
||||
for (edge, blend) in [([128, 0, 0, 192], true), ([128, 0, 128, 192], false)] {
|
||||
let img = Raster::from_fn(3, 2, |x, y| match (x, y) {
|
||||
(0, 0) => [255, 0, 0, 255],
|
||||
(1, 0) => edge,
|
||||
(2, 0) => [0, 0, 255, 255],
|
||||
_ => [0, 0, 0, 0],
|
||||
});
|
||||
let t = TRANSPARENT;
|
||||
let q = Quantized { labels: vec![0, 0, 1, t, t, t], palette: vec![[255, 0, 0], [0, 0, 255]] };
|
||||
let mut settled = q.clone();
|
||||
let marked = crate::quantize::settle_cut_edges(&mut settled, &img, false);
|
||||
assert_eq!(settled, q, "{edge:?}");
|
||||
assert_eq!(marked, [false, blend, false, false, false, false], "{edge:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semi_transparent_line_across_a_gap_keeps_its_own_color() {
|
||||
// A light block, a transparent column, then a semi-transparent tan line: the block lies within
|
||||
@@ -761,8 +783,9 @@ fn a_thin_semi_transparent_outline_keeps_its_own_color() {
|
||||
let q = quantize(&img, &TraceParams { mode, colors: 3, ..TraceParams::default() });
|
||||
assert_ne!(q.labels[9 * 60 + 30], q.labels[30 * 60 + 30], "{mode:?}, alpha {alpha}: the outline has a color of its own");
|
||||
let mut settled = q.clone();
|
||||
crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale);
|
||||
let marked = crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale);
|
||||
assert_eq!(settled, q, "{mode:?}, alpha {alpha}");
|
||||
assert!(!marked.contains(&true), "{mode:?}, alpha {alpha}: the outline is no blend of the square");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -899,10 +922,10 @@ fn presets_have_their_paths_corners_and_noise() {
|
||||
("High Fidelity Photo", 50.0, 50.0, 5),
|
||||
("Low Fidelity Photo", 50.0, 50.0, 10),
|
||||
("3 Colors", 50.0, 50.0, 15),
|
||||
("6 Colors", 50.0, 50.0, 15),
|
||||
("16 Colors", 50.0, 50.0, 15),
|
||||
("6 Colors", 50.0, 50.0, 8),
|
||||
("16 Colors", 50.0, 50.0, 8),
|
||||
("Shades of Gray", 50.0, 50.0, 15),
|
||||
("Black and White Logo", 50.0, 75.0, 25),
|
||||
("Black and White Logo", 50.0, 75.0, 5),
|
||||
("Sketched Art", 50.0, 50.0, 20),
|
||||
("Silhouettes", 50.0, 50.0, 90),
|
||||
("Line Art", 50.0, 75.0, 20),
|
||||
@@ -1928,7 +1951,9 @@ fn contour_spread(res: &TraceResult) -> (f64, usize) {
|
||||
|
||||
#[test]
|
||||
fn the_borders_of_a_gradients_bands_follow_its_contours() {
|
||||
let res = trace(&wavy_bands(), &sixteen_colors());
|
||||
// At the Noise this test was written for: at 16 Colors' Noise 8 the 6 levels of noise leave more
|
||||
// small regions along the borders.
|
||||
let res = trace(&wavy_bands(), &TraceParams { noise: 15, ..sixteen_colors() });
|
||||
// The square's sides are edges: it keeps its four corners.
|
||||
let [l, t, r, b] = WAVY_SQUARE;
|
||||
let square = res.paths.iter().find(|p| p.color.iter().all(|&c| c < 40)).expect("the dark square");
|
||||
|
||||
Reference in New Issue
Block a user