BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / examples / matte_eval.rs

matte_eval.rs

matte_eval.rs 17.0 KiB Download Raw
1//! Scores the person matte against a portrait matting set with true alphas (PPM-100 layout: `<dir>/fg/*.jpg`, `<dir>/alpha/*.png`).
2//! Usage: matte_eval <out_dir> <set_dir>... [--model mediapipe-256x144|modnet-320x192|modnet-512x288] [--gpu] [--shots N] [--limit N] [--motion]
3//! `--motion` moves the person over a room backdrop and scores a mask that arrives K frames late, stale and propagated.
4use std::path::{Path, PathBuf};
5use std::time::Instant;
6
7use calling::background::BackgroundPicture;
8use calling::composite::{Backdrop, PicturePlanes, composite};
9use calling::blur::{MaskInference, compose_image};
10use calling::segmentation::FixedSegmenter;
11use calling::segmentation::model::{MEDIAPIPE, MODNET_LARGE, MODNET_SMALL, ModelSpec};
12use calling::segmentation::runtime::Device;
13use calling::camera::i420_from_rgba;
14use calling::mask::Mask;
15use calling::matte::{Matte, Planes, RefineSettings, refine_with};
16use calling::motion::{LumaGrid, propagate_for_display};
17use image::imageops::FilterType;
18use libwebrtc::native::yuv_helper::i420_to_abgr;
19use libwebrtc::video_frame::I420Buffer;
20
21const WIDTH: u32 = 1280;
22const HEIGHT: u32 = 720;
23const EDGE_RADIUS: usize = 12;
24const JITTER_X: usize = 3;
25const JITTER_Y: usize = 2;
26const SPEEDS: [usize; 2] = [8, 16];
27const DELAYS: [usize; 4] = [0, 1, 2, 3];
28const METHODS: [&str; 5] = ["stale", "stale+guided", "propagated", "propagated+guided", "shipped"];
29
30struct Sample {
31 name: String,
32 rgba: Vec<u8>,
33 truth: Vec<f32>,
34}
35
36#[derive(Default, Clone, Copy)]
37struct Score {
38 mse: f64,
39 edge_mse: f64,
40 sad: f64,
41 flicker: f64,
42 infer_ms: f64,
43 refine_ms: f64,
44}
45
46fn load(foreground: &Path, alpha: &Path) -> Option<Sample> {
47 let photo = image::open(foreground).ok()?.resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle).to_rgba8().into_raw();
48 let truth = image::open(alpha).ok()?.resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle).to_luma8().into_raw();
49 let name = foreground.file_stem()?.to_string_lossy().into_owned();
50 Some(Sample { name, rgba: photo, truth: truth.iter().map(|&value| f32::from(value) / 255.).collect() })
51}
52
53fn samples(sets: &[PathBuf]) -> Vec<Sample> {
54 let mut found = Vec::new();
55 for set in sets {
56 let Ok(entries) = std::fs::read_dir(set.join("fg")) else { continue };
57 let mut paths: Vec<PathBuf> = entries.filter_map(|entry| entry.ok().map(|entry| entry.path())).collect();
58 paths.sort();
59 for path in paths {
60 let stem = path.file_stem().unwrap_or_default().to_string_lossy().into_owned();
61 let alpha = ["png", "jpg"].iter().map(|extension| set.join("alpha").join(format!("{stem}.{extension}"))).find(|candidate| candidate.exists());
62 if let Some(sample) = alpha.and_then(|alpha| load(&path, &alpha)) {
63 found.push(sample);
64 }
65 }
66 }
67 found
68}
69
70fn box_mean(values: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {
71 let mut across = vec![0f32; values.len()];
72 for row in 0..height {
73 let line = &values[row * width..][..width];
74 let mut prefix = vec![0f32; width + 1];
75 for (index, &value) in line.iter().enumerate() {
76 prefix[index + 1] = prefix[index] + value;
77 }
78 for column in 0..width {
79 let (low, high) = (column.saturating_sub(radius), (column + radius + 1).min(width));
80 across[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32;
81 }
82 }
83 let mut output = vec![0f32; values.len()];
84 for column in 0..width {
85 let mut prefix = vec![0f32; height + 1];
86 for row in 0..height {
87 prefix[row + 1] = prefix[row] + across[row * width + column];
88 }
89 for row in 0..height {
90 let (low, high) = (row.saturating_sub(radius), (row + radius + 1).min(height));
91 output[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32;
92 }
93 }
94 output
95}
96
97fn edge_band(truth: &[f32]) -> Vec<bool> {
98 box_mean(truth, WIDTH as usize, HEIGHT as usize, EDGE_RADIUS).iter().map(|&mean| mean > 0.01 && mean < 0.99).collect()
99}
100
101fn shifted(rgba: &[u8]) -> Vec<u8> {
102 let (width, height) = (WIDTH as usize, HEIGHT as usize);
103 let mut output = vec![0u8; rgba.len()];
104 for row in 0..height {
105 for column in 0..width {
106 let (source_row, source_column) = (row.saturating_sub(JITTER_Y), column.saturating_sub(JITTER_X));
107 let noise = ((row * 7919 + column * 104_729) % 9) as i16 - 4;
108 for channel in 0..4 {
109 let value = i16::from(rgba[(source_row * width + source_column) * 4 + channel]);
110 output[(row * width + column) * 4 + channel] = if channel == 3 { 255 } else { (value + noise).clamp(0, 255) as u8 };
111 }
112 }
113 }
114 output
115}
116
117fn settings() -> RefineSettings {
118 let read = |name: &str| std::env::var(name).ok().and_then(|value| value.parse::<f32>().ok());
119 let defaults = RefineSettings::default();
120 RefineSettings {
121 guide_width: read("GUIDE_WIDTH").map_or(defaults.guide_width, |value| value as usize),
122 edge_low: read("EDGE_LOW").unwrap_or(defaults.edge_low),
123 edge_high: read("EDGE_HIGH").unwrap_or(defaults.edge_high),
124 sure_person: read("SURE_PERSON").unwrap_or(defaults.sure_person),
125 sure_background: read("SURE_BACKGROUND").unwrap_or(defaults.sure_background),
126 }
127}
128
129fn matte_of(segmenter: &mut FixedSegmenter, rgba: &[u8]) -> (Matte, f64, f64) {
130 let camera = i420_from_rgba(rgba, WIDTH, HEIGHT);
131 let started = Instant::now();
132 let mask = segmenter.infer(i420_from_rgba(rgba, WIDTH, HEIGHT)).expect("mask");
133 let infer_ms = started.elapsed().as_secs_f64() * 1000.;
134 let started = Instant::now();
135 let matte = refine_with(&mask, Planes::of(&camera), settings());
136 (matte, infer_ms, started.elapsed().as_secs_f64() * 1000.)
137}
138
139fn score(segmenter: &mut FixedSegmenter, sample: &Sample) -> (Score, Matte) {
140 let (matte, infer_ms, refine_ms) = matte_of(segmenter, &sample.rgba);
141 let band = edge_band(&sample.truth);
142 let (mut squared, mut edge_squared, mut edge_count, mut absolute) = (0f64, 0f64, 0usize, 0f64);
143 for ((&alpha, &truth), &edge) in matte.alpha.iter().zip(&sample.truth).zip(&band) {
144 let difference = f64::from(f32::from(alpha) / 255. - truth);
145 squared += difference * difference;
146 absolute += difference.abs();
147 if edge {
148 edge_squared += difference * difference;
149 edge_count += 1;
150 }
151 }
152 let (jittered, ..) = matte_of(segmenter, &shifted(&sample.rgba));
153 let (width, height) = (WIDTH as usize, HEIGHT as usize);
154 let mut flicker = 0f64;
155 let mut flicker_count = 0usize;
156 for row in JITTER_Y..height {
157 for column in JITTER_X..width {
158 let source = (row - JITTER_Y) * width + column - JITTER_X;
159 if band[source] {
160 flicker += f64::from(i16::from(jittered.alpha[row * width + column]).abs_diff(i16::from(matte.alpha[source])));
161 flicker_count += 1;
162 }
163 }
164 }
165 let pixels = (width * height) as f64;
166 let result = Score {
167 mse: squared / pixels * 1000.,
168 edge_mse: edge_squared / edge_count.max(1) as f64 * 1000.,
169 sad: absolute / 1000.,
170 flicker: flicker / flicker_count.max(1) as f64,
171 infer_ms,
172 refine_ms,
173 };
174 (result, matte)
175}
176
177fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {
178 let (stride_y, stride_u, stride_v) = buffer.strides();
179 let (plane_y, plane_u, plane_v) = buffer.data();
180 let mut rgba = vec![0u8; (WIDTH * HEIGHT * 4) as usize];
181 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, WIDTH * 4, WIDTH as i32, HEIGHT as i32);
182 rgba
183}
184
185fn backdrop() -> PicturePlanes {
186 let (width, height) = (64, 36);
187 let rgb = (0..width * height).flat_map(|index| {
188 let (x, y) = (index % width, index / width);
189 [(20 + x) as u8, (170 + y * 2) as u8, (60 + x * 2) as u8]
190 });
191 let covered = BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop").covering(WIDTH as usize, HEIGHT as usize);
192 PicturePlanes::new(&covered, WIDTH as usize, HEIGHT as usize)
193}
194
195fn gray_rgba(values: impl Iterator<Item = u8>) -> Vec<u8> {
196 values.flat_map(|value| [value, value, value, 255]).collect()
197}
198
199fn save_sheet(out: &Path, sample: &Sample, matte: &Matte) {
200 let mut blurred = i420_from_rgba(&sample.rgba, WIDTH, HEIGHT);
201 composite(&mut blurred, matte, Backdrop::Blur);
202 let mut replaced = sample.rgba.clone();
203 compose_image(&mut replaced, WIDTH as usize, HEIGHT as usize, matte, &backdrop());
204 let tiles = [sample.rgba.clone(), gray_rgba(sample.truth.iter().map(|&value| (value * 255. + 0.5) as u8)), gray_rgba(matte.alpha.iter().copied()), rgba_of(&blurred), replaced];
205 let mut sheet = image::RgbaImage::new(WIDTH * 3, HEIGHT * 2);
206 for (index, tile) in tiles.into_iter().enumerate() {
207 let tile = image::RgbaImage::from_raw(WIDTH, HEIGHT, tile).expect("tile size");
208 image::imageops::replace(&mut sheet, &tile, i64::from(WIDTH) * (index % 3) as i64, i64::from(HEIGHT) * (index / 3) as i64);
209 }
210 image::imageops::resize(&sheet, WIDTH * 3 / 2, HEIGHT, FilterType::Triangle).save(out.join(format!("{}.png", sample.name))).expect("sheet written");
211}
212
213fn room(seed: usize) -> Vec<u8> {
214 let (width, height) = (WIDTH as usize, HEIGHT as usize);
215 let mut state = (seed as u64).wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
216 let mut next = move |range: usize| {
217 state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
218 ((state >> 33) as usize) % range.max(1)
219 };
220 let mut rgba: Vec<u8> = (0..width * height)
221 .flat_map(|index| {
222 let row = index / width;
223 let shade = (150 + row * 60 / height) as u8;
224 [shade, shade - 10, shade - 25, 255]
225 })
226 .collect();
227 for _ in 0..40 {
228 let (left, top, box_width, box_height) = (next(width), next(height), 20 + next(220), 10 + next(160));
229 let colour = [30 + next(200) as u8, 30 + next(200) as u8, 30 + next(200) as u8];
230 for row in top..(top + box_height).min(height) {
231 for column in left..(left + box_width).min(width) {
232 rgba[(row * width + column) * 4..][..3].copy_from_slice(&colour);
233 }
234 }
235 }
236 for (index, pixel) in rgba.chunks_exact_mut(4).enumerate() {
237 let noise = ((index * 7919 + index / width * 104_729) % 17) as i16 - 8;
238 for channel in pixel.iter_mut().take(3) {
239 *channel = (i16::from(*channel) + noise).clamp(0, 255) as u8;
240 }
241 }
242 rgba
243}
244
245fn moved(sample: &Sample, backdrop: &[u8], (across, down): (usize, usize)) -> (Vec<u8>, Vec<f32>) {
246 let (width, height) = (WIDTH as usize, HEIGHT as usize);
247 let mut rgba = backdrop.to_vec();
248 let mut truth = vec![0f32; width * height];
249 for row in down..height {
250 for column in across..width {
251 let source = (row - down) * width + column - across;
252 let alpha = sample.truth[source];
253 truth[row * width + column] = alpha;
254 for channel in 0..3 {
255 let target = &mut rgba[(row * width + column) * 4 + channel];
256 *target = (f32::from(sample.rgba[source * 4 + channel]) * alpha + f32::from(*target) * (1. - alpha) + 0.5) as u8;
257 }
258 }
259 }
260 (rgba, truth)
261}
262
263fn band_error(matte: &Matte, truth: &[f32], band: &[bool]) -> f64 {
264 let (mut squared, mut count) = (0f64, 0usize);
265 for ((&alpha, &truth), _) in matte.alpha.iter().zip(truth).zip(band).filter(|(_, edge)| **edge) {
266 let difference = f64::from(f32::from(alpha) / 255. - truth);
267 squared += difference * difference;
268 count += 1;
269 }
270 squared / count.max(1) as f64 * 1000.
271}
272
273fn guided(mask: &Mask) -> Mask {
274 Mask { matte: false, ..mask.clone() }
275}
276
277fn motion_eval(segmenter: &mut FixedSegmenter, spec: ModelSpec, all: &[Sample]) {
278 let rows = SPEEDS.len() * DELAYS.len();
279 let mut errors = vec![[0f64; METHODS.len()]; rows];
280 let mut propagate_ms = 0f64;
281 let mut propagations = 0usize;
282 for (index, sample) in all.iter().enumerate() {
283 let backdrop = room(index);
284 let (source_rgba, source_truth) = moved(sample, &backdrop, (0, 0));
285 let source = i420_from_rgba(&source_rgba, WIDTH, HEIGHT);
286 let mask = segmenter.infer(i420_from_rgba(&source_rgba, WIDTH, HEIGHT)).expect("mask");
287 let reference = LumaGrid::of(&source);
288 let source_band = edge_band(&source_truth);
289 for (speed_index, speed) in SPEEDS.into_iter().enumerate() {
290 for (delay_index, delay) in DELAYS.into_iter().enumerate() {
291 let (rgba, truth) = moved(sample, &backdrop, (speed * delay, speed * delay / 4));
292 let current = i420_from_rgba(&rgba, WIDTH, HEIGHT);
293 let band: Vec<bool> = edge_band(&truth).iter().zip(&source_band).map(|(now, before)| *now || *before).collect();
294 let started = Instant::now();
295 let (propagated, moved) = propagate_for_display(&mask, &reference, &LumaGrid::of(&current));
296 propagate_ms += started.elapsed().as_secs_f64() * 1000.;
297 propagations += 1;
298 let shipped = Mask { matte: propagated.matte && !moved, ..propagated.clone() };
299 let candidates = [mask.clone(), guided(&mask), propagated.clone(), guided(&propagated), shipped];
300 for (method, candidate) in candidates.iter().enumerate() {
301 let matte = refine_with(candidate, Planes::of(&current), settings());
302 errors[speed_index * DELAYS.len() + delay_index][method] += band_error(&matte, &truth, &band);
303 }
304 }
305 }
306 }
307 let count = all.len().max(1) as f64;
308 println!("{} {} images, motion edge_mse x1000 (band = old and new edge), propagate {:.2} ms", spec.name, all.len(), propagate_ms / propagations.max(1) as f64);
309 println!("| speed px/frame | late frames | {} |", METHODS.join(" | "));
310 for (speed_index, speed) in SPEEDS.into_iter().enumerate() {
311 for (delay_index, delay) in DELAYS.into_iter().enumerate() {
312 let row = &errors[speed_index * DELAYS.len() + delay_index];
313 println!("| {speed} | {delay} | {} |", row.iter().map(|error| format!("{:.1}", error / count)).collect::<Vec<_>>().join(" | "));
314 }
315 }
316}
317
318fn main() {
319 let mut arguments: Vec<String> = std::env::args().skip(1).collect();
320 let flag = |arguments: &mut Vec<String>, name: &str| -> Option<usize> {
321 let position = arguments.iter().position(|argument| argument == name)?;
322 let value = arguments.remove(position + 1).parse().ok();
323 arguments.remove(position);
324 value
325 };
326 let model = arguments.iter().position(|argument| argument == "--model").map(|position| {
327 let name = arguments.remove(position + 1);
328 arguments.remove(position);
329 name
330 });
331 let spec: ModelSpec = [MEDIAPIPE, MODNET_SMALL, MODNET_LARGE].into_iter().find(|spec| Some(spec.name) == model.as_deref()).unwrap_or(MEDIAPIPE);
332 let gpu = arguments.iter().position(|argument| argument == "--gpu").map(|position| arguments.remove(position)).is_some();
333 let motion = arguments.iter().position(|argument| argument == "--motion").map(|position| arguments.remove(position)).is_some();
334 let shots = flag(&mut arguments, "--shots").unwrap_or(6);
335 let limit = flag(&mut arguments, "--limit").unwrap_or(usize::MAX);
336 let out = PathBuf::from(arguments.first().expect("out dir"));
337 let sets: Vec<PathBuf> = arguments[1..].iter().map(PathBuf::from).collect();
338 std::fs::create_dir_all(&out).expect("out dir");
339 let mut segmenter = FixedSegmenter::new(spec, if gpu { Device::Gpu } else { Device::Cpu { threads: 4 } }).expect("model");
340 let all = samples(&sets);
341 if motion {
342 motion_eval(&mut segmenter, spec, &all[..all.len().min(limit)]);
343 return;
344 }
345 let mut total = Score::default();
346 let mut lines = vec!["name,mse,edge_mse,sad,flicker,infer_ms,refine_ms".to_owned()];
347 let count = all.len().min(limit);
348 for (index, sample) in all.iter().take(limit).enumerate() {
349 let (result, matte) = score(&mut segmenter, sample);
350 lines.push(format!("{},{:.3},{:.3},{:.2},{:.3},{:.2},{:.2}", sample.name, result.mse, result.edge_mse, result.sad, result.flicker, result.infer_ms, result.refine_ms));
351 total.mse += result.mse;
352 total.edge_mse += result.edge_mse;
353 total.sad += result.sad;
354 total.flicker += result.flicker;
355 total.infer_ms += result.infer_ms;
356 total.refine_ms += result.refine_ms;
357 if index < shots {
358 save_sheet(&out, sample, &matte);
359 }
360 }
361 std::fs::write(out.join("scores.csv"), lines.join("\n")).expect("csv written");
362 let mean = |value: f64| value / count.max(1) as f64;
363 println!(
364 "{} {count} images: mse {:.2} edge_mse {:.2} sad {:.1} flicker {:.2} infer {:.1} ms refine {:.1} ms",
365 spec.name,
366 mean(total.mse),
367 mean(total.edge_mse),
368 mean(total.sad),
369 mean(total.flicker),
370 mean(total.infer_ms),
371 mean(total.refine_ms)
372 );
373}