M6.7: roto brush segmentation + propagation
Graph-cut segmentation (Boykov-Kolmogorov max-flow, GrabCut GMMs, coarse to fine), optical-flow propagation with band re-segmentation, correction strokes, Roto Brush & Refine Edge effect with content-keyed derived cache, roto.* commands (stroke/propagate/span/freeze/unfreeze/clearStrokes/ cancel/options/status), refine-edge matting (guided filter + closed-form) and decontamination, Freeze job. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e911cc5c93
commit
07330bca6b
@@ -22,6 +22,7 @@ pub mod fit;
|
||||
pub mod klt;
|
||||
pub mod mask;
|
||||
pub mod plane;
|
||||
pub mod roto;
|
||||
pub mod solve;
|
||||
pub mod stabilize;
|
||||
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Gaussian mixture colour models (full 3 × 3 covariances), as used by GrabCut (C. Rother,
|
||||
//! V. Kolmogorov and A. Blake, "GrabCut: Interactive Foreground Extraction using Iterated Graph
|
||||
//! Cuts", SIGGRAPH 2004).
|
||||
//!
|
||||
//! Fitting is deterministic: components are initialised by recursive splitting of the cluster
|
||||
//! with the largest variance along its principal axis (Orchard & Bouman, "Color Quantization of
|
||||
//! Images", IEEE TSP 1991), then refined by a few hard-assignment EM iterations.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One Gaussian: weight, mean, inverse covariance and log normaliser.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Gauss {
|
||||
pub weight: f64,
|
||||
pub mean: [f64; 3],
|
||||
pub inv: [[f64; 3]; 3],
|
||||
/// −log(weight) + ½·log(det Σ) (the 2π term is dropped: it cancels between models).
|
||||
pub log_norm: f64,
|
||||
}
|
||||
|
||||
/// A colour model.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Gmm {
|
||||
pub comps: Vec<Gauss>,
|
||||
}
|
||||
|
||||
/// Regularisation added to every covariance's diagonal (colour noise floor).
|
||||
const REG: f64 = 2e-4;
|
||||
|
||||
fn det3(m: &[[f64; 3]; 3]) -> f64 {
|
||||
m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
|
||||
}
|
||||
|
||||
fn inv3(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
|
||||
let d = det3(m);
|
||||
if d.abs() < 1e-30 {
|
||||
return None;
|
||||
}
|
||||
let mut r = [[0.0; 3]; 3];
|
||||
r[0][0] = (m[1][1] * m[2][2] - m[1][2] * m[2][1]) / d;
|
||||
r[0][1] = (m[0][2] * m[2][1] - m[0][1] * m[2][2]) / d;
|
||||
r[0][2] = (m[0][1] * m[1][2] - m[0][2] * m[1][1]) / d;
|
||||
r[1][0] = (m[1][2] * m[2][0] - m[1][0] * m[2][2]) / d;
|
||||
r[1][1] = (m[0][0] * m[2][2] - m[0][2] * m[2][0]) / d;
|
||||
r[1][2] = (m[0][2] * m[1][0] - m[0][0] * m[1][2]) / d;
|
||||
r[2][0] = (m[1][0] * m[2][1] - m[1][1] * m[2][0]) / d;
|
||||
r[2][1] = (m[0][1] * m[2][0] - m[0][0] * m[2][1]) / d;
|
||||
r[2][2] = (m[0][0] * m[1][1] - m[0][1] * m[1][0]) / d;
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// Sufficient statistics of a cluster.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Stats {
|
||||
n: f64,
|
||||
s: [f64; 3],
|
||||
ss: [[f64; 3]; 3],
|
||||
}
|
||||
|
||||
impl Stats {
|
||||
fn add(&mut self, c: [f32; 3]) {
|
||||
let c = [c[0] as f64, c[1] as f64, c[2] as f64];
|
||||
self.n += 1.0;
|
||||
for i in 0..3 {
|
||||
self.s[i] += c[i];
|
||||
for j in 0..3 {
|
||||
self.ss[i][j] += c[i] * c[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
fn mean(&self) -> [f64; 3] {
|
||||
let n = self.n.max(1.0);
|
||||
[self.s[0] / n, self.s[1] / n, self.s[2] / n]
|
||||
}
|
||||
fn cov(&self) -> [[f64; 3]; 3] {
|
||||
let n = self.n.max(1.0);
|
||||
let m = self.mean();
|
||||
let mut c = [[0.0; 3]; 3];
|
||||
for i in 0..3 {
|
||||
for j in 0..3 {
|
||||
c[i][j] = self.ss[i][j] / n - m[i] * m[j];
|
||||
}
|
||||
c[i][i] += REG;
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
/// Principal eigenvector and eigenvalue of a symmetric 3 × 3 matrix (power iteration).
|
||||
fn principal(c: &[[f64; 3]; 3]) -> ([f64; 3], f64) {
|
||||
let mut v = [0.577, 0.577, 0.577];
|
||||
let mut lambda = 0.0;
|
||||
for _ in 0..40 {
|
||||
let w = [
|
||||
c[0][0] * v[0] + c[0][1] * v[1] + c[0][2] * v[2],
|
||||
c[1][0] * v[0] + c[1][1] * v[1] + c[1][2] * v[2],
|
||||
c[2][0] * v[0] + c[2][1] * v[1] + c[2][2] * v[2],
|
||||
];
|
||||
let n = (w[0] * w[0] + w[1] * w[1] + w[2] * w[2]).sqrt();
|
||||
if n < 1e-30 {
|
||||
break;
|
||||
}
|
||||
lambda = n;
|
||||
v = [w[0] / n, w[1] / n, w[2] / n];
|
||||
}
|
||||
(v, lambda)
|
||||
}
|
||||
|
||||
impl Gmm {
|
||||
/// Fit `k` components to `samples` (at most `max_samples` are used, taken at a fixed stride).
|
||||
pub fn fit(samples: &[[f32; 3]], k: usize, max_samples: usize) -> Gmm {
|
||||
if samples.is_empty() {
|
||||
return Gmm::default();
|
||||
}
|
||||
let stride = samples.len().div_ceil(max_samples.max(1)).max(1);
|
||||
let xs: Vec<[f32; 3]> = samples.iter().step_by(stride).copied().collect();
|
||||
// Orchard–Bouman splitting.
|
||||
let mut label = vec![0usize; xs.len()];
|
||||
let mut ncl = 1;
|
||||
while ncl < k {
|
||||
let mut st = vec![Stats::default(); ncl];
|
||||
for (x, l) in xs.iter().zip(&label) {
|
||||
st[*l].add(*x);
|
||||
}
|
||||
let (mut best, mut best_l, mut axis) = (usize::MAX, 0.0, [0.0; 3]);
|
||||
for (c, s) in st.iter().enumerate() {
|
||||
if s.n < 2.0 {
|
||||
continue;
|
||||
}
|
||||
let (v, l) = principal(&s.cov());
|
||||
if l > best_l {
|
||||
best = c;
|
||||
best_l = l;
|
||||
axis = v;
|
||||
}
|
||||
}
|
||||
if best == usize::MAX || best_l <= REG * 1.01 {
|
||||
break;
|
||||
}
|
||||
let m = st[best].mean();
|
||||
let thr = axis[0] * m[0] + axis[1] * m[1] + axis[2] * m[2];
|
||||
for (x, l) in xs.iter().zip(label.iter_mut()) {
|
||||
if *l == best && axis[0] * x[0] as f64 + axis[1] * x[1] as f64 + axis[2] * x[2] as f64 > thr {
|
||||
*l = ncl;
|
||||
}
|
||||
}
|
||||
ncl += 1;
|
||||
}
|
||||
let mut g = Gmm::from_labels(&xs, &label, ncl);
|
||||
// Hard EM.
|
||||
for _ in 0..3 {
|
||||
for (x, l) in xs.iter().zip(label.iter_mut()) {
|
||||
*l = g.best(*x);
|
||||
}
|
||||
let ng = Gmm::from_labels(&xs, &label, g.comps.len());
|
||||
if ng.comps.is_empty() {
|
||||
break;
|
||||
}
|
||||
g = ng;
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
fn from_labels(xs: &[[f32; 3]], label: &[usize], k: usize) -> Gmm {
|
||||
let mut st = vec![Stats::default(); k];
|
||||
for (x, l) in xs.iter().zip(label) {
|
||||
st[*l].add(*x);
|
||||
}
|
||||
let total: f64 = st.iter().map(|s| s.n).sum::<f64>().max(1.0);
|
||||
let comps = st
|
||||
.iter()
|
||||
.filter(|s| s.n >= 1.0)
|
||||
.filter_map(|s| {
|
||||
let c = s.cov();
|
||||
let inv = inv3(&c)?;
|
||||
let det = det3(&c).max(1e-300);
|
||||
let weight = s.n / total;
|
||||
Some(Gauss { weight, mean: s.mean(), inv, log_norm: -weight.ln() + 0.5 * det.ln() })
|
||||
})
|
||||
.collect();
|
||||
Gmm { comps }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn comp_cost(g: &Gauss, c: [f32; 3]) -> f64 {
|
||||
let d = [c[0] as f64 - g.mean[0], c[1] as f64 - g.mean[1], c[2] as f64 - g.mean[2]];
|
||||
let mut q = 0.0;
|
||||
for i in 0..3 {
|
||||
q += d[i] * (g.inv[i][0] * d[0] + g.inv[i][1] * d[1] + g.inv[i][2] * d[2]);
|
||||
}
|
||||
g.log_norm + 0.5 * q
|
||||
}
|
||||
|
||||
/// The most likely component of colour `c`.
|
||||
pub fn best(&self, c: [f32; 3]) -> usize {
|
||||
let mut b = 0;
|
||||
let mut bv = f64::INFINITY;
|
||||
for (i, g) in self.comps.iter().enumerate() {
|
||||
let v = Self::comp_cost(g, c);
|
||||
if v < bv {
|
||||
bv = v;
|
||||
b = i;
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// −log p(c) (up to a constant shared by all models), clamped to a finite range.
|
||||
pub fn cost(&self, c: [f32; 3]) -> f64 {
|
||||
if self.comps.is_empty() {
|
||||
return 10.0;
|
||||
}
|
||||
// log-sum-exp over components.
|
||||
let mut m = f64::INFINITY;
|
||||
let mut costs = [0.0f64; 16];
|
||||
let n = self.comps.len().min(16);
|
||||
for (i, g) in self.comps.iter().take(n).enumerate() {
|
||||
costs[i] = Self::comp_cost(g, c);
|
||||
m = m.min(costs[i]);
|
||||
}
|
||||
let s: f64 = costs[..n].iter().map(|v| (m - v).exp()).sum();
|
||||
(m - s.ln()).clamp(-20.0, 60.0)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.comps.is_empty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
//! Matte utilities: exact Euclidean distance transforms (Felzenszwalb & Huttenlocher,
|
||||
//! "Distance Transforms of Sampled Functions", Theory of Computing 8, 2012), box and Gaussian
|
||||
//! filters, the colour **guided filter** (K. He, J. Sun and X. Tang, "Guided Image Filtering",
|
||||
//! ECCV 2010 / IEEE PAMI 2013) used for edge matting, foreground colour estimation
|
||||
//! (decontamination, from the compositing equation I = αF + (1 − α)B with B and F estimated from
|
||||
//! nearby pure background / foreground pixels), and the Refine Edge matte adjustments.
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
const BIG: f32 = 1e12;
|
||||
|
||||
/// 1-D squared distance transform of `f` (lower envelope of parabolas).
|
||||
fn dt1(f: &[f32], d: &mut [f32], v: &mut [usize], z: &mut [f64]) {
|
||||
let n = f.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let ff = |q: usize| f[q] as f64 + (q * q) as f64;
|
||||
let mut k = 0usize;
|
||||
v[0] = 0;
|
||||
z[0] = f64::NEG_INFINITY;
|
||||
z[1] = f64::INFINITY;
|
||||
for q in 1..n {
|
||||
let mut s = (ff(q) - ff(v[k])) / (2.0 * (q as f64 - v[k] as f64));
|
||||
while s <= z[k] {
|
||||
if k == 0 {
|
||||
break;
|
||||
}
|
||||
k -= 1;
|
||||
s = (ff(q) - ff(v[k])) / (2.0 * (q as f64 - v[k] as f64));
|
||||
}
|
||||
k += 1;
|
||||
v[k] = q;
|
||||
z[k] = s;
|
||||
z[k + 1] = f64::INFINITY;
|
||||
}
|
||||
k = 0;
|
||||
for (q, dq) in d.iter_mut().enumerate().take(n) {
|
||||
while z[k + 1] < q as f64 {
|
||||
k += 1;
|
||||
}
|
||||
let p = v[k];
|
||||
let dd = q as f64 - p as f64;
|
||||
*dq = (dd * dd + f[p] as f64) as f32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Euclidean distance from every pixel to the nearest pixel where `seed` is true (BIG.sqrt()
|
||||
/// when there is none).
|
||||
pub fn distance(seed: &[bool], w: usize, h: usize) -> Vec<f32> {
|
||||
if w == 0 || h == 0 {
|
||||
return vec![];
|
||||
}
|
||||
let mut g: Vec<f32> = seed.iter().map(|s| if *s { 0.0 } else { BIG }).collect();
|
||||
// Columns.
|
||||
let cols: Vec<Vec<f32>> = (0..w)
|
||||
.into_par_iter()
|
||||
.map(|x| {
|
||||
let f: Vec<f32> = (0..h).map(|y| g[y * w + x]).collect();
|
||||
let mut d = vec![0.0; h];
|
||||
let (mut v, mut z) = (vec![0usize; h], vec![0.0f64; h + 1]);
|
||||
dt1(&f, &mut d, &mut v, &mut z);
|
||||
d
|
||||
})
|
||||
.collect();
|
||||
for (x, c) in cols.iter().enumerate() {
|
||||
for y in 0..h {
|
||||
g[y * w + x] = c[y];
|
||||
}
|
||||
}
|
||||
// Rows.
|
||||
g.par_chunks_mut(w).for_each(|row| {
|
||||
let f = row.to_vec();
|
||||
let (mut v, mut z) = (vec![0usize; w], vec![0.0f64; w + 1]);
|
||||
dt1(&f, row, &mut v, &mut z);
|
||||
});
|
||||
g.par_iter_mut().for_each(|v| *v = v.sqrt());
|
||||
g
|
||||
}
|
||||
|
||||
/// Signed distance to a binary matte's edge: positive inside (distance to the nearest
|
||||
/// background pixel centre, minus ½), negative outside.
|
||||
pub fn signed_distance(m: &[u8], w: usize, h: usize) -> Vec<f32> {
|
||||
let fg: Vec<bool> = m.iter().map(|v| *v != 0).collect();
|
||||
let bg: Vec<bool> = m.iter().map(|v| *v == 0).collect();
|
||||
let din = distance(&bg, w, h);
|
||||
let dout = distance(&fg, w, h);
|
||||
m.iter().enumerate().map(|(i, v)| if *v != 0 { din[i] - 0.5 } else { 0.5 - dout[i] }).collect()
|
||||
}
|
||||
|
||||
/// Mean over the (2r+1)² window (clamped at the edges: averages only the pixels inside).
|
||||
pub fn box_mean(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {
|
||||
if w == 0 || h == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// Horizontal window sums per row.
|
||||
let mut tmp = vec![0.0f64; w * h];
|
||||
tmp.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
|
||||
let s = &src[y * w..y * w + w];
|
||||
let mut acc = 0.0f64;
|
||||
for x in 0..r.min(w) {
|
||||
acc += s[x] as f64;
|
||||
}
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
if x + r < w {
|
||||
acc += s[x + r] as f64;
|
||||
}
|
||||
if x > r {
|
||||
acc -= s[x - r - 1] as f64;
|
||||
}
|
||||
*o = acc;
|
||||
}
|
||||
});
|
||||
// Vertical prefix sums (row by row, cache friendly), then window differences.
|
||||
let mut pre = vec![0.0f64; w * (h + 1)];
|
||||
for y in 0..h {
|
||||
let (done, rest) = pre.split_at_mut((y + 1) * w);
|
||||
let prev = &done[y * w..];
|
||||
let cur = &mut rest[..w];
|
||||
let t = &tmp[y * w..y * w + w];
|
||||
for x in 0..w {
|
||||
cur[x] = prev[x] + t[x];
|
||||
}
|
||||
}
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
|
||||
let a = y.saturating_sub(r);
|
||||
let b = (y + r + 1).min(h);
|
||||
let cy = (b - a) as f64;
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let cx = ((x + r + 1).min(w) - x.saturating_sub(r)) as f64;
|
||||
*o = ((pre[b * w + x] - pre[a * w + x]) / (cx * cy)) as f32;
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Approximate Gaussian blur (three box passes) with standard deviation `sigma` pixels.
|
||||
pub fn gauss(src: &[f32], w: usize, h: usize, sigma: f64) -> Vec<f32> {
|
||||
if sigma < 0.3 {
|
||||
return src.to_vec();
|
||||
}
|
||||
// Box radius whose three passes match the variance: 3·((2r+1)² − 1)/12 = σ².
|
||||
let r = (((4.0 * sigma * sigma + 1.0).sqrt() - 1.0) / 2.0).round().max(1.0) as usize;
|
||||
let a = box_mean(src, w, h, r);
|
||||
let b = box_mean(&a, w, h, r);
|
||||
box_mean(&b, w, h, r)
|
||||
}
|
||||
|
||||
fn inv3(m: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
|
||||
let d = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
|
||||
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
|
||||
let d = if d.abs() < 1e-20 { 1e-20 } else { d };
|
||||
[
|
||||
[(m[1][1] * m[2][2] - m[1][2] * m[2][1]) / d, (m[0][2] * m[2][1] - m[0][1] * m[2][2]) / d, (m[0][1] * m[1][2] - m[0][2] * m[1][1]) / d],
|
||||
[(m[1][2] * m[2][0] - m[1][0] * m[2][2]) / d, (m[0][0] * m[2][2] - m[0][2] * m[2][0]) / d, (m[0][2] * m[1][0] - m[0][0] * m[1][2]) / d],
|
||||
[(m[1][0] * m[2][1] - m[1][1] * m[2][0]) / d, (m[0][1] * m[2][0] - m[0][0] * m[2][1]) / d, (m[0][0] * m[1][1] - m[0][1] * m[1][0]) / d],
|
||||
]
|
||||
}
|
||||
|
||||
/// The colour guided filter of `p` with guide `img` (RGB, w × h), window radius `r`,
|
||||
/// regularisation `eps` (He et al. 2010, section 3.5).
|
||||
pub fn guided_filter(img: &[[f32; 3]], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {
|
||||
let n = w * h;
|
||||
let ch = |c: usize| -> Vec<f32> { img.iter().map(|v| v[c]).collect() };
|
||||
let (ir, ig, ib) = (ch(0), ch(1), ch(2));
|
||||
let mul = |a: &[f32], b: &[f32]| -> Vec<f32> { a.iter().zip(b).map(|(x, y)| x * y).collect() };
|
||||
let bm = |v: &[f32]| box_mean(v, w, h, r);
|
||||
let (mr, mg, mb, mp) = (bm(&ir), bm(&ig), bm(&ib), bm(p));
|
||||
let (mrp, mgp, mbp) = (bm(&mul(&ir, p)), bm(&mul(&ig, p)), bm(&mul(&ib, p)));
|
||||
let (vrr, vrg, vrb) = (bm(&mul(&ir, &ir)), bm(&mul(&ir, &ig)), bm(&mul(&ir, &ib)));
|
||||
let (vgg, vgb, vbb) = (bm(&mul(&ig, &ig)), bm(&mul(&ig, &ib)), bm(&mul(&ib, &ib)));
|
||||
let mut a = vec![[0.0f32; 3]; n];
|
||||
let mut b = vec![0.0f32; n];
|
||||
a.par_iter_mut().zip(b.par_iter_mut()).enumerate().for_each(|(i, (ai, bi))| {
|
||||
let cov = [mrp[i] - mr[i] * mp[i], mgp[i] - mg[i] * mp[i], mbp[i] - mb[i] * mp[i]];
|
||||
let s = [
|
||||
[vrr[i] - mr[i] * mr[i] + eps, vrg[i] - mr[i] * mg[i], vrb[i] - mr[i] * mb[i]],
|
||||
[vrg[i] - mr[i] * mg[i], vgg[i] - mg[i] * mg[i] + eps, vgb[i] - mg[i] * mb[i]],
|
||||
[vrb[i] - mr[i] * mb[i], vgb[i] - mg[i] * mb[i], vbb[i] - mb[i] * mb[i] + eps],
|
||||
];
|
||||
let inv = inv3(s);
|
||||
let av = [
|
||||
cov[0] * inv[0][0] + cov[1] * inv[1][0] + cov[2] * inv[2][0],
|
||||
cov[0] * inv[0][1] + cov[1] * inv[1][1] + cov[2] * inv[2][1],
|
||||
cov[0] * inv[0][2] + cov[1] * inv[1][2] + cov[2] * inv[2][2],
|
||||
];
|
||||
*ai = av;
|
||||
*bi = mp[i] - av[0] * mr[i] - av[1] * mg[i] - av[2] * mb[i];
|
||||
});
|
||||
let (a0, a1, a2): (Vec<f32>, Vec<f32>, Vec<f32>) = (a.iter().map(|v| v[0]).collect(), a.iter().map(|v| v[1]).collect(), a.iter().map(|v| v[2]).collect());
|
||||
let (ma0, ma1, ma2, mbb) = (bm(&a0), bm(&a1), bm(&a2), bm(&b));
|
||||
(0..n).into_par_iter().map(|i| ma0[i] * ir[i] + ma1[i] * ig[i] + ma2[i] * ib[i] + mbb[i]).collect()
|
||||
}
|
||||
|
||||
/// Closed-form matting (A. Levin, D. Lischinski and Y. Weiss, "A Closed-Form Solution to Natural
|
||||
/// Image Matting", IEEE PAMI 30(2), 2008): the alpha that minimises αᵀLα with the matting
|
||||
/// Laplacian `L` of the colour image, with `known` pixels fixed to `init`. Solved by conjugate
|
||||
/// gradients over the unknown pixels, starting from `init`; `L·x` is evaluated with box filters
|
||||
/// (K. He, J. Sun and X. Tang, "Fast Matting Using Large Kernel Matting Laplacian Matrices",
|
||||
/// CVPR 2010): `(L·x)ᵢ = Σ_{k∋i} (xᵢ − a_kᵀIᵢ − b_k)` with `(a_k, b_k)` the ridge-regression
|
||||
/// fit of `x` to the colours in window k.
|
||||
pub fn closed_form(img: &[[f32; 3]], init: &[f32], known: &[bool], w: usize, h: usize, r: usize, eps: f32, iters: usize) -> Vec<f32> {
|
||||
let n = w * h;
|
||||
if n == 0 || known.iter().all(|k| *k) {
|
||||
return init.to_vec();
|
||||
}
|
||||
let ch = |c: usize| -> Vec<f32> { img.iter().map(|v| v[c]).collect() };
|
||||
let ic = [ch(0), ch(1), ch(2)];
|
||||
let bm = |v: &[f32]| box_mean(v, w, h, r);
|
||||
let mu = [bm(&ic[0]), bm(&ic[1]), bm(&ic[2])];
|
||||
let prod = |a: usize, b: usize| -> Vec<f32> { ic[a].iter().zip(&ic[b]).map(|(x, y)| x * y).collect() };
|
||||
let mut cov = [[vec![], vec![], vec![]], [vec![], vec![], vec![]], [vec![], vec![], vec![]]];
|
||||
for a in 0..3 {
|
||||
for b in a..3 {
|
||||
let m = bm(&prod(a, b));
|
||||
cov[a][b] = m.clone();
|
||||
cov[b][a] = m;
|
||||
}
|
||||
}
|
||||
let inv: Vec<[[f32; 3]; 3]> = (0..n)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let mut s = [[0.0f32; 3]; 3];
|
||||
for a in 0..3 {
|
||||
for b in 0..3 {
|
||||
s[a][b] = cov[a][b][i] - mu[a][i] * mu[b][i] + if a == b { eps } else { 0.0 };
|
||||
}
|
||||
}
|
||||
inv3(s)
|
||||
})
|
||||
.collect();
|
||||
// Pixels per window (= windows per pixel).
|
||||
let cnt: Vec<f32> = {
|
||||
let (rr, mut out) = (r as i64, vec![0.0f32; n]);
|
||||
for (i, o) in out.iter_mut().enumerate() {
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
let cx = (x + rr).min(w as i64 - 1) - (x - rr).max(0) + 1;
|
||||
let cy = (y + rr).min(h as i64 - 1) - (y - rr).max(0) + 1;
|
||||
*o = (cx * cy) as f32;
|
||||
}
|
||||
out
|
||||
};
|
||||
let lap = |x: &[f32]| -> Vec<f32> {
|
||||
let pm = bm(x);
|
||||
let ipm: Vec<Vec<f32>> = (0..3).map(|c| bm(&ic[c].iter().zip(x).map(|(a, b)| a * b).collect::<Vec<_>>())).collect();
|
||||
let ab: Vec<[f32; 4]> = (0..n)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let cv = [ipm[0][i] - mu[0][i] * pm[i], ipm[1][i] - mu[1][i] * pm[i], ipm[2][i] - mu[2][i] * pm[i]];
|
||||
let m = &inv[i];
|
||||
let a = [
|
||||
m[0][0] * cv[0] + m[0][1] * cv[1] + m[0][2] * cv[2],
|
||||
m[1][0] * cv[0] + m[1][1] * cv[1] + m[1][2] * cv[2],
|
||||
m[2][0] * cv[0] + m[2][1] * cv[1] + m[2][2] * cv[2],
|
||||
];
|
||||
[a[0], a[1], a[2], pm[i] - a[0] * mu[0][i] - a[1] * mu[1][i] - a[2] * mu[2][i]]
|
||||
})
|
||||
.collect();
|
||||
let sa: Vec<Vec<f32>> = (0..3).map(|c| bm(&ab.iter().map(|v| v[c]).collect::<Vec<_>>())).collect();
|
||||
let sb = bm(&ab.iter().map(|v| v[3]).collect::<Vec<_>>());
|
||||
(0..n).into_par_iter().map(|i| cnt[i] * (x[i] - sa[0][i] * ic[0][i] - sa[1][i] * ic[1][i] - sa[2][i] * ic[2][i] - sb[i])).collect()
|
||||
};
|
||||
// L_UU x = −(L α_K)_U.
|
||||
let a0: Vec<f32> = (0..n).map(|i| if known[i] { init[i] } else { 0.0 }).collect();
|
||||
let la0 = lap(&a0);
|
||||
let mut x: Vec<f32> = (0..n).map(|i| if known[i] { 0.0 } else { init[i] }).collect();
|
||||
let lx = lap(&x);
|
||||
let mut res: Vec<f64> = (0..n).map(|i| if known[i] { 0.0 } else { (-la0[i] - lx[i]) as f64 }).collect();
|
||||
let mut p = res.clone();
|
||||
let mut rs: f64 = res.iter().map(|v| v * v).sum();
|
||||
let rs0 = rs.max(1e-30);
|
||||
for _ in 0..iters {
|
||||
if rs <= rs0 * 1e-8 {
|
||||
break;
|
||||
}
|
||||
let pf: Vec<f32> = p.iter().map(|v| *v as f32).collect();
|
||||
let ap: Vec<f64> = lap(&pf).iter().enumerate().map(|(i, v)| if known[i] { 0.0 } else { *v as f64 }).collect();
|
||||
let pap: f64 = p.iter().zip(&ap).map(|(a, b)| a * b).sum();
|
||||
if pap <= 1e-30 {
|
||||
break;
|
||||
}
|
||||
let alpha = rs / pap;
|
||||
for i in 0..n {
|
||||
x[i] += (alpha * p[i]) as f32;
|
||||
res[i] -= alpha * ap[i];
|
||||
}
|
||||
let rs_new: f64 = res.iter().map(|v| v * v).sum();
|
||||
let beta = rs_new / rs;
|
||||
rs = rs_new;
|
||||
for i in 0..n {
|
||||
p[i] = res[i] + beta * p[i];
|
||||
}
|
||||
}
|
||||
(0..n).map(|i| if known[i] { init[i] } else { x[i].clamp(0.0, 1.0) }).collect()
|
||||
}
|
||||
|
||||
/// Contrast (0–100 %) around ½ on a soft alpha.
|
||||
pub fn contrast(a: &mut [f32], pc: f64) {
|
||||
if pc <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let k = 1.0 / (1.0 - 0.99 * (pc / 100.0).clamp(0.0, 1.0)) as f32;
|
||||
a.par_iter_mut().for_each(|v| *v = (0.5 + (*v - 0.5) * k).clamp(0.0, 1.0));
|
||||
}
|
||||
|
||||
/// Shift Edge (−100–100 %) on a soft alpha: positive values grow the matte (a gamma curve on α).
|
||||
pub fn shift_soft(a: &mut [f32], pc: f64) {
|
||||
if pc.abs() < 1e-9 {
|
||||
return;
|
||||
}
|
||||
let g = 2f32.powf((-pc / 50.0) as f32);
|
||||
a.par_iter_mut().for_each(|v| *v = v.clamp(0.0, 1.0).powf(g));
|
||||
}
|
||||
|
||||
/// Estimate the pure foreground colour of every pixel listed in `region` (alpha strictly
|
||||
/// between 0 and 1) and mix it in by `amount` (0–1). `radius`: neighbourhood (pixels) that pure
|
||||
/// background / foreground estimates are taken from. Returns the decontamination map (how much
|
||||
/// each pixel's colour changed, 0–1).
|
||||
pub fn decontaminate(img: &mut [[f32; 3]], alpha: &[f32], region: &[bool], w: usize, h: usize, radius: usize, amount: f32) -> Vec<f32> {
|
||||
let n = w * h;
|
||||
let mut map = vec![0.0f32; n];
|
||||
if !region.iter().any(|r| *r) || amount <= 0.0 {
|
||||
return map;
|
||||
}
|
||||
let lo: Vec<f32> = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect();
|
||||
let hi: Vec<f32> = alpha.iter().map(|a| if *a > 0.98 { 1.0 } else { 0.0 }).collect();
|
||||
// Windowed means of pure background / foreground colours, widening where none is near.
|
||||
let est = |m: &[f32]| -> Vec<Option<[f32; 3]>> {
|
||||
let mut out: Vec<Option<[f32; 3]>> = vec![None; n];
|
||||
let mut r = radius.max(2);
|
||||
for _ in 0..4 {
|
||||
let cnt = box_mean(m, w, h, r);
|
||||
let sums: Vec<Vec<f32>> = (0..3).map(|c| box_mean(&img.iter().zip(m).map(|(p, k)| p[c] * k).collect::<Vec<_>>(), w, h, r)).collect();
|
||||
let mut missing = false;
|
||||
for i in 0..n {
|
||||
if region[i] && out[i].is_none() {
|
||||
if cnt[i] > 1e-4 {
|
||||
out[i] = Some([sums[0][i] / cnt[i], sums[1][i] / cnt[i], sums[2][i] / cnt[i]]);
|
||||
} else {
|
||||
missing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !missing {
|
||||
break;
|
||||
}
|
||||
r *= 2;
|
||||
}
|
||||
out
|
||||
};
|
||||
let bgc = est(&lo);
|
||||
let fgc = est(&hi);
|
||||
for i in 0..n {
|
||||
if !region[i] {
|
||||
continue;
|
||||
}
|
||||
let a = alpha[i].clamp(0.0, 1.0);
|
||||
if a <= 0.0 || a >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let c = img[i];
|
||||
let f = match (bgc[i], fgc[i]) {
|
||||
(Some(b), fbar) => {
|
||||
let mut f = [0.0f32; 3];
|
||||
for k in 0..3 {
|
||||
f[k] = ((c[k] - (1.0 - a) * b[k]) / a).clamp(0.0, 1.0);
|
||||
}
|
||||
// Low alphas amplify noise: lean on the nearby foreground colour there.
|
||||
if let Some(fb) = fbar {
|
||||
let t = ((0.25 - a) / 0.25).clamp(0.0, 1.0);
|
||||
for k in 0..3 {
|
||||
f[k] += (fb[k] - f[k]) * t;
|
||||
}
|
||||
}
|
||||
f
|
||||
}
|
||||
(None, Some(fb)) => fb,
|
||||
(None, None) => c,
|
||||
};
|
||||
let mut d = 0.0f32;
|
||||
for k in 0..3 {
|
||||
let v = c[k] + (f[k] - c[k]) * amount;
|
||||
d = d.max((v - c[k]).abs());
|
||||
img[i][k] = v;
|
||||
}
|
||||
map[i] = d.min(1.0);
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
/// Sample a float plane bilinearly at continuous coordinates (pixel centres at +0.5), clamped.
|
||||
pub fn sample(p: &[f32], w: usize, h: usize, x: f64, y: f64) -> f32 {
|
||||
if w == 0 || h == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let fx = (x - 0.5).clamp(0.0, (w - 1) as f64);
|
||||
let fy = (y - 0.5).clamp(0.0, (h - 1) as f64);
|
||||
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
|
||||
let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
|
||||
let g = |x: usize, y: usize| p[y * w + x];
|
||||
let top = g(x0, y0) + (g(x1, y0) - g(x0, y0)) * tx;
|
||||
let bot = g(x0, y1) + (g(x1, y1) - g(x0, y1)) * tx;
|
||||
top + (bot - top) * ty
|
||||
}
|
||||
|
||||
/// Average of `a` sampled along the segment `[-v/2, v/2]` with `samples` taps (motion blur of a
|
||||
/// matte moving by `v` pixels during the shutter).
|
||||
pub fn motion_blur(a: &[f32], w: usize, h: usize, v: [f64; 2], samples: usize) -> Vec<f32> {
|
||||
let n = samples.max(2);
|
||||
if v[0].hypot(v[1]) < 0.25 {
|
||||
return a.to_vec();
|
||||
}
|
||||
(0..w * h)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
|
||||
let mut s = 0.0;
|
||||
for k in 0..n {
|
||||
let t = k as f64 / (n - 1) as f64 - 0.5;
|
||||
s += sample(a, w, h, x - v[0] * t, y - v[1] * t);
|
||||
}
|
||||
s / n as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn distance_matches_brute_force() {
|
||||
let (w, h) = (23, 17);
|
||||
let seed: Vec<bool> = (0..w * h).map(|i| (i * 7919) % 31 == 0).collect();
|
||||
let d = distance(&seed, w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut b = f32::INFINITY;
|
||||
for j in 0..h {
|
||||
for i in 0..w {
|
||||
if seed[j * w + i] {
|
||||
b = b.min(((x as f32 - i as f32).powi(2) + (y as f32 - j as f32).powi(2)).sqrt());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!((d[y * w + x] - b).abs() < 1e-3, "{x},{y}: {} vs {b}", d[y * w + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guided_filter_recovers_a_linear_blend() {
|
||||
// I = αF + (1 − α)B with constant F, B: the filtered binary matte is close to α.
|
||||
let (w, h) = (64, 8);
|
||||
let alpha: Vec<f32> = (0..w * h).map(|i| (((i % w) as f32 - 26.0) / 12.0).clamp(0.0, 1.0)).collect();
|
||||
let (f, b) = ([0.9f32, 0.2, 0.1], [0.1f32, 0.3, 0.8]);
|
||||
let img: Vec<[f32; 3]> = alpha.iter().map(|a| [a * f[0] + (1.0 - a) * b[0], a * f[1] + (1.0 - a) * b[1], a * f[2] + (1.0 - a) * b[2]]).collect();
|
||||
let p: Vec<f32> = alpha.iter().map(|a| if *a >= 0.5 { 1.0 } else { 0.0 }).collect();
|
||||
let q = guided_filter(&img, &p, w, h, 8, 1e-5);
|
||||
let err: f32 = q.iter().zip(&alpha).map(|(a, b)| (a.clamp(0.0, 1.0) - b).abs()).sum::<f32>() / (w * h) as f32;
|
||||
assert!(err < 0.03, "mean error {err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
//! Min-cut / max-flow on sparse graphs with source and sink terminals, by the
|
||||
//! Boykov–Kolmogorov algorithm (Y. Boykov and V. Kolmogorov, "An Experimental Comparison of
|
||||
//! Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision", IEEE PAMI 26(9), 2004).
|
||||
//!
|
||||
//! Two search trees grow from the terminals (S from the source, T from the sink) through
|
||||
//! non-saturated edges; when they touch, the path found is augmented; saturated tree edges turn
|
||||
//! the nodes below them into *orphans*, which the adoption stage re-attaches to their tree (or
|
||||
//! frees). Trees are reused between augmentations, which is what makes the method fast on the
|
||||
//! grid graphs of image segmentation. The timestamp/distance heuristic of section 3.2.3 keeps
|
||||
//! adoption paths short.
|
||||
//!
|
||||
//! Capacities are integers (callers scale their energies), so saturation tests are exact and
|
||||
//! the result is deterministic.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const NONE: u32 = u32::MAX;
|
||||
const TERMINAL: u32 = u32::MAX - 1;
|
||||
const ORPHAN: u32 = u32::MAX - 2;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Node {
|
||||
first: u32,
|
||||
/// Arc to the parent (from this node), or TERMINAL / ORPHAN / NONE (free).
|
||||
parent: u32,
|
||||
/// Residual terminal capacity: > 0 towards the source, < 0 towards the sink.
|
||||
tr_cap: i64,
|
||||
is_sink: bool,
|
||||
active: bool,
|
||||
ts: u32,
|
||||
dist: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Arc {
|
||||
head: u32,
|
||||
next: u32,
|
||||
r_cap: i32,
|
||||
}
|
||||
|
||||
/// A graph for one min-cut computation.
|
||||
pub struct Graph {
|
||||
nodes: Vec<Node>,
|
||||
arcs: Vec<Arc>,
|
||||
flow: i64,
|
||||
time: u32,
|
||||
queue: VecDeque<u32>,
|
||||
orphans: VecDeque<u32>,
|
||||
}
|
||||
|
||||
/// Which side of the cut a node ended on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Segment {
|
||||
Source,
|
||||
Sink,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
pub fn new(nodes: usize, edges_hint: usize) -> Graph {
|
||||
Graph {
|
||||
nodes: vec![Node { first: NONE, parent: NONE, tr_cap: 0, is_sink: false, active: false, ts: 0, dist: 0 }; nodes],
|
||||
arcs: Vec::with_capacity(edges_hint * 2),
|
||||
flow: 0,
|
||||
time: 0,
|
||||
queue: VecDeque::new(),
|
||||
orphans: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.nodes.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty()
|
||||
}
|
||||
|
||||
/// Terminal capacities of node `i`: `source` is paid when `i` ends on the sink side, `sink`
|
||||
/// when it ends on the source side.
|
||||
pub fn add_tweights(&mut self, i: usize, source: i64, sink: i64) {
|
||||
let n = &mut self.nodes[i];
|
||||
let d = n.tr_cap;
|
||||
let (s, t) = if d > 0 { (source + d, sink) } else { (source, sink - d) };
|
||||
self.flow += s.min(t);
|
||||
n.tr_cap = s - t;
|
||||
}
|
||||
|
||||
/// An edge between `i` and `j` with capacity `cap` from i to j and `rev` from j to i.
|
||||
pub fn add_edge(&mut self, i: usize, j: usize, cap: i32, rev: i32) {
|
||||
debug_assert!(i != j);
|
||||
let a = self.arcs.len() as u32;
|
||||
self.arcs.push(Arc { head: j as u32, next: self.nodes[i].first, r_cap: cap });
|
||||
self.nodes[i].first = a;
|
||||
self.arcs.push(Arc { head: i as u32, next: self.nodes[j].first, r_cap: rev });
|
||||
self.nodes[j].first = a + 1;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_active(&mut self, i: u32) {
|
||||
let n = &mut self.nodes[i as usize];
|
||||
if !n.active {
|
||||
n.active = true;
|
||||
self.queue.push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the maximum flow (= the minimum cut's cost).
|
||||
pub fn maxflow(&mut self) -> i64 {
|
||||
for i in 0..self.nodes.len() {
|
||||
let n = &mut self.nodes[i];
|
||||
if n.tr_cap != 0 {
|
||||
n.is_sink = n.tr_cap < 0;
|
||||
n.parent = TERMINAL;
|
||||
n.ts = 0;
|
||||
n.dist = 1;
|
||||
self.set_active(i as u32);
|
||||
}
|
||||
}
|
||||
let mut current: Option<u32> = None;
|
||||
loop {
|
||||
let i = match current.take() {
|
||||
Some(i) if self.nodes[i as usize].parent != NONE => i,
|
||||
_ => loop {
|
||||
let Some(i) = self.queue.pop_front() else { return self.flow };
|
||||
self.nodes[i as usize].active = false;
|
||||
if self.nodes[i as usize].parent != NONE {
|
||||
break i;
|
||||
}
|
||||
},
|
||||
};
|
||||
// Growth.
|
||||
let mut found = NONE;
|
||||
let ni = self.nodes[i as usize];
|
||||
let mut a = ni.first;
|
||||
if !ni.is_sink {
|
||||
while a != NONE {
|
||||
let arc = self.arcs[a as usize];
|
||||
if arc.r_cap > 0 {
|
||||
let j = arc.head as usize;
|
||||
let nj = self.nodes[j];
|
||||
if nj.parent == NONE {
|
||||
let n = &mut self.nodes[j];
|
||||
n.is_sink = false;
|
||||
n.parent = a ^ 1;
|
||||
n.ts = ni.ts;
|
||||
n.dist = ni.dist + 1;
|
||||
self.set_active(j as u32);
|
||||
} else if nj.is_sink {
|
||||
found = a;
|
||||
break;
|
||||
} else if nj.ts <= ni.ts && nj.dist > ni.dist {
|
||||
let n = &mut self.nodes[j];
|
||||
n.parent = a ^ 1;
|
||||
n.ts = ni.ts;
|
||||
n.dist = ni.dist + 1;
|
||||
}
|
||||
}
|
||||
a = arc.next;
|
||||
}
|
||||
} else {
|
||||
while a != NONE {
|
||||
let arc = self.arcs[a as usize];
|
||||
if self.arcs[(a ^ 1) as usize].r_cap > 0 {
|
||||
let j = arc.head as usize;
|
||||
let nj = self.nodes[j];
|
||||
if nj.parent == NONE {
|
||||
let n = &mut self.nodes[j];
|
||||
n.is_sink = true;
|
||||
n.parent = a ^ 1;
|
||||
n.ts = ni.ts;
|
||||
n.dist = ni.dist + 1;
|
||||
self.set_active(j as u32);
|
||||
} else if !nj.is_sink {
|
||||
found = a ^ 1;
|
||||
break;
|
||||
} else if nj.ts <= ni.ts && nj.dist > ni.dist {
|
||||
let n = &mut self.nodes[j];
|
||||
n.parent = a ^ 1;
|
||||
n.ts = ni.ts;
|
||||
n.dist = ni.dist + 1;
|
||||
}
|
||||
}
|
||||
a = arc.next;
|
||||
}
|
||||
}
|
||||
self.time = self.time.wrapping_add(1);
|
||||
if found != NONE {
|
||||
// Keep `i` current: it may have more paths.
|
||||
current = Some(i);
|
||||
self.augment(found);
|
||||
self.adopt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn augment(&mut self, middle: u32) {
|
||||
let mut b = self.arcs[middle as usize].r_cap as i64;
|
||||
// Source side.
|
||||
let mut i = self.arcs[(middle ^ 1) as usize].head;
|
||||
loop {
|
||||
let a = self.nodes[i as usize].parent;
|
||||
if a == TERMINAL {
|
||||
break;
|
||||
}
|
||||
b = b.min(self.arcs[(a ^ 1) as usize].r_cap as i64);
|
||||
i = self.arcs[a as usize].head;
|
||||
}
|
||||
b = b.min(self.nodes[i as usize].tr_cap);
|
||||
// Sink side.
|
||||
let mut i = self.arcs[middle as usize].head;
|
||||
loop {
|
||||
let a = self.nodes[i as usize].parent;
|
||||
if a == TERMINAL {
|
||||
break;
|
||||
}
|
||||
b = b.min(self.arcs[a as usize].r_cap as i64);
|
||||
i = self.arcs[a as usize].head;
|
||||
}
|
||||
b = b.min(-self.nodes[i as usize].tr_cap);
|
||||
let bi = b as i32;
|
||||
self.arcs[(middle ^ 1) as usize].r_cap += bi;
|
||||
self.arcs[middle as usize].r_cap -= bi;
|
||||
// Source side.
|
||||
let mut i = self.arcs[(middle ^ 1) as usize].head;
|
||||
loop {
|
||||
let a = self.nodes[i as usize].parent;
|
||||
if a == TERMINAL {
|
||||
break;
|
||||
}
|
||||
self.arcs[a as usize].r_cap += bi;
|
||||
self.arcs[(a ^ 1) as usize].r_cap -= bi;
|
||||
if self.arcs[(a ^ 1) as usize].r_cap == 0 {
|
||||
self.make_orphan(i);
|
||||
}
|
||||
i = self.arcs[a as usize].head;
|
||||
}
|
||||
self.nodes[i as usize].tr_cap -= b;
|
||||
if self.nodes[i as usize].tr_cap == 0 {
|
||||
self.make_orphan(i);
|
||||
}
|
||||
// Sink side.
|
||||
let mut i = self.arcs[middle as usize].head;
|
||||
loop {
|
||||
let a = self.nodes[i as usize].parent;
|
||||
if a == TERMINAL {
|
||||
break;
|
||||
}
|
||||
self.arcs[(a ^ 1) as usize].r_cap += bi;
|
||||
self.arcs[a as usize].r_cap -= bi;
|
||||
if self.arcs[a as usize].r_cap == 0 {
|
||||
self.make_orphan(i);
|
||||
}
|
||||
i = self.arcs[a as usize].head;
|
||||
}
|
||||
self.nodes[i as usize].tr_cap += b;
|
||||
if self.nodes[i as usize].tr_cap == 0 {
|
||||
self.make_orphan(i);
|
||||
}
|
||||
self.flow += b;
|
||||
}
|
||||
|
||||
fn make_orphan(&mut self, i: u32) {
|
||||
self.nodes[i as usize].parent = ORPHAN;
|
||||
self.orphans.push_back(i);
|
||||
}
|
||||
|
||||
/// Whether node `j`'s path to its terminal is intact; returns its distance (marking the
|
||||
/// path with the current time) or None.
|
||||
fn origin_dist(&mut self, j: u32) -> Option<u32> {
|
||||
let mut d = 0u32;
|
||||
let mut k = j;
|
||||
loop {
|
||||
let n = self.nodes[k as usize];
|
||||
if n.ts == self.time {
|
||||
d += n.dist;
|
||||
break;
|
||||
}
|
||||
let a = n.parent;
|
||||
d += 1;
|
||||
if a == TERMINAL {
|
||||
let n = &mut self.nodes[k as usize];
|
||||
n.ts = self.time;
|
||||
n.dist = 1;
|
||||
break;
|
||||
}
|
||||
if a == ORPHAN || a == NONE {
|
||||
return None;
|
||||
}
|
||||
k = self.arcs[a as usize].head;
|
||||
}
|
||||
// Mark the path.
|
||||
let total = d;
|
||||
let mut k = j;
|
||||
let mut dd = d;
|
||||
while self.nodes[k as usize].ts != self.time {
|
||||
let n = &mut self.nodes[k as usize];
|
||||
n.ts = self.time;
|
||||
n.dist = dd;
|
||||
dd -= 1;
|
||||
k = self.arcs[n.parent as usize].head;
|
||||
}
|
||||
Some(total)
|
||||
}
|
||||
|
||||
fn adopt(&mut self) {
|
||||
while let Some(i) = self.orphans.pop_front() {
|
||||
let sink = self.nodes[i as usize].is_sink;
|
||||
let mut best = NONE;
|
||||
let mut best_d = u32::MAX;
|
||||
let mut a = self.nodes[i as usize].first;
|
||||
while a != NONE {
|
||||
let arc = self.arcs[a as usize];
|
||||
// S orphan: the parent must push flow into i (residual on j→i = sister of i→j).
|
||||
// T orphan: i must push flow into the parent (residual on i→j).
|
||||
let cap = if sink { arc.r_cap } else { self.arcs[(a ^ 1) as usize].r_cap };
|
||||
if cap > 0 {
|
||||
let j = arc.head;
|
||||
let nj = self.nodes[j as usize];
|
||||
if nj.is_sink == sink
|
||||
&& nj.parent != NONE
|
||||
&& let Some(d) = self.origin_dist(j)
|
||||
&& d < best_d
|
||||
{
|
||||
best = a;
|
||||
best_d = d;
|
||||
}
|
||||
}
|
||||
a = arc.next;
|
||||
}
|
||||
if best != NONE {
|
||||
let n = &mut self.nodes[i as usize];
|
||||
n.parent = best;
|
||||
n.ts = self.time;
|
||||
n.dist = best_d + 1;
|
||||
continue;
|
||||
}
|
||||
// No parent: free the node; its children become orphans, neighbours that could
|
||||
// reach it become active.
|
||||
self.nodes[i as usize].ts = 0;
|
||||
let mut a = self.nodes[i as usize].first;
|
||||
while a != NONE {
|
||||
let arc = self.arcs[a as usize];
|
||||
let j = arc.head;
|
||||
let nj = self.nodes[j as usize];
|
||||
if nj.is_sink == sink && nj.parent != NONE {
|
||||
let cap = if sink { arc.r_cap } else { self.arcs[(a ^ 1) as usize].r_cap };
|
||||
if cap > 0 {
|
||||
self.set_active(j);
|
||||
}
|
||||
let pa = nj.parent;
|
||||
if pa != TERMINAL && pa != ORPHAN && self.arcs[pa as usize].head == i {
|
||||
self.make_orphan(j);
|
||||
}
|
||||
}
|
||||
a = arc.next;
|
||||
}
|
||||
self.nodes[i as usize].parent = NONE;
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of node `i` after [`Graph::maxflow`] (free nodes go to the sink).
|
||||
pub fn segment(&self, i: usize) -> Segment {
|
||||
let n = &self.nodes[i];
|
||||
if n.parent != NONE && !n.is_sink { Segment::Source } else { Segment::Sink }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Brute-force min cut over all labelings of a small graph.
|
||||
fn brute(n: usize, t: &[(i64, i64)], e: &[(usize, usize, i32, i32)]) -> i64 {
|
||||
let mut best = i64::MAX;
|
||||
for m in 0..(1u32 << n) {
|
||||
let src = |i: usize| m & (1 << i) != 0;
|
||||
let mut c = 0i64;
|
||||
for (i, (s, k)) in t.iter().enumerate() {
|
||||
c += if src(i) { *k } else { *s };
|
||||
}
|
||||
for (i, j, a, b) in e {
|
||||
if src(*i) && !src(*j) {
|
||||
c += *a as i64;
|
||||
}
|
||||
if src(*j) && !src(*i) {
|
||||
c += *b as i64;
|
||||
}
|
||||
}
|
||||
best = best.min(c);
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_brute_force_on_random_graphs() {
|
||||
let mut s = 12345u64;
|
||||
let mut rnd = |m: u64| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 7;
|
||||
s ^= s << 17;
|
||||
s % m
|
||||
};
|
||||
for _ in 0..300 {
|
||||
let n = 2 + rnd(9) as usize;
|
||||
let t: Vec<(i64, i64)> = (0..n).map(|_| (rnd(20) as i64, rnd(20) as i64)).collect();
|
||||
let mut e = vec![];
|
||||
for _ in 0..rnd(20) {
|
||||
let (i, j) = (rnd(n as u64) as usize, rnd(n as u64) as usize);
|
||||
if i != j {
|
||||
e.push((i, j, rnd(15) as i32, rnd(15) as i32));
|
||||
}
|
||||
}
|
||||
let mut g = Graph::new(n, e.len());
|
||||
for (i, (a, b)) in t.iter().enumerate() {
|
||||
g.add_tweights(i, *a, *b);
|
||||
}
|
||||
for (i, j, a, b) in &e {
|
||||
g.add_edge(*i, *j, *a, *b);
|
||||
}
|
||||
let f = g.maxflow();
|
||||
assert_eq!(f, brute(n, &t, &e));
|
||||
// The labeling realises the cut.
|
||||
let src = |i: usize| g.segment(i) == Segment::Source;
|
||||
let mut c = 0i64;
|
||||
for (i, (a, b)) in t.iter().enumerate() {
|
||||
c += if src(i) { *b } else { *a };
|
||||
}
|
||||
for (i, j, a, b) in &e {
|
||||
if src(*i) && !src(*j) {
|
||||
c += *a as i64;
|
||||
}
|
||||
if src(*j) && !src(*i) {
|
||||
c += *b as i64;
|
||||
}
|
||||
}
|
||||
assert_eq!(c, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,754 @@
|
||||
//! Roto Brush segmentation and propagation, clean-room from published methods:
|
||||
//!
|
||||
//! - **Interactive graph-cut segmentation** (Y. Boykov and M.-P. Jolly, "Interactive Graph Cuts
|
||||
//! for Optimal Boundary & Region Segmentation of Objects in N-D Images", ICCV 2001): the user's
|
||||
//! foreground / background strokes are hard constraints, every other pixel gets a data cost
|
||||
//! from colour models and neighbouring pixels a contrast-sensitive smoothness cost; the
|
||||
//! minimum s–t cut ([`maxflow`], Boykov–Kolmogorov) is the segmentation.
|
||||
//! - **Iterated colour models** (C. Rother, V. Kolmogorov and A. Blake, "GrabCut", SIGGRAPH
|
||||
//! 2004): Gaussian mixtures ([`gmm`]) are fitted to the strokes, then re-fitted to the
|
||||
//! segmentation and the cut repeated; the 8-connected n-link weight is
|
||||
//! `γ/dist · exp(−β‖Iₚ − I_q‖²)` with `β = 1 / (2⟨‖Iₚ − I_q‖²⟩)`.
|
||||
//! - **Coarse to fine**: large frames are segmented at a reduced size, then re-cut at full
|
||||
//! resolution in a narrow band around the upsampled boundary (Lombaert et al., "A Multilevel
|
||||
//! Banded Graph Cuts Method for Fast Image Segmentation", ICCV 2005).
|
||||
//! - **Propagation** (in the spirit of X. Bai et al., "Video SnapCut", SIGGRAPH 2009): the
|
||||
//! previous frame's matte is warped to the next frame by optical flow
|
||||
//! (`effectcraft_raster::flow::block_flow`), and the frame re-segmented by graph cut only in a
|
||||
//! band of **Search Radius** pixels around the warped boundary, with the previous frame's
|
||||
//! colour models and the warped matte as a shape prior. Correction strokes on a frame re-cut
|
||||
//! the whole frame with the warped matte as a soft prior, and propagation restarts from there.
|
||||
//!
|
||||
//! Mattes are in layer pixels at a given scale (1 = full resolution). Strokes are stored in
|
||||
//! layer pixels ([`RotoData`], serde) and keyed per frame so that each frame's result is a
|
||||
//! deterministic function of its *chain*: the base frame's strokes, then every frame's strokes
|
||||
//! on the way out to it ([`RotoData::chain_keys`]).
|
||||
|
||||
pub mod gmm;
|
||||
pub mod matting;
|
||||
pub mod maxflow;
|
||||
pub mod refine;
|
||||
pub mod rle;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use gmm::Gmm;
|
||||
use maxflow::{Graph, Segment};
|
||||
|
||||
/// What a stroke paints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum StrokeKind {
|
||||
/// Roto Brush (green): foreground.
|
||||
Fg,
|
||||
/// Roto Brush with Alt (red): background.
|
||||
Bg,
|
||||
/// Refine Edge tool: mark a band for edge matting.
|
||||
Refine,
|
||||
/// Refine Edge tool with Alt: remove from the band.
|
||||
RefineErase,
|
||||
}
|
||||
|
||||
impl StrokeKind {
|
||||
pub fn from_name(s: &str) -> Option<StrokeKind> {
|
||||
Some(match s.to_ascii_lowercase().as_str() {
|
||||
"fg" | "foreground" => StrokeKind::Fg,
|
||||
"bg" | "background" => StrokeKind::Bg,
|
||||
"refine" | "refineedge" => StrokeKind::Refine,
|
||||
"refineerase" | "refine-erase" | "erase" => StrokeKind::RefineErase,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn is_segmentation(self) -> bool {
|
||||
matches!(self, StrokeKind::Fg | StrokeKind::Bg)
|
||||
}
|
||||
}
|
||||
|
||||
/// One stroke: a polyline swept by a disc of `radius` layer pixels, on layer frame `frame`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Stroke {
|
||||
pub kind: StrokeKind,
|
||||
pub frame: i64,
|
||||
pub radius: f64,
|
||||
pub points: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// A Roto Brush instance's user data: strokes, the base frame and the segmentation span
|
||||
/// (inclusive layer frames).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RotoData {
|
||||
pub base: Option<i64>,
|
||||
pub span: [i64; 2],
|
||||
pub strokes: Vec<Stroke>,
|
||||
}
|
||||
|
||||
fn fnv(h: &mut u64, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
*h ^= *b as u64;
|
||||
*h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
impl RotoData {
|
||||
pub fn from_json(s: &str) -> RotoData {
|
||||
if s.trim().is_empty() {
|
||||
return RotoData::default();
|
||||
}
|
||||
serde_json::from_str(s).unwrap_or_default()
|
||||
}
|
||||
pub fn to_json(&self) -> String {
|
||||
serde_json::to_string(self).unwrap_or_default()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.base.is_none() || !self.strokes.iter().any(|s| s.kind.is_segmentation())
|
||||
}
|
||||
pub fn strokes_at(&self, frame: i64) -> Vec<&Stroke> {
|
||||
self.strokes.iter().filter(|s| s.frame == frame).collect()
|
||||
}
|
||||
/// Frames that carry strokes.
|
||||
pub fn stroke_frames(&self) -> Vec<i64> {
|
||||
let mut v: Vec<i64> = self.strokes.iter().map(|s| s.frame).collect();
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
pub fn in_span(&self, f: i64) -> bool {
|
||||
self.base.is_some() && f >= self.span[0] && f <= self.span[1]
|
||||
}
|
||||
/// Add a stroke: the first segmentation stroke sets the base frame and a span of
|
||||
/// `default_span` frames each side (clamped to `limits`); strokes outside the span extend it.
|
||||
pub fn add(&mut self, s: Stroke, default_span: i64, limits: [i64; 2]) {
|
||||
let f = s.frame;
|
||||
match self.base {
|
||||
None if s.kind.is_segmentation() => {
|
||||
self.base = Some(f);
|
||||
self.span = [(f - default_span).max(limits[0]), (f + default_span).min(limits[1]).max(f)];
|
||||
}
|
||||
Some(_) => {
|
||||
self.span[0] = self.span[0].min(f);
|
||||
self.span[1] = self.span[1].max(f);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
self.strokes.push(s);
|
||||
}
|
||||
/// Largest Refine Edge stroke radius (layer pixels).
|
||||
pub fn refine_radius(&self) -> f64 {
|
||||
self.strokes.iter().filter(|s| matches!(s.kind, StrokeKind::Refine)).map(|s| s.radius).fold(0.0, f64::max)
|
||||
}
|
||||
/// Content key of every frame in the span: the base frame's from `seed` (what the frames
|
||||
/// and settings are) and its strokes, every other frame's from its neighbour towards the
|
||||
/// base and its own strokes.
|
||||
pub fn chain_keys(&self, seed: u64) -> BTreeMap<i64, u64> {
|
||||
let mut out = BTreeMap::new();
|
||||
let Some(base) = self.base else { return out };
|
||||
let key = |prev: u64, f: i64| {
|
||||
let mut h = prev ^ 0x9e37_79b9_7f4a_7c15;
|
||||
fnv(&mut h, &f.to_le_bytes());
|
||||
for s in self.strokes.iter().filter(|s| s.frame == f) {
|
||||
fnv(&mut h, serde_json::to_string(s).unwrap_or_default().as_bytes());
|
||||
}
|
||||
h
|
||||
};
|
||||
let k0 = key(seed, base);
|
||||
out.insert(base, k0);
|
||||
let mut k = k0;
|
||||
for f in base + 1..=self.span[1] {
|
||||
k = key(k, f);
|
||||
out.insert(f, k);
|
||||
}
|
||||
k = k0;
|
||||
for f in (self.span[0]..base).rev() {
|
||||
k = key(k, f);
|
||||
out.insert(f, k);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The neighbour a frame is propagated from (None for the base frame and outside the span).
|
||||
pub fn source_of(&self, f: i64) -> Option<i64> {
|
||||
let base = self.base?;
|
||||
if !self.in_span(f) || f == base {
|
||||
return None;
|
||||
}
|
||||
Some(if f > base { f - 1 } else { f + 1 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Segmentation settings (the effect's Roto Brush parameters, in frame pixels).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SegOpts {
|
||||
/// Pixels of the matte per layer pixel.
|
||||
pub scale: f64,
|
||||
/// Search Radius (layer pixels).
|
||||
pub search_radius: f64,
|
||||
/// Motion Threshold / Motion Damping, percent.
|
||||
pub motion_threshold: f64,
|
||||
pub motion_damping: f64,
|
||||
/// Quality ▸ Best.
|
||||
pub best: bool,
|
||||
}
|
||||
|
||||
impl Default for SegOpts {
|
||||
fn default() -> Self {
|
||||
SegOpts { scale: 1.0, search_radius: 15.0, motion_threshold: 10.0, motion_damping: 20.0, best: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame's segmentation: the binary matte, the Refine Edge band and the colour models.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct FrameSeg {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub matte: Vec<u8>,
|
||||
pub refine: Vec<u8>,
|
||||
pub fg: Gmm,
|
||||
pub bg: Gmm,
|
||||
}
|
||||
|
||||
impl FrameSeg {
|
||||
pub fn empty(w: usize, h: usize) -> FrameSeg {
|
||||
FrameSeg { w, h, matte: vec![0; w * h], refine: vec![0; w * h], ..Default::default() }
|
||||
}
|
||||
pub fn area(&self) -> usize {
|
||||
self.matte.iter().filter(|v| **v != 0).count()
|
||||
}
|
||||
/// Centroid of the matte (pixels), if any.
|
||||
pub fn centroid(&self) -> Option<[f64; 2]> {
|
||||
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
|
||||
for (i, v) in self.matte.iter().enumerate() {
|
||||
if *v != 0 {
|
||||
sx += (i % self.w) as f64 + 0.5;
|
||||
sy += (i / self.w) as f64 + 0.5;
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
(n > 0.0).then(|| [sx / n, sy / n])
|
||||
}
|
||||
}
|
||||
|
||||
/// Straight RGB of an image (transparent pixels are black).
|
||||
pub fn rgb_of(img: &Image) -> Vec<[f32; 3]> {
|
||||
img.data.par_iter().map(|p| if p[3] > 1e-6 { [p[0] / p[3], p[1] / p[3], p[2] / p[3]] } else { [0.0; 3] }).collect()
|
||||
}
|
||||
|
||||
/// Pixels covered by `strokes` (of the given kinds) at `scale`.
|
||||
pub fn rasterize(strokes: &[&Stroke], kinds: &[StrokeKind], scale: f64, w: usize, h: usize) -> Vec<bool> {
|
||||
let mut m = vec![false; w * h];
|
||||
for s in strokes.iter().filter(|s| kinds.contains(&s.kind)) {
|
||||
let r = (s.radius * scale).max(0.5);
|
||||
let pts: Vec<[f64; 2]> = s.points.iter().map(|p| [p[0] * scale, p[1] * scale]).collect();
|
||||
let segs: Vec<([f64; 2], [f64; 2])> = if pts.len() == 1 { vec![(pts[0], pts[0])] } else { pts.windows(2).map(|w| (w[0], w[1])).collect() };
|
||||
for (a, b) in segs {
|
||||
let x0 = (a[0].min(b[0]) - r).floor().max(0.0) as usize;
|
||||
let x1 = ((a[0].max(b[0]) + r).ceil().max(0.0) as usize).min(w);
|
||||
let y0 = (a[1].min(b[1]) - r).floor().max(0.0) as usize;
|
||||
let y1 = ((a[1].max(b[1]) + r).ceil().max(0.0) as usize).min(h);
|
||||
let d = [b[0] - a[0], b[1] - a[1]];
|
||||
let l2 = d[0] * d[0] + d[1] * d[1];
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let p = [x as f64 + 0.5, y as f64 + 0.5];
|
||||
let t = if l2 > 0.0 { (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let q = [a[0] + d[0] * t, a[1] + d[1] * t];
|
||||
if (p[0] - q[0]).hypot(p[1] - q[1]) <= r {
|
||||
m[y * w + x] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Hard constraints: 1 = foreground, 2 = background, 0 = free.
|
||||
const HARD_FG: u8 = 1;
|
||||
const HARD_BG: u8 = 2;
|
||||
|
||||
/// Graph-cut energy weights.
|
||||
const GAMMA: f64 = 50.0;
|
||||
const PRIOR: f64 = 1.0;
|
||||
/// Fixed-point scale of the energies.
|
||||
const K: f64 = 16.0;
|
||||
const INF: i64 = 1 << 40;
|
||||
|
||||
const NB: [(i64, i64, bool); 8] = [(1, 0, true), (0, 1, true), (1, 1, true), (-1, 1, true), (-1, 0, false), (0, -1, false), (-1, -1, false), (1, -1, false)];
|
||||
|
||||
fn beta(img: &[[f32; 3]], free: &[bool], w: usize, h: usize) -> f64 {
|
||||
let (mut s, mut n) = (0.0f64, 0.0f64);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = y * w + x;
|
||||
if !free[i] {
|
||||
continue;
|
||||
}
|
||||
let c = img[i];
|
||||
for (dx, dy) in [(1usize, 0usize), (0, 1)] {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx < w && ny < h {
|
||||
let q = img[ny * w + nx];
|
||||
s += ((c[0] - q[0]).powi(2) + (c[1] - q[1]).powi(2) + (c[2] - q[2]).powi(2)) as f64;
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if s <= 1e-12 { 1.0 } else { n / (2.0 * s) }
|
||||
}
|
||||
|
||||
/// One min-cut over the `free` pixels; others keep `labels`. `prior`: P(foreground) per pixel.
|
||||
fn cut(img: &[[f32; 3]], w: usize, h: usize, labels: &mut [u8], free: &[bool], hard: &[u8], fg: &Gmm, bg: &Gmm, prior: Option<&[f32]>) {
|
||||
let mut idx = vec![u32::MAX; w * h];
|
||||
let mut nodes = vec![];
|
||||
for i in 0..w * h {
|
||||
if free[i] {
|
||||
idx[i] = nodes.len() as u32;
|
||||
nodes.push(i);
|
||||
}
|
||||
}
|
||||
if nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let b = beta(img, free, w, h);
|
||||
let costs: Vec<(f64, f64)> = nodes
|
||||
.par_iter()
|
||||
.map(|&i| {
|
||||
let c = img[i];
|
||||
let (mut cf, mut cb) = (fg.cost(c), bg.cost(c));
|
||||
if let Some(p) = prior {
|
||||
let pf = (p[i] as f64).clamp(0.02, 0.98);
|
||||
cf += PRIOR * -pf.ln();
|
||||
cb += PRIOR * -(1.0 - pf).ln();
|
||||
}
|
||||
(cf, cb)
|
||||
})
|
||||
.collect();
|
||||
let mut g = Graph::new(nodes.len(), nodes.len() * 4);
|
||||
for (n, &i) in nodes.iter().enumerate() {
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
let (cf, cb) = costs[n];
|
||||
let m = cf.min(cb);
|
||||
let (mut src, mut snk) = (((cb - m) * K).round() as i64, ((cf - m) * K).round() as i64);
|
||||
match hard[i] {
|
||||
HARD_FG => (src, snk) = (INF, 0),
|
||||
HARD_BG => (src, snk) = (0, INF),
|
||||
_ => {}
|
||||
}
|
||||
g.add_tweights(n, src, snk);
|
||||
let c = img[i];
|
||||
for (dx, dy, fwd) in NB {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
let j = ny as usize * w + nx as usize;
|
||||
let q = img[j];
|
||||
let d2 = ((c[0] - q[0]).powi(2) + (c[1] - q[1]).powi(2) + (c[2] - q[2]).powi(2)) as f64;
|
||||
let dist = if dx != 0 && dy != 0 { std::f64::consts::SQRT_2 } else { 1.0 };
|
||||
let wt = ((GAMMA / dist * (-b * d2).exp()) * K).round() as i32;
|
||||
if wt <= 0 {
|
||||
continue;
|
||||
}
|
||||
if idx[j] == u32::MAX {
|
||||
// Fixed neighbour: disagreeing with it costs the edge.
|
||||
if labels[j] != 0 {
|
||||
g.add_tweights(n, wt as i64, 0);
|
||||
} else {
|
||||
g.add_tweights(n, 0, wt as i64);
|
||||
}
|
||||
} else if fwd {
|
||||
g.add_edge(n, idx[j] as usize, wt, wt);
|
||||
}
|
||||
}
|
||||
}
|
||||
g.maxflow();
|
||||
for (n, &i) in nodes.iter().enumerate() {
|
||||
labels[i] = (g.segment(n) == Segment::Source) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour samples of the pixels where `sel` holds.
|
||||
fn samples(img: &[[f32; 3]], sel: impl Fn(usize) -> bool) -> Vec<[f32; 3]> {
|
||||
img.iter().enumerate().filter(|(i, _)| sel(*i)).map(|(_, c)| *c).collect()
|
||||
}
|
||||
|
||||
const COMPONENTS: usize = 5;
|
||||
const MAX_SAMPLES: usize = 24_000;
|
||||
|
||||
fn fit_models(img: &[[f32; 3]], labels: &[u8]) -> (Gmm, Gmm) {
|
||||
let fg = samples(img, |i| labels[i] != 0);
|
||||
let bg = samples(img, |i| labels[i] == 0);
|
||||
(Gmm::fit(&fg, COMPONENTS, MAX_SAMPLES), Gmm::fit(&bg, COMPONENTS, MAX_SAMPLES))
|
||||
}
|
||||
|
||||
/// Keep the foreground components (8-connected) that touch `seeds`; fill small background
|
||||
/// holes that touch neither the frame edge nor a background seed.
|
||||
fn clean(labels: &mut [u8], seeds: &[bool], bg_seeds: &[bool], w: usize, h: usize) {
|
||||
let n = w * h;
|
||||
let mut comp = vec![u32::MAX; n];
|
||||
let mut stack = vec![];
|
||||
let mut fg_area = 0usize;
|
||||
for start in 0..n {
|
||||
if comp[start] != u32::MAX {
|
||||
continue;
|
||||
}
|
||||
let lab = labels[start];
|
||||
let id = start as u32;
|
||||
comp[start] = id;
|
||||
stack.push(start);
|
||||
let mut members = vec![];
|
||||
let (mut seeded, mut edge, mut bgs) = (false, false, false);
|
||||
while let Some(i) = stack.pop() {
|
||||
members.push(i);
|
||||
seeded |= seeds[i];
|
||||
bgs |= bg_seeds[i];
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
edge |= x == 0 || y == 0 || x == w as i64 - 1 || y == h as i64 - 1;
|
||||
for (dx, dy, _) in NB {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
let j = ny as usize * w + nx as usize;
|
||||
if comp[j] == u32::MAX && labels[j] == lab {
|
||||
comp[j] = id;
|
||||
stack.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
if lab != 0 {
|
||||
if seeded {
|
||||
fg_area += members.len();
|
||||
} else {
|
||||
for i in members {
|
||||
labels[i] = 0;
|
||||
}
|
||||
}
|
||||
} else if !edge && !bgs {
|
||||
// Remember holes as negative candidates (resolved below once fg_area is known).
|
||||
for i in members {
|
||||
comp[i] = u32::MAX - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fill holes smaller than 2 % of the foreground.
|
||||
let mut seen = vec![false; n];
|
||||
for start in 0..n {
|
||||
if comp[start] != u32::MAX - 1 || seen[start] || labels[start] != 0 {
|
||||
continue;
|
||||
}
|
||||
let mut members = vec![start];
|
||||
seen[start] = true;
|
||||
let mut k = 0;
|
||||
while k < members.len() {
|
||||
let i = members[k];
|
||||
k += 1;
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
for (dx, dy, _) in NB {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
let j = ny as usize * w + nx as usize;
|
||||
if !seen[j] && comp[j] == u32::MAX - 1 && labels[j] == 0 {
|
||||
seen[j] = true;
|
||||
members.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A hole is enclosed by foreground that survived the component filter.
|
||||
let enclosed = members.iter().all(|&i| {
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
NB.iter().all(|(dx, dy, _)| {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
|
||||
return false;
|
||||
}
|
||||
let j = ny as usize * w + nx as usize;
|
||||
labels[j] != 0 || comp[j] == u32::MAX - 1
|
||||
})
|
||||
});
|
||||
if enclosed && (members.len() as f64) < 0.02 * fg_area as f64 {
|
||||
for i in members {
|
||||
labels[i] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn downsample_rgb(img: &[[f32; 3]], w: usize, h: usize, f: usize) -> (Vec<[f32; 3]>, usize, usize) {
|
||||
let (cw, ch) = (w.div_ceil(f), h.div_ceil(f));
|
||||
let out = (0..cw * ch)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let (cx, cy) = (i % cw, i / cw);
|
||||
let mut s = [0.0f32; 3];
|
||||
let mut n = 0.0;
|
||||
for y in cy * f..((cy + 1) * f).min(h) {
|
||||
for x in cx * f..((cx + 1) * f).min(w) {
|
||||
let c = img[y * w + x];
|
||||
s[0] += c[0];
|
||||
s[1] += c[1];
|
||||
s[2] += c[2];
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
[s[0] / n, s[1] / n, s[2] / n]
|
||||
})
|
||||
.collect();
|
||||
(out, cw, ch)
|
||||
}
|
||||
|
||||
/// What a frame is segmented with besides its strokes: the matte propagated from its neighbour.
|
||||
pub struct Prior {
|
||||
/// Warped neighbour matte, soft (0–1).
|
||||
pub soft: Vec<f32>,
|
||||
/// The neighbour's colour models.
|
||||
pub fg: Gmm,
|
||||
pub bg: Gmm,
|
||||
/// Warped Refine Edge band.
|
||||
pub refine: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Segment a frame from its strokes (and a propagated prior): GrabCut iterations on a reduced
|
||||
/// copy, then a full-resolution cut in a band around the boundary.
|
||||
pub fn segment(img: &Image, strokes: &[&Stroke], prior: Option<&Prior>, opts: &SegOpts, refine_radius: f64) -> FrameSeg {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
if w == 0 || h == 0 {
|
||||
return FrameSeg::empty(w, h);
|
||||
}
|
||||
let rgb = rgb_of(img);
|
||||
let fgs = rasterize(strokes, &[StrokeKind::Fg], opts.scale, w, h);
|
||||
let bgs = rasterize(strokes, &[StrokeKind::Bg], opts.scale, w, h);
|
||||
let hard: Vec<u8> = fgs
|
||||
.iter()
|
||||
.zip(&bgs)
|
||||
.map(|(f, b)| {
|
||||
if *b {
|
||||
HARD_BG
|
||||
} else if *f {
|
||||
HARD_FG
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let soft_prior: Option<Vec<f32>> = prior.map(|p| matting::gauss(&p.soft, w, h, (opts.search_radius * opts.scale / 4.0).max(1.0)));
|
||||
// Initial colour models: the strokes (and the propagated matte).
|
||||
let (fg0, bg0) = match prior {
|
||||
Some(p) => {
|
||||
let fgc = samples(&rgb, |i| (hard[i] == HARD_FG) || (hard[i] == 0 && p.soft[i] >= 0.5));
|
||||
let bgc = samples(&rgb, |i| (hard[i] == HARD_BG) || (hard[i] == 0 && p.soft[i] < 0.5));
|
||||
let f = Gmm::fit(&fgc, COMPONENTS, MAX_SAMPLES);
|
||||
let b = Gmm::fit(&bgc, COMPONENTS, MAX_SAMPLES);
|
||||
(if f.is_empty() { p.fg.clone() } else { f }, if b.is_empty() { p.bg.clone() } else { b })
|
||||
}
|
||||
None => {
|
||||
let fgc = samples(&rgb, |i| hard[i] == HARD_FG);
|
||||
let mut bgc = samples(&rgb, |i| hard[i] == HARD_BG);
|
||||
if bgc.is_empty() {
|
||||
// No background strokes: what is far from the foreground strokes.
|
||||
let d = matting::distance(&fgs, w, h);
|
||||
let r = strokes.iter().filter(|s| s.kind == StrokeKind::Fg).map(|s| s.radius).fold(1.0, f64::max) * opts.scale;
|
||||
let far = (4.0 * r).max(0.25 * w.max(h) as f64) as f32;
|
||||
bgc = samples(&rgb, |i| d[i] > far);
|
||||
if bgc.is_empty() {
|
||||
bgc = samples(&rgb, |i| hard[i] != HARD_FG);
|
||||
}
|
||||
}
|
||||
(Gmm::fit(&fgc, COMPONENTS, MAX_SAMPLES), Gmm::fit(&bgc, COMPONENTS, MAX_SAMPLES))
|
||||
}
|
||||
};
|
||||
let iters = if opts.best { 4 } else { 3 };
|
||||
let work = if opts.best { 960 } else { 480 };
|
||||
let f = w.max(h).div_ceil(work).max(1);
|
||||
let mut labels: Vec<u8> = match &soft_prior {
|
||||
Some(p) => p.iter().map(|v| (*v >= 0.5) as u8).collect(),
|
||||
None => fgs.iter().map(|v| *v as u8).collect(),
|
||||
};
|
||||
for (l, hd) in labels.iter_mut().zip(&hard) {
|
||||
if *hd != 0 {
|
||||
*l = (*hd == HARD_FG) as u8;
|
||||
}
|
||||
}
|
||||
let (mut fgm, mut bgm) = (fg0, bg0);
|
||||
if f > 1 {
|
||||
let (crgb, cw, ch) = downsample_rgb(&rgb, w, h, f);
|
||||
let mut chard = vec![0u8; cw * ch];
|
||||
let mut cprior = soft_prior.as_ref().map(|_| vec![0.0f32; cw * ch]);
|
||||
for cy in 0..ch {
|
||||
for cx in 0..cw {
|
||||
let (mut anyf, mut anyb, mut s, mut n) = (false, false, 0.0f32, 0.0f32);
|
||||
for y in cy * f..((cy + 1) * f).min(h) {
|
||||
for x in cx * f..((cx + 1) * f).min(w) {
|
||||
let i = y * w + x;
|
||||
anyf |= hard[i] == HARD_FG;
|
||||
anyb |= hard[i] == HARD_BG;
|
||||
if let Some(p) = &soft_prior {
|
||||
s += p[i];
|
||||
}
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
chard[cy * cw + cx] = match (anyf, anyb) {
|
||||
(true, false) => HARD_FG,
|
||||
(false, true) => HARD_BG,
|
||||
_ => 0,
|
||||
};
|
||||
if let Some(cp) = &mut cprior {
|
||||
cp[cy * cw + cx] = s / n;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut cl: Vec<u8> = match &cprior {
|
||||
Some(p) => p.iter().map(|v| (*v >= 0.5) as u8).collect(),
|
||||
None => chard.iter().map(|v| (*v == HARD_FG) as u8).collect(),
|
||||
};
|
||||
let free = vec![true; cw * ch];
|
||||
for it in 0..iters {
|
||||
cut(&crgb, cw, ch, &mut cl, &free, &chard, &fgm, &bgm, cprior.as_deref());
|
||||
if it + 1 < iters {
|
||||
let (a, b) = fit_models(&crgb, &cl);
|
||||
if !a.is_empty() && !b.is_empty() {
|
||||
(fgm, bgm) = (a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = y * w + x;
|
||||
labels[i] = if hard[i] != 0 { (hard[i] == HARD_FG) as u8 } else { cl[(y / f) * cw + x / f] };
|
||||
}
|
||||
}
|
||||
let (a, b) = fit_models(&rgb, &labels);
|
||||
if !a.is_empty() && !b.is_empty() {
|
||||
(fgm, bgm) = (a, b);
|
||||
}
|
||||
// Full-resolution band.
|
||||
let sd = matting::signed_distance(&labels, w, h);
|
||||
let band = f as f32 + 1.5;
|
||||
let free: Vec<bool> = sd.iter().map(|d| d.abs() <= band).collect();
|
||||
cut(&rgb, w, h, &mut labels, &free, &hard, &fgm, &bgm, soft_prior.as_deref());
|
||||
} else {
|
||||
let free = vec![true; w * h];
|
||||
for it in 0..iters {
|
||||
cut(&rgb, w, h, &mut labels, &free, &hard, &fgm, &bgm, soft_prior.as_deref());
|
||||
if it + 1 < iters {
|
||||
let (a, b) = fit_models(&rgb, &labels);
|
||||
if !a.is_empty() && !b.is_empty() {
|
||||
(fgm, bgm) = (a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Keep what the strokes (or the prior's core) select.
|
||||
let mut seeds = fgs.clone();
|
||||
if let Some(p) = &soft_prior {
|
||||
let core = core_of(p, w, h, opts.search_radius * opts.scale);
|
||||
for (s, c) in seeds.iter_mut().zip(core) {
|
||||
*s |= c;
|
||||
}
|
||||
}
|
||||
clean(&mut labels, &seeds, &bgs, w, h);
|
||||
finish(img, &rgb, labels, strokes, prior.map(|p| p.refine.as_slice()), opts, refine_radius)
|
||||
}
|
||||
|
||||
/// Pixels deep inside a soft matte (more than `r` from its edge), else the matte itself.
|
||||
fn core_of(soft: &[f32], w: usize, h: usize, r: f64) -> Vec<bool> {
|
||||
let bin: Vec<u8> = soft.iter().map(|v| (*v >= 0.5) as u8).collect();
|
||||
let sd = matting::signed_distance(&bin, w, h);
|
||||
let core: Vec<bool> = sd.iter().map(|d| *d as f64 > r).collect();
|
||||
if core.iter().any(|c| *c) { core } else { bin.iter().map(|v| *v != 0).collect() }
|
||||
}
|
||||
|
||||
/// Final models and Refine Edge band of a segmented frame.
|
||||
fn finish(_img: &Image, rgb: &[[f32; 3]], labels: Vec<u8>, strokes: &[&Stroke], warped_refine: Option<&[u8]>, opts: &SegOpts, refine_radius: f64) -> FrameSeg {
|
||||
let (w, h) = (_img.width as usize, _img.height as usize);
|
||||
let (fg, bg) = fit_models(rgb, &labels);
|
||||
let add = rasterize(strokes, &[StrokeKind::Refine], opts.scale, w, h);
|
||||
let erase = rasterize(strokes, &[StrokeKind::RefineErase], opts.scale, w, h);
|
||||
let near: Option<Vec<f32>> = warped_refine.filter(|r| r.iter().any(|v| *v != 0)).map(|_| matting::signed_distance(&labels, w, h));
|
||||
let rr = (refine_radius * opts.scale + 2.0) as f32;
|
||||
let refine: Vec<u8> = (0..w * h)
|
||||
.map(|i| {
|
||||
let carried = match (warped_refine, &near) {
|
||||
(Some(r), Some(sd)) => r[i] != 0 && sd[i].abs() <= rr,
|
||||
_ => false,
|
||||
};
|
||||
((carried || add[i]) && !erase[i]) as u8
|
||||
})
|
||||
.collect();
|
||||
FrameSeg { w, h, matte: labels, refine, fg, bg }
|
||||
}
|
||||
|
||||
/// Warp the previous frame's segmentation onto the next frame by optical flow (next → prev),
|
||||
/// with Motion Threshold / Damping applied to the vectors.
|
||||
pub fn warp_prior(prev_img: &Image, prev: &FrameSeg, next_img: &Image, opts: &SegOpts) -> Prior {
|
||||
let (w, h) = (next_img.width as usize, next_img.height as usize);
|
||||
let flow = effectcraft_raster::flow::block_flow(next_img, prev_img, 8, 4);
|
||||
let thr = (opts.motion_threshold / 100.0 * opts.search_radius * opts.scale).max(0.0);
|
||||
let damp = (1.0 - opts.motion_damping / 100.0).clamp(0.0, 1.0);
|
||||
let src: Vec<f32> = prev.matte.iter().map(|v| *v as f32).collect();
|
||||
let pw = prev.w.min(w);
|
||||
let ph = prev.h.min(h);
|
||||
let res: Vec<(f32, u8)> = (0..w * h)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
|
||||
let v = flow.at(x, y);
|
||||
let (mut vx, mut vy) = (v[0] as f64, v[1] as f64);
|
||||
if vx.hypot(vy) < thr {
|
||||
vx *= damp;
|
||||
vy *= damp;
|
||||
}
|
||||
let (sx, sy) = (x + vx, y + vy);
|
||||
let soft = if pw == prev.w && ph == prev.h { matting::sample(&src, prev.w, prev.h, sx, sy) } else { 0.0 };
|
||||
let (ix, iy) = (sx.floor().clamp(0.0, (prev.w.max(1) - 1) as f64) as usize, sy.floor().clamp(0.0, (prev.h.max(1) - 1) as f64) as usize);
|
||||
let r = prev.refine.get(iy * prev.w + ix).copied().unwrap_or(0);
|
||||
(soft, r)
|
||||
})
|
||||
.collect();
|
||||
Prior { soft: res.iter().map(|r| r.0).collect(), fg: prev.fg.clone(), bg: prev.bg.clone(), refine: res.iter().map(|r| r.1).collect() }
|
||||
}
|
||||
|
||||
/// Propagate the previous frame's segmentation to the next frame: warp it, then re-cut in a
|
||||
/// band of Search Radius pixels around the warped boundary. Strokes on the next frame re-cut
|
||||
/// the whole frame with the warped matte as a soft prior instead.
|
||||
pub fn propagate(prev_img: &Image, prev: &FrameSeg, next_img: &Image, strokes: &[&Stroke], opts: &SegOpts, refine_radius: f64) -> FrameSeg {
|
||||
let (w, h) = (next_img.width as usize, next_img.height as usize);
|
||||
let prior = warp_prior(prev_img, prev, next_img, opts);
|
||||
if strokes.iter().any(|s| s.kind.is_segmentation()) {
|
||||
return segment(next_img, strokes, Some(&prior), opts, refine_radius);
|
||||
}
|
||||
let rgb = rgb_of(next_img);
|
||||
let mut labels: Vec<u8> = prior.soft.iter().map(|v| (*v >= 0.5) as u8).collect();
|
||||
let sd = matting::signed_distance(&labels, w, h);
|
||||
let r = (opts.search_radius * opts.scale).max(2.0) as f32;
|
||||
let free: Vec<bool> = sd.iter().map(|d| d.abs() <= r).collect();
|
||||
let hard = vec![0u8; w * h];
|
||||
let soft = matting::gauss(&prior.soft, w, h, (r as f64 / 4.0).max(1.0));
|
||||
let (fg, bg) = if prev.fg.is_empty() || prev.bg.is_empty() { fit_models(&rgb, &labels) } else { (prev.fg.clone(), prev.bg.clone()) };
|
||||
cut(&rgb, w, h, &mut labels, &free, &hard, &fg, &bg, Some(&soft));
|
||||
let seeds = core_of(&prior.soft, w, h, r as f64);
|
||||
clean(&mut labels, &seeds, &vec![false; w * h], w, h);
|
||||
finish(next_img, &rgb, labels, strokes, Some(&prior.refine), opts, refine_radius)
|
||||
}
|
||||
|
||||
/// Intersection over union of two binary mattes.
|
||||
pub fn iou(a: &[u8], b: &[u8]) -> f64 {
|
||||
let (mut i, mut u) = (0usize, 0usize);
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
let (x, y) = (*x != 0, *y != 0);
|
||||
i += (x && y) as usize;
|
||||
u += (x || y) as usize;
|
||||
}
|
||||
if u == 0 { 1.0 } else { i as f64 / u as f64 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,198 @@
|
||||
//! From a frame's binary segmentation to the final soft matte: the Roto Brush Matte and Refine
|
||||
//! Edge Matte adjustments, edge matting inside the Refine Edge band (colour guided filter),
|
||||
//! Reduce Chatter (temporal averaging with the neighbouring frames), matte motion blur and edge
|
||||
//! colour decontamination.
|
||||
|
||||
use super::FrameSeg;
|
||||
use super::matting::{self, contrast, gauss, guided_filter, shift_soft, signed_distance};
|
||||
|
||||
/// The effect's matte parameters (After Effects' units: pixels and percent).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MatteParams {
|
||||
// Roto Brush Matte.
|
||||
pub rb_feather: f64,
|
||||
pub rb_contrast: f64,
|
||||
pub rb_shift: f64,
|
||||
pub rb_chatter: f64,
|
||||
// Refine Edge Matte.
|
||||
pub smooth: f64,
|
||||
pub feather: f64,
|
||||
pub contrast: f64,
|
||||
pub shift: f64,
|
||||
pub chatter: f64,
|
||||
pub motion_blur: bool,
|
||||
pub mb_samples: usize,
|
||||
pub shutter_angle: f64,
|
||||
/// Higher Quality: closed-form matting after the guided-filter estimate.
|
||||
pub higher_quality: bool,
|
||||
pub decontaminate: bool,
|
||||
pub decontamination: f64,
|
||||
pub extend_where_smoothed: bool,
|
||||
pub increase_radius: f64,
|
||||
}
|
||||
|
||||
impl Default for MatteParams {
|
||||
fn default() -> Self {
|
||||
MatteParams {
|
||||
rb_feather: 0.0,
|
||||
rb_contrast: 0.0,
|
||||
rb_shift: 0.0,
|
||||
rb_chatter: 0.0,
|
||||
smooth: 1.0,
|
||||
feather: 0.0,
|
||||
contrast: 0.0,
|
||||
shift: 0.0,
|
||||
chatter: 0.0,
|
||||
motion_blur: false,
|
||||
mb_samples: 11,
|
||||
shutter_angle: 180.0,
|
||||
higher_quality: true,
|
||||
decontaminate: true,
|
||||
decontamination: 100.0,
|
||||
extend_where_smoothed: true,
|
||||
increase_radius: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shifted(seg: &FrameSeg, px: f64) -> Vec<f32> {
|
||||
if px.abs() < 0.25 {
|
||||
return seg.matte.iter().map(|v| *v as f32).collect();
|
||||
}
|
||||
let sd = signed_distance(&seg.matte, seg.w, seg.h);
|
||||
sd.iter().map(|d| ((*d as f64) > -px) as u8 as f32).collect()
|
||||
}
|
||||
|
||||
/// The soft matte of `seg` (all planes `seg.w × seg.h`), with `rgb` the frame's straight colour.
|
||||
/// `prev` / `next`: the neighbouring frames' segmentations (Reduce Chatter, motion blur).
|
||||
/// `band_radius`: the Refine Edge brush radius in these pixels; `scale`: pixels per layer pixel.
|
||||
pub fn matte_alpha(
|
||||
rgb: &[[f32; 3]],
|
||||
seg: &FrameSeg,
|
||||
prev: Option<&FrameSeg>,
|
||||
next: Option<&FrameSeg>,
|
||||
p: &MatteParams,
|
||||
band_radius: f64,
|
||||
scale: f64,
|
||||
) -> Vec<f32> {
|
||||
let (w, h) = (seg.w, seg.h);
|
||||
let n = w * h;
|
||||
let same = |s: &&FrameSeg| s.w == w && s.h == h;
|
||||
let (prev, next) = (prev.filter(same), next.filter(same));
|
||||
// Roto Brush Matte: Shift Edge (100 % = 10 px), Reduce Chatter, Feather, Contrast.
|
||||
let shift_px = p.rb_shift / 100.0 * 10.0 * scale;
|
||||
let mut a = shifted(seg, shift_px);
|
||||
let nb: Vec<Vec<f32>> = [prev, next].into_iter().flatten().map(|s| shifted(s, shift_px)).collect();
|
||||
if p.rb_chatter > 0.0 && !nb.is_empty() {
|
||||
let k = (p.rb_chatter / 100.0).clamp(0.0, 1.0) as f32 * (nb.len() as f32 / (nb.len() as f32 + 1.0));
|
||||
for i in 0..n {
|
||||
let m = nb.iter().map(|v| v[i]).sum::<f32>() / nb.len() as f32;
|
||||
a[i] += (m - a[i]) * k;
|
||||
}
|
||||
}
|
||||
if p.rb_feather > 0.0 {
|
||||
a = gauss(&a, w, h, p.rb_feather * scale / 2.0);
|
||||
}
|
||||
contrast(&mut a, p.rb_contrast);
|
||||
// Refine Edge band: guided-filter matting.
|
||||
if seg.refine.iter().any(|v| *v != 0) && seg.refine.len() == n {
|
||||
let r = (band_radius * 1.0).round().max(2.0) as usize;
|
||||
let eps = (2e-4 * (1.0 + p.smooth.max(0.0))) as f32;
|
||||
// Work on the band's bounding box (plus the filter's reach).
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
|
||||
for (i, v) in seg.refine.iter().enumerate() {
|
||||
if *v != 0 {
|
||||
let (x, y) = (i % w, i / w);
|
||||
x0 = x0.min(x);
|
||||
y0 = y0.min(y);
|
||||
x1 = x1.max(x + 1);
|
||||
y1 = y1.max(y + 1);
|
||||
}
|
||||
}
|
||||
let pad = 2 * r + 2;
|
||||
let (x0, y0, x1, y1) = (x0.saturating_sub(pad), y0.saturating_sub(pad), (x1 + pad).min(w), (y1 + pad).min(h));
|
||||
let (cw, ch) = (x1 - x0, y1 - y0);
|
||||
let crop = |src: &dyn Fn(usize) -> f32| -> Vec<f32> { (0..cw * ch).map(|j| src((y0 + j / cw) * w + x0 + j % cw)).collect() };
|
||||
let cimg: Vec<[f32; 3]> = (0..cw * ch).map(|j| rgb[(y0 + j / cw) * w + x0 + j % cw]).collect();
|
||||
let cp = crop(&|i| a[i]);
|
||||
let band: Vec<bool> = crop(&|i| seg.refine[i] as f32).iter().map(|v| *v > 0.0).collect();
|
||||
let outside: Vec<bool> = band.iter().map(|b| !b).collect();
|
||||
// Guided filter estimate, then closed-form matting with everything outside the band known.
|
||||
let mut q = guided_filter(&cimg, &cp, cw, ch, r, eps);
|
||||
for j in 0..cw * ch {
|
||||
q[j] = if band[j] { q[j].clamp(0.0, 1.0) } else { cp[j] };
|
||||
}
|
||||
if p.higher_quality {
|
||||
q = matting::closed_form(&cimg, &q, &outside, cw, ch, 1, 1e-5 * (1.0 + p.smooth.max(0.0)) as f32, 50);
|
||||
}
|
||||
// Refine Edge Matte adjustments.
|
||||
if p.smooth > 1.0 {
|
||||
q = gauss(&q, cw, ch, (p.smooth - 1.0) * 0.5 * scale);
|
||||
}
|
||||
if p.feather > 0.0 {
|
||||
q = gauss(&q, cw, ch, p.feather * scale / 2.0);
|
||||
}
|
||||
contrast(&mut q, p.contrast);
|
||||
shift_soft(&mut q, p.shift);
|
||||
// Blend in, fading over the band's last two pixels.
|
||||
let din = matting::distance(&outside, cw, ch);
|
||||
for j in 0..cw * ch {
|
||||
if !band[j] {
|
||||
continue;
|
||||
}
|
||||
let wgt = (din[j] / 2.0).clamp(0.0, 1.0);
|
||||
let i = (y0 + j / cw) * w + x0 + j % cw;
|
||||
a[i] += (q[j] - a[i]) * wgt;
|
||||
}
|
||||
// Refine-stage Reduce Chatter: towards the neighbours' mattes inside the band.
|
||||
if p.chatter > 0.0 && !nb.is_empty() {
|
||||
let k = (p.chatter / 100.0).clamp(0.0, 1.0) as f32 * 0.5;
|
||||
let soft: Vec<Vec<f32>> = nb.iter().map(|v| gauss(v, w, h, (r as f64 / 2.0).max(1.0))).collect();
|
||||
for i in 0..n {
|
||||
if seg.refine[i] != 0 {
|
||||
let m = soft.iter().map(|v| v[i]).sum::<f32>() / soft.len() as f32;
|
||||
a[i] += (m - a[i]) * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Motion blur: the matte's motion between the neighbouring frames.
|
||||
if p.motion_blur {
|
||||
let c = seg.centroid();
|
||||
let v = match (prev.and_then(FrameSeg::centroid), next.and_then(FrameSeg::centroid), c) {
|
||||
(Some(a), Some(b), _) => Some([(b[0] - a[0]) / 2.0, (b[1] - a[1]) / 2.0]),
|
||||
(Some(a), None, Some(c)) => Some([c[0] - a[0], c[1] - a[1]]),
|
||||
(None, Some(b), Some(c)) => Some([b[0] - c[0], b[1] - c[1]]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(v) = v {
|
||||
let s = p.shutter_angle / 360.0;
|
||||
a = matting::motion_blur(&a, w, h, [v[0] * s, v[1] * s], p.mb_samples);
|
||||
}
|
||||
}
|
||||
a.iter_mut().for_each(|v| *v = v.clamp(0.0, 1.0));
|
||||
a
|
||||
}
|
||||
|
||||
/// Decontaminate edge colours of `rgb` in place for the matte `alpha` (see
|
||||
/// [`matting::decontaminate`]); returns the decontamination map. `band`: the Refine Edge band
|
||||
/// (pixels where decontamination always applies).
|
||||
pub fn decontaminate(rgb: &mut [[f32; 3]], alpha: &[f32], band: &[u8], w: usize, h: usize, p: &MatteParams, band_radius: f64, scale: f64) -> Vec<f32> {
|
||||
if !p.decontaminate {
|
||||
return vec![0.0; w * h];
|
||||
}
|
||||
let grow = p.increase_radius * scale;
|
||||
let in_band: Vec<bool> = if band.len() == w * h && band.iter().any(|v| *v != 0) {
|
||||
if grow > 0.5 {
|
||||
let d = matting::distance(&band.iter().map(|v| *v != 0).collect::<Vec<_>>(), w, h);
|
||||
d.iter().map(|v| (*v as f64) <= grow).collect()
|
||||
} else {
|
||||
band.iter().map(|v| *v != 0).collect()
|
||||
}
|
||||
} else {
|
||||
vec![false; w * h]
|
||||
};
|
||||
let region: Vec<bool> = (0..w * h).map(|i| alpha[i] > 0.004 && alpha[i] < 0.996 && (in_band[i] || p.extend_where_smoothed)).collect();
|
||||
let radius = (band_radius + grow).max(4.0 * scale).round() as usize;
|
||||
matting::decontaminate(rgb, alpha, ®ion, w, h, radius, (p.decontamination / 100.0).clamp(0.0, 1.0) as f32)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Compact text encodings of mattes for project storage: run-length coding (LEB128 varints)
|
||||
//! wrapped in standard base64 (RFC 4648 §4).
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let b = [c[0], *c.get(1).unwrap_or(&0), *c.get(2).unwrap_or(&0)];
|
||||
let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
|
||||
out.push(B64[(n >> 18) as usize & 63] as char);
|
||||
out.push(B64[(n >> 12) as usize & 63] as char);
|
||||
out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' });
|
||||
out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let val = |c: u8| -> Option<u32> {
|
||||
Some(match c {
|
||||
b'A'..=b'Z' => (c - b'A') as u32,
|
||||
b'a'..=b'z' => (c - b'a' + 26) as u32,
|
||||
b'0'..=b'9' => (c - b'0' + 52) as u32,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
let bytes: Vec<u8> = s.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
|
||||
if !bytes.len().is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
|
||||
for c in bytes.chunks(4) {
|
||||
let pad = c.iter().rev().take_while(|b| **b == b'=').count();
|
||||
let mut n = 0u32;
|
||||
for (i, b) in c.iter().enumerate() {
|
||||
n |= if *b == b'=' { 0 } else { val(*b)? } << (18 - 6 * i);
|
||||
}
|
||||
out.push((n >> 16) as u8);
|
||||
if pad < 2 {
|
||||
out.push((n >> 8) as u8);
|
||||
}
|
||||
if pad < 1 {
|
||||
out.push(n as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn put(out: &mut Vec<u8>, mut v: u64) {
|
||||
loop {
|
||||
let b = (v & 0x7f) as u8;
|
||||
v >>= 7;
|
||||
if v == 0 {
|
||||
out.push(b);
|
||||
return;
|
||||
}
|
||||
out.push(b | 0x80);
|
||||
}
|
||||
}
|
||||
|
||||
fn get(data: &[u8], pos: &mut usize) -> Option<u64> {
|
||||
let mut v = 0u64;
|
||||
let mut shift = 0;
|
||||
loop {
|
||||
let b = *data.get(*pos)?;
|
||||
*pos += 1;
|
||||
v |= ((b & 0x7f) as u64) << shift;
|
||||
if b & 0x80 == 0 {
|
||||
return Some(v);
|
||||
}
|
||||
shift += 7;
|
||||
if shift > 63 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a byte plane as (value, run length) pairs.
|
||||
pub fn encode(values: &[u8]) -> String {
|
||||
let mut out = vec![];
|
||||
put(&mut out, values.len() as u64);
|
||||
let mut i = 0;
|
||||
while i < values.len() {
|
||||
let v = values[i];
|
||||
let mut j = i + 1;
|
||||
while j < values.len() && values[j] == v {
|
||||
j += 1;
|
||||
}
|
||||
out.push(v);
|
||||
put(&mut out, (j - i) as u64);
|
||||
i = j;
|
||||
}
|
||||
base64_encode(&out)
|
||||
}
|
||||
|
||||
/// Decode [`encode`]'s output (None when malformed).
|
||||
pub fn decode(s: &str) -> Option<Vec<u8>> {
|
||||
let data = base64_decode(s)?;
|
||||
let mut pos = 0;
|
||||
let n = get(&data, &mut pos)? as usize;
|
||||
if n > 1 << 30 {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
while out.len() < n {
|
||||
let v = *data.get(pos)?;
|
||||
pos += 1;
|
||||
let run = get(&data, &mut pos)? as usize;
|
||||
if out.len() + run > n {
|
||||
return None;
|
||||
}
|
||||
out.resize(out.len() + run, v);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
for n in [0usize, 1, 2, 3, 4, 5, 100, 1000] {
|
||||
let v: Vec<u8> = (0..n).map(|i| ((i / 7) % 3) as u8 * 100).collect();
|
||||
assert_eq!(decode(&encode(&v)).unwrap(), v);
|
||||
let raw: Vec<u8> = (0..n).map(|i| (i * 31) as u8).collect();
|
||||
assert_eq!(base64_decode(&base64_encode(&raw)).unwrap(), raw);
|
||||
}
|
||||
assert_eq!(base64_encode(b"Man"), "TWFu");
|
||||
assert_eq!(base64_encode(b"Ma"), "TWE=");
|
||||
assert!(decode("!!!!").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! Roto Brush on synthetic sequences: a textured disk moving over a textured background.
|
||||
|
||||
use super::refine::{MatteParams, decontaminate, matte_alpha};
|
||||
use super::*;
|
||||
|
||||
pub(crate) const W: u32 = 200;
|
||||
pub(crate) const H: u32 = 150;
|
||||
pub(crate) const R: f64 = 32.0;
|
||||
|
||||
/// Smooth value noise in 0..1.
|
||||
pub(crate) fn noise(x: f64, y: f64, seed: u32) -> f64 {
|
||||
fn h(i: i64, j: i64, s: u32) -> f64 {
|
||||
let mut v = (i.wrapping_mul(73856093) ^ j.wrapping_mul(19349663) ^ (s as i64).wrapping_mul(83492791)) as u64;
|
||||
v ^= v >> 13;
|
||||
v = v.wrapping_mul(0x5bd1e995);
|
||||
v ^= v >> 15;
|
||||
(v % 10_000) as f64 / 10_000.0
|
||||
}
|
||||
let mut out = 0.0;
|
||||
for (cell, amp) in [(9.0, 0.6), (3.5, 0.4)] {
|
||||
let (fx, fy) = (x / cell, y / cell);
|
||||
let (i, j) = (fx.floor() as i64, fy.floor() as i64);
|
||||
let (tx, ty) = (fx - i as f64, fy - j as f64);
|
||||
let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
|
||||
let a = h(i, j, seed) + (h(i + 1, j, seed) - h(i, j, seed)) * sx;
|
||||
let b = h(i, j + 1, seed) + (h(i + 1, j + 1, seed) - h(i, j + 1, seed)) * sx;
|
||||
out += amp * (a + (b - a) * sy);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn fg_color(x: f64, y: f64) -> [f32; 3] {
|
||||
let n = noise(x, y, 11);
|
||||
[(0.75 + 0.25 * n) as f32, (0.35 + 0.3 * n) as f32, (0.1 + 0.15 * n) as f32]
|
||||
}
|
||||
|
||||
pub(crate) fn bg_color(x: f64, y: f64) -> [f32; 3] {
|
||||
let n = noise(x, y, 5);
|
||||
let m = noise(x * 1.7, y * 1.7, 9);
|
||||
[(0.05 + 0.25 * m) as f32, (0.3 + 0.4 * n) as f32, (0.45 + 0.4 * m) as f32]
|
||||
}
|
||||
|
||||
pub(crate) fn center(f: i64) -> [f64; 2] {
|
||||
let t = f as f64;
|
||||
[60.0 + 3.1 * t, 70.0 + 1.3 * t + 4.0 * (t * 0.3).sin()]
|
||||
}
|
||||
|
||||
/// Frame `f`: the disk (texture moving with it) over the static background, with a 1-pixel
|
||||
/// anti-aliased edge; `c` overrides the centre.
|
||||
pub(crate) fn frame_at(c: [f64; 2]) -> (Image, Vec<u8>) {
|
||||
let mut img = Image::new(W, H);
|
||||
let mut gt = vec![0u8; (W * H) as usize];
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let p = [x as f64 + 0.5, y as f64 + 0.5];
|
||||
let d = (p[0] - c[0]).hypot(p[1] - c[1]);
|
||||
let a = (R + 0.5 - d).clamp(0.0, 1.0) as f32;
|
||||
let f = fg_color(p[0] - c[0], p[1] - c[1]);
|
||||
let b = bg_color(p[0], p[1]);
|
||||
img.set(x, y, [f[0] * a + b[0] * (1.0 - a), f[1] * a + b[1] * (1.0 - a), f[2] * a + b[2] * (1.0 - a), 1.0]);
|
||||
gt[(y * W + x) as usize] = (d <= R) as u8;
|
||||
}
|
||||
}
|
||||
(img, gt)
|
||||
}
|
||||
|
||||
fn line(kind: StrokeKind, frame: i64, a: [f64; 2], b: [f64; 2], radius: f64) -> Stroke {
|
||||
Stroke { kind, frame, radius, points: (0..=10).map(|k| [a[0] + (b[0] - a[0]) * k as f64 / 10.0, a[1] + (b[1] - a[1]) * k as f64 / 10.0]).collect() }
|
||||
}
|
||||
|
||||
/// The strokes an artist would paint on frame `f`: one through the disk, one around it.
|
||||
pub(crate) fn base_strokes(f: i64) -> Vec<Stroke> {
|
||||
let c = center(f);
|
||||
vec![
|
||||
line(StrokeKind::Fg, f, [c[0] - 18.0, c[1] - 6.0], [c[0] + 18.0, c[1] + 6.0], 5.0),
|
||||
line(StrokeKind::Bg, f, [c[0] - 50.0, c[1] - 45.0], [c[0] + 50.0, c[1] - 45.0], 5.0),
|
||||
line(StrokeKind::Bg, f, [c[0] + 50.0, c[1] + 45.0], [c[0] - 45.0, c[1] + 45.0], 5.0),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strokes_segment_the_base_frame() {
|
||||
let (img, gt) = frame_at(center(0));
|
||||
let st = base_strokes(0);
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let seg = segment(&img, &refs, None, &SegOpts::default(), 0.0);
|
||||
let j = iou(&seg.matte, >);
|
||||
assert!(j > 0.95, "IoU {j}");
|
||||
// Deterministic.
|
||||
let again = segment(&img, &refs, None, &SegOpts::default(), 0.0);
|
||||
assert_eq!(seg, again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coarse_to_fine_segments_large_frames() {
|
||||
// A 2× upscaled frame goes through the reduced-size path (Standard works at 480 px).
|
||||
let (small, _) = frame_at(center(0));
|
||||
let img = effectcraft_raster::resample(&small, W * 3, H * 3);
|
||||
let c = center(0);
|
||||
let st: Vec<Stroke> = base_strokes(0)
|
||||
.into_iter()
|
||||
.map(|mut s| {
|
||||
s.points.iter_mut().for_each(|p| *p = [p[0] * 3.0, p[1] * 3.0]);
|
||||
s.radius *= 3.0;
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let seg = segment(&img, &refs, None, &SegOpts::default(), 0.0);
|
||||
let gt: Vec<u8> =
|
||||
(0..W * H * 9).map(|i| ((((i % (W * 3)) as f64 + 0.5) / 3.0 - c[0]).hypot((((i / (W * 3)) as f64 + 0.5) / 3.0) - c[1]) <= R) as u8).collect();
|
||||
let j = iou(&seg.matte, >);
|
||||
assert!(j > 0.95, "IoU {j}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propagation_follows_the_disk_for_20_frames() {
|
||||
let (img0, _) = frame_at(center(0));
|
||||
let st = base_strokes(0);
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let opts = SegOpts::default();
|
||||
let mut seg = segment(&img0, &refs, None, &opts, 0.0);
|
||||
let mut prev = img0;
|
||||
let mut worst: f64 = 1.0;
|
||||
for f in 1..=20 {
|
||||
let (img, gt) = frame_at(center(f));
|
||||
seg = propagate(&prev, &seg, &img, &[], &opts, 0.0);
|
||||
let j = iou(&seg.matte, >);
|
||||
worst = worst.min(j);
|
||||
prev = img;
|
||||
}
|
||||
assert!(worst > 0.9, "worst IoU {worst}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_correction_stroke_fixes_a_bad_frame() {
|
||||
let opts = SegOpts::default();
|
||||
let (img0, _) = frame_at(center(0));
|
||||
let st = base_strokes(0);
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let seg0 = segment(&img0, &refs, None, &opts, 0.0);
|
||||
// The disk jumps far away on frame 1: propagation cannot follow.
|
||||
let jump = [150.0, 90.0];
|
||||
let (img1, gt1) = frame_at(jump);
|
||||
let bad = propagate(&img0, &seg0, &img1, &[], &opts, 0.0);
|
||||
assert!(iou(&bad.matte, >1) < 0.5, "the jump should break propagation");
|
||||
// Paint the disk in and the old place out.
|
||||
let c0 = center(0);
|
||||
let fix = [
|
||||
line(StrokeKind::Fg, 1, [jump[0] - 15.0, jump[1]], [jump[0] + 15.0, jump[1]], 5.0),
|
||||
line(StrokeKind::Bg, 1, [c0[0] - 10.0, c0[1] - 10.0], [c0[0] + 10.0, c0[1] + 10.0], 6.0),
|
||||
];
|
||||
let fr: Vec<&Stroke> = fix.iter().collect();
|
||||
let good = propagate(&img0, &seg0, &img1, &fr, &opts, 0.0);
|
||||
let j = iou(&good.matte, >1);
|
||||
assert!(j > 0.95, "corrected IoU {j}");
|
||||
// And propagation continues from the corrected frame.
|
||||
let c2 = [jump[0] + 3.0, jump[1] + 1.0];
|
||||
let (img2, gt2) = frame_at(c2);
|
||||
let next = propagate(&img1, &good, &img2, &[], &opts, 0.0);
|
||||
assert!(iou(&next.matte, >2) > 0.93);
|
||||
}
|
||||
|
||||
/// A soft-edged disk (alpha ramp over `width` pixels) over a background.
|
||||
fn soft_frame(c: [f64; 2], width: f64, fg: [f32; 3], bg: [f32; 3]) -> (Image, Vec<f32>) {
|
||||
let mut img = Image::new(W, H);
|
||||
let mut gt = vec![0.0f32; (W * H) as usize];
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let p = [x as f64 + 0.5, y as f64 + 0.5];
|
||||
let d = (p[0] - c[0]).hypot(p[1] - c[1]);
|
||||
let a = ((R + width / 2.0 - d) / width).clamp(0.0, 1.0) as f32;
|
||||
// Faint texture on both layers.
|
||||
let tf = (noise(p[0], p[1], 3) as f32 - 0.5) * 0.04;
|
||||
let tb = (noise(p[0], p[1], 4) as f32 - 0.5) * 0.04;
|
||||
let f = [fg[0] + tf, fg[1] + tf, fg[2] + tf];
|
||||
let b = [bg[0] + tb, bg[1] + tb, bg[2] + tb];
|
||||
img.set(x, y, [f[0] * a + b[0] * (1.0 - a), f[1] * a + b[1] * (1.0 - a), f[2] * a + b[2] * (1.0 - a), 1.0]);
|
||||
gt[(y * W + x) as usize] = a;
|
||||
}
|
||||
}
|
||||
(img, gt)
|
||||
}
|
||||
|
||||
fn ring(frame: i64, c: [f64; 2], r: f64, radius: f64) -> Stroke {
|
||||
Stroke {
|
||||
kind: StrokeKind::Refine,
|
||||
frame,
|
||||
radius,
|
||||
points: (0..=48).map(|k| k as f64 / 48.0 * std::f64::consts::TAU).map(|a| [c[0] + r * a.cos(), c[1] + r * a.sin()]).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refine_edge_recovers_a_soft_edge_and_decontaminates() {
|
||||
let c = [100.0, 75.0];
|
||||
let (fgc, bgc) = ([0.9f32, 0.25, 0.1], [0.1f32, 0.3, 0.9]);
|
||||
let (img, gt) = soft_frame(c, 10.0, fgc, bgc);
|
||||
let mut st = vec![
|
||||
line(StrokeKind::Fg, 0, [c[0] - 15.0, c[1]], [c[0] + 15.0, c[1]], 5.0),
|
||||
line(StrokeKind::Bg, 0, [c[0] - 60.0, c[1] - 55.0], [c[0] + 60.0, c[1] - 55.0], 5.0),
|
||||
];
|
||||
st.push(ring(0, c, R, 9.0));
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let seg = segment(&img, &refs, None, &SegOpts::default(), 9.0);
|
||||
assert!(seg.refine.iter().filter(|v| **v != 0).count() > 1000);
|
||||
let p = MatteParams::default();
|
||||
let rgb = rgb_of(&img);
|
||||
let a = matte_alpha(&rgb, &seg, None, None, &p, 9.0, 1.0);
|
||||
// Inside the ramp the matte is fractional and close to the truth.
|
||||
let (mut err, mut n, mut frac) = (0.0f64, 0usize, 0usize);
|
||||
let (mut err_bin, mut n_bin) = (0.0f64, 0usize);
|
||||
for i in 0..a.len() {
|
||||
if gt[i] > 0.0 && gt[i] < 1.0 {
|
||||
err += (a[i] - gt[i]).abs() as f64;
|
||||
err_bin += (seg.matte[i] as f32 - gt[i]).abs() as f64;
|
||||
n += 1;
|
||||
n_bin += 1;
|
||||
frac += (a[i] > 0.05 && a[i] < 0.95) as usize;
|
||||
}
|
||||
}
|
||||
let (err, err_bin) = (err / n as f64, err_bin / n_bin as f64);
|
||||
assert!(err < 0.03, "mean alpha error {err} (binary {err_bin})");
|
||||
assert!(err < err_bin * 0.4);
|
||||
assert!(frac as f64 > 0.6 * n as f64, "{frac}/{n} fractional");
|
||||
// Decontamination: edge pixels' colour is the foreground's, not a blue blend.
|
||||
let mut col = rgb.clone();
|
||||
let map = decontaminate(&mut col, &a, &seg.refine, W as usize, H as usize, &p, 9.0, 1.0);
|
||||
let (mut blue_before, mut blue_after, mut m) = (0.0f64, 0.0f64, 0usize);
|
||||
for i in 0..a.len() {
|
||||
if a[i] > 0.2 && a[i] < 0.8 {
|
||||
blue_before += rgb[i][2] as f64;
|
||||
blue_after += col[i][2] as f64;
|
||||
m += 1;
|
||||
}
|
||||
}
|
||||
let (bb, ba) = (blue_before / m as f64, blue_after / m as f64);
|
||||
assert!(ba < 0.2 && bb > 0.35, "blue before {bb}, after {ba}");
|
||||
assert!(map.iter().any(|v| *v > 0.2));
|
||||
// Without the band, the binary matte passes through.
|
||||
let mut seg2 = seg.clone();
|
||||
seg2.refine.iter_mut().for_each(|v| *v = 0);
|
||||
let a2 = matte_alpha(&rgb, &seg2, None, None, &p, 9.0, 1.0);
|
||||
assert!(a2.iter().zip(&seg.matte).all(|(x, y)| (*x - *y as f32).abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduce_chatter_and_motion_blur_use_the_neighbours() {
|
||||
let (w, h) = (40usize, 20usize);
|
||||
let mk = |x0: usize| FrameSeg {
|
||||
w,
|
||||
h,
|
||||
matte: (0..w * h).map(|i| (i % w >= x0 && i % w < x0 + 10) as u8).collect(),
|
||||
refine: vec![0; w * h],
|
||||
..Default::default()
|
||||
};
|
||||
let (a, b, c) = (mk(10), mk(14), mk(18));
|
||||
let rgb = vec![[0.5f32; 3]; w * h];
|
||||
let p = MatteParams { rb_chatter: 100.0, ..Default::default() };
|
||||
let al = matte_alpha(&rgb, &b, Some(&a), Some(&c), &p, 0.0, 1.0);
|
||||
// Pixel 12 is only in the previous frame: partially on.
|
||||
assert!(al[12] > 0.2 && al[12] < 0.5, "{}", al[12]);
|
||||
let p = MatteParams { motion_blur: true, ..Default::default() };
|
||||
let al = matte_alpha(&rgb, &b, Some(&a), Some(&c), &p, 0.0, 1.0);
|
||||
assert!(al[14] > 0.3 && al[14] < 0.9, "{}", al[14]);
|
||||
assert!(al[19] > 0.99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_keys_restart_at_correction_frames() {
|
||||
let mut d = RotoData::default();
|
||||
for s in base_strokes(5) {
|
||||
d.add(s, 20, [0, 30]);
|
||||
}
|
||||
assert_eq!(d.base, Some(5));
|
||||
assert_eq!(d.span, [0, 25]);
|
||||
let k1 = d.chain_keys(1);
|
||||
d.add(line(StrokeKind::Fg, 12, [0.0, 0.0], [1.0, 1.0], 3.0), 20, [0, 30]);
|
||||
let k2 = d.chain_keys(1);
|
||||
for f in 0..=11 {
|
||||
assert_eq!(k1[&f], k2[&f], "frame {f}");
|
||||
}
|
||||
for f in 12..=25 {
|
||||
assert_ne!(k1[&f], k2[&f], "frame {f}");
|
||||
}
|
||||
assert_ne!(d.chain_keys(2)[&5], k2[&5]);
|
||||
let back = RotoData::from_json(&d.to_json());
|
||||
assert_eq!(back, d);
|
||||
assert_eq!(d.source_of(12), Some(11));
|
||||
assert_eq!(d.source_of(3), Some(4));
|
||||
assert_eq!(d.source_of(5), None);
|
||||
}
|
||||
|
||||
/// `cargo test -p effectcraft-track --release roto_perf -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn roto_perf_1080p() {
|
||||
let up = |c: [f64; 2]| {
|
||||
let (img, _) = frame_at(c);
|
||||
effectcraft_raster::resample(&img, 1920, 1080)
|
||||
};
|
||||
let s = 1920.0 / W as f64;
|
||||
let st: Vec<Stroke> = base_strokes(0)
|
||||
.into_iter()
|
||||
.map(|mut k| {
|
||||
k.points.iter_mut().for_each(|p| *p = [p[0] * s, p[1] * s]);
|
||||
k.radius *= s;
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
let refs: Vec<&Stroke> = st.iter().collect();
|
||||
let opts = SegOpts { search_radius: 15.0 * s / 4.0, ..Default::default() };
|
||||
let a = up(center(0));
|
||||
let t = std::time::Instant::now();
|
||||
let seg = segment(&a, &refs, None, &opts, 0.0);
|
||||
eprintln!("segment 1080p: {:?}", t.elapsed());
|
||||
let b = up(center(1));
|
||||
let t = std::time::Instant::now();
|
||||
let next = propagate(&a, &seg, &b, &[], &opts, 0.0);
|
||||
eprintln!("propagate 1080p: {:?} (area {})", t.elapsed(), next.area());
|
||||
let mut seg2 = next.clone();
|
||||
let c = center(1);
|
||||
let ring: Vec<[f64; 2]> = (0..=64).map(|k| k as f64 / 64.0 * std::f64::consts::TAU).map(|t| [(c[0] + R * t.cos()) * s, (c[1] + R * t.sin()) * s]).collect();
|
||||
let st = [Stroke { kind: StrokeKind::Refine, frame: 1, radius: 20.0, points: ring }];
|
||||
let r = rasterize(&st.iter().collect::<Vec<_>>(), &[StrokeKind::Refine], 1.0, 1920, 1080);
|
||||
seg2.refine = r.iter().map(|v| *v as u8).collect();
|
||||
let rgb = rgb_of(&b);
|
||||
let t = std::time::Instant::now();
|
||||
let _ = matte_alpha(&rgb, &seg2, None, None, &MatteParams::default(), 20.0, 1.0);
|
||||
eprintln!("refine 1080p: {:?}", t.elapsed());
|
||||
}
|
||||
Reference in New Issue
Block a user