BlueGit

ict rusty-teams

Files

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

matte_eval.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
matte_eval.rs 18.9 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::blur::{MaskInference, compose_image};
9use calling::camera::i420_from_rgba;
10use calling::composite::{Backdrop, PicturePlanes, composite};
11use calling::mask::Mask;
12use calling::matte::{Matte, Planes, RefineSettings, refine_with};
13use calling::motion::{LumaGrid, propagate_for_display};
14use calling::segmentation::FixedSegmenter;
15use calling::segmentation::model::{MEDIAPIPE, MODNET_LARGE, MODNET_SMALL, ModelSpec};
16use calling::segmentation::runtime::Device;
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] = [
29 "stale",
30 "stale+guided",
31 "propagated",
32 "propagated+guided",
33 "shipped",
34];
35
36struct Sample {
37 name: String,
38 rgba: Vec<u8>,
39 truth: Vec<f32>,
40}
41
42#[derive(Default, Clone, Copy)]
43struct Score {
44 mse: f64,
45 edge_mse: f64,
46 sad: f64,
47 flicker: f64,
48 infer_ms: f64,
49 refine_ms: f64,
50}
51
52fn load(foreground: &Path, alpha: &Path) -> Option<Sample> {
53 let photo = image::open(foreground)
54 .ok()?
55 .resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle)
56 .to_rgba8()
57 .into_raw();
58 let truth = image::open(alpha)
59 .ok()?
60 .resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle)
61 .to_luma8()
62 .into_raw();
63 let name = foreground.file_stem()?.to_string_lossy().into_owned();
64 Some(Sample {
65 name,
66 rgba: photo,
67 truth: truth.iter().map(|&value| f32::from(value) / 255.).collect(),
68 })
69}
70
71fn samples(sets: &[PathBuf]) -> Vec<Sample> {
72 let mut found = Vec::new();
73 for set in sets {
74 let Ok(entries) = std::fs::read_dir(set.join("fg")) else {
75 continue;
76 };
77 let mut paths: Vec<PathBuf> = entries
78 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
79 .collect();
80 paths.sort();
81 for path in paths {
82 let stem = path
83 .file_stem()
84 .unwrap_or_default()
85 .to_string_lossy()
86 .into_owned();
87 let alpha = ["png", "jpg"]
88 .iter()
89 .map(|extension| set.join("alpha").join(format!("{stem}.{extension}")))
90 .find(|candidate| candidate.exists());
91 if let Some(sample) = alpha.and_then(|alpha| load(&path, &alpha)) {
92 found.push(sample);
93 }
94 }
95 }
96 found
97}
98
99fn box_mean(values: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {
100 let mut across = vec![0f32; values.len()];
101 for row in 0..height {
102 let line = &values[row * width..][..width];
103 let mut prefix = vec![0f32; width + 1];
104 for (index, &value) in line.iter().enumerate() {
105 prefix[index + 1] = prefix[index] + value;
106 }
107 for column in 0..width {
108 let (low, high) = (
109 column.saturating_sub(radius),
110 (column + radius + 1).min(width),
111 );
112 across[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32;
113 }
114 }
115 let mut output = vec![0f32; values.len()];
116 for column in 0..width {
117 let mut prefix = vec![0f32; height + 1];
118 for row in 0..height {
119 prefix[row + 1] = prefix[row] + across[row * width + column];
120 }
121 for row in 0..height {
122 let (low, high) = (row.saturating_sub(radius), (row + radius + 1).min(height));
123 output[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32;
124 }
125 }
126 output
127}
128
129fn edge_band(truth: &[f32]) -> Vec<bool> {
130 box_mean(truth, WIDTH as usize, HEIGHT as usize, EDGE_RADIUS)
131 .iter()
132 .map(|&mean| mean > 0.01 && mean < 0.99)
133 .collect()
134}
135
136fn shifted(rgba: &[u8]) -> Vec<u8> {
137 let (width, height) = (WIDTH as usize, HEIGHT as usize);
138 let mut output = vec![0u8; rgba.len()];
139 for row in 0..height {
140 for column in 0..width {
141 let (source_row, source_column) = (
142 row.saturating_sub(JITTER_Y),
143 column.saturating_sub(JITTER_X),
144 );
145 let noise = ((row * 7919 + column * 104_729) % 9) as i16 - 4;
146 for channel in 0..4 {
147 let value = i16::from(rgba[(source_row * width + source_column) * 4 + channel]);
148 output[(row * width + column) * 4 + channel] = if channel == 3 {
149 255
150 } else {
151 (value + noise).clamp(0, 255) as u8
152 };
153 }
154 }
155 }
156 output
157}
158
159fn settings() -> RefineSettings {
160 let read = |name: &str| {
161 std::env::var(name)
162 .ok()
163 .and_then(|value| value.parse::<f32>().ok())
164 };
165 let defaults = RefineSettings::default();
166 RefineSettings {
167 guide_width: read("GUIDE_WIDTH").map_or(defaults.guide_width, |value| value as usize),
168 edge_low: read("EDGE_LOW").unwrap_or(defaults.edge_low),
169 edge_high: read("EDGE_HIGH").unwrap_or(defaults.edge_high),
170 sure_person: read("SURE_PERSON").unwrap_or(defaults.sure_person),
171 sure_background: read("SURE_BACKGROUND").unwrap_or(defaults.sure_background),
172 }
173}
174
175fn matte_of(segmenter: &mut FixedSegmenter, rgba: &[u8]) -> (Matte, f64, f64) {
176 let camera = i420_from_rgba(rgba, WIDTH, HEIGHT);
177 let started = Instant::now();
178 let mask = segmenter
179 .infer(i420_from_rgba(rgba, WIDTH, HEIGHT))
180 .expect("mask");
181 let infer_ms = started.elapsed().as_secs_f64() * 1000.;
182 let started = Instant::now();
183 let matte = refine_with(&mask, Planes::of(&camera), settings());
184 (matte, infer_ms, started.elapsed().as_secs_f64() * 1000.)
185}
186
187fn score(segmenter: &mut FixedSegmenter, sample: &Sample) -> (Score, Matte) {
188 let (matte, infer_ms, refine_ms) = matte_of(segmenter, &sample.rgba);
189 let band = edge_band(&sample.truth);
190 let (mut squared, mut edge_squared, mut edge_count, mut absolute) = (0f64, 0f64, 0usize, 0f64);
191 for ((&alpha, &truth), &edge) in matte.alpha.iter().zip(&sample.truth).zip(&band) {
192 let difference = f64::from(f32::from(alpha) / 255. - truth);
193 squared += difference * difference;
194 absolute += difference.abs();
195 if edge {
196 edge_squared += difference * difference;
197 edge_count += 1;
198 }
199 }
200 let (jittered, ..) = matte_of(segmenter, &shifted(&sample.rgba));
201 let (width, height) = (WIDTH as usize, HEIGHT as usize);
202 let mut flicker = 0f64;
203 let mut flicker_count = 0usize;
204 for row in JITTER_Y..height {
205 for column in JITTER_X..width {
206 let source = (row - JITTER_Y) * width + column - JITTER_X;
207 if band[source] {
208 flicker += f64::from(
209 i16::from(jittered.alpha[row * width + column])
210 .abs_diff(i16::from(matte.alpha[source])),
211 );
212 flicker_count += 1;
213 }
214 }
215 }
216 let pixels = (width * height) as f64;
217 let result = Score {
218 mse: squared / pixels * 1000.,
219 edge_mse: edge_squared / edge_count.max(1) as f64 * 1000.,
220 sad: absolute / 1000.,
221 flicker: flicker / flicker_count.max(1) as f64,
222 infer_ms,
223 refine_ms,
224 };
225 (result, matte)
226}
227
228fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {
229 let (stride_y, stride_u, stride_v) = buffer.strides();
230 let (plane_y, plane_u, plane_v) = buffer.data();
231 let mut rgba = vec![0u8; (WIDTH * HEIGHT * 4) as usize];
232 i420_to_abgr(
233 plane_y,
234 stride_y,
235 plane_u,
236 stride_u,
237 plane_v,
238 stride_v,
239 &mut rgba,
240 WIDTH * 4,
241 WIDTH as i32,
242 HEIGHT as i32,
243 );
244 rgba
245}
246
247fn backdrop() -> PicturePlanes {
248 let (width, height) = (64, 36);
249 let rgb = (0..width * height).flat_map(|index| {
250 let (x, y) = (index % width, index / width);
251 [(20 + x) as u8, (170 + y * 2) as u8, (60 + x * 2) as u8]
252 });
253 let covered = BackgroundPicture::from_rgb(rgb.collect(), width, height)
254 .expect("backdrop")
255 .covering(WIDTH as usize, HEIGHT as usize);
256 PicturePlanes::new(&covered, WIDTH as usize, HEIGHT as usize)
257}
258
259fn gray_rgba(values: impl Iterator<Item = u8>) -> Vec<u8> {
260 values
261 .flat_map(|value| [value, value, value, 255])
262 .collect()
263}
264
265fn save_sheet(out: &Path, sample: &Sample, matte: &Matte) {
266 let mut blurred = i420_from_rgba(&sample.rgba, WIDTH, HEIGHT);
267 composite(&mut blurred, matte, Backdrop::Blur);
268 let mut replaced = sample.rgba.clone();
269 compose_image(
270 &mut replaced,
271 WIDTH as usize,
272 HEIGHT as usize,
273 matte,
274 &backdrop(),
275 );
276 let tiles = [
277 sample.rgba.clone(),
278 gray_rgba(sample.truth.iter().map(|&value| (value * 255. + 0.5) as u8)),
279 gray_rgba(matte.alpha.iter().copied()),
280 rgba_of(&blurred),
281 replaced,
282 ];
283 let mut sheet = image::RgbaImage::new(WIDTH * 3, HEIGHT * 2);
284 for (index, tile) in tiles.into_iter().enumerate() {
285 let tile = image::RgbaImage::from_raw(WIDTH, HEIGHT, tile).expect("tile size");
286 image::imageops::replace(
287 &mut sheet,
288 &tile,
289 i64::from(WIDTH) * (index % 3) as i64,
290 i64::from(HEIGHT) * (index / 3) as i64,
291 );
292 }
293 image::imageops::resize(&sheet, WIDTH * 3 / 2, HEIGHT, FilterType::Triangle)
294 .save(out.join(format!("{}.png", sample.name)))
295 .expect("sheet written");
296}
297
298fn room(seed: usize) -> Vec<u8> {
299 let (width, height) = (WIDTH as usize, HEIGHT as usize);
300 let mut state = (seed as u64)
301 .wrapping_mul(6_364_136_223_846_793_005)
302 .wrapping_add(1_442_695_040_888_963_407);
303 let mut next = move |range: usize| {
304 state = state
305 .wrapping_mul(6_364_136_223_846_793_005)
306 .wrapping_add(1_442_695_040_888_963_407);
307 ((state >> 33) as usize) % range.max(1)
308 };
309 let mut rgba: Vec<u8> = (0..width * height)
310 .flat_map(|index| {
311 let row = index / width;
312 let shade = (150 + row * 60 / height) as u8;
313 [shade, shade - 10, shade - 25, 255]
314 })
315 .collect();
316 for _ in 0..40 {
317 let (left, top, box_width, box_height) =
318 (next(width), next(height), 20 + next(220), 10 + next(160));
319 let colour = [
320 30 + next(200) as u8,
321 30 + next(200) as u8,
322 30 + next(200) as u8,
323 ];
324 for row in top..(top + box_height).min(height) {
325 for column in left..(left + box_width).min(width) {
326 rgba[(row * width + column) * 4..][..3].copy_from_slice(&colour);
327 }
328 }
329 }
330 for (index, pixel) in rgba.chunks_exact_mut(4).enumerate() {
331 let noise = ((index * 7919 + index / width * 104_729) % 17) as i16 - 8;
332 for channel in pixel.iter_mut().take(3) {
333 *channel = (i16::from(*channel) + noise).clamp(0, 255) as u8;
334 }
335 }
336 rgba
337}
338
339fn moved(sample: &Sample, backdrop: &[u8], (across, down): (usize, usize)) -> (Vec<u8>, Vec<f32>) {
340 let (width, height) = (WIDTH as usize, HEIGHT as usize);
341 let mut rgba = backdrop.to_vec();
342 let mut truth = vec![0f32; width * height];
343 for row in down..height {
344 for column in across..width {
345 let source = (row - down) * width + column - across;
346 let alpha = sample.truth[source];
347 truth[row * width + column] = alpha;
348 for channel in 0..3 {
349 let target = &mut rgba[(row * width + column) * 4 + channel];
350 *target = (f32::from(sample.rgba[source * 4 + channel]) * alpha
351 + f32::from(*target) * (1. - alpha)
352 + 0.5) as u8;
353 }
354 }
355 }
356 (rgba, truth)
357}
358
359fn band_error(matte: &Matte, truth: &[f32], band: &[bool]) -> f64 {
360 let (mut squared, mut count) = (0f64, 0usize);
361 for ((&alpha, &truth), _) in matte
362 .alpha
363 .iter()
364 .zip(truth)
365 .zip(band)
366 .filter(|(_, edge)| **edge)
367 {
368 let difference = f64::from(f32::from(alpha) / 255. - truth);
369 squared += difference * difference;
370 count += 1;
371 }
372 squared / count.max(1) as f64 * 1000.
373}
374
375fn guided(mask: &Mask) -> Mask {
376 Mask {
377 matte: false,
378 ..mask.clone()
379 }
380}
381
382fn motion_eval(segmenter: &mut FixedSegmenter, spec: ModelSpec, all: &[Sample]) {
383 let rows = SPEEDS.len() * DELAYS.len();
384 let mut errors = vec![[0f64; METHODS.len()]; rows];
385 let mut propagate_ms = 0f64;
386 let mut propagations = 0usize;
387 for (index, sample) in all.iter().enumerate() {
388 let backdrop = room(index);
389 let (source_rgba, source_truth) = moved(sample, &backdrop, (0, 0));
390 let source = i420_from_rgba(&source_rgba, WIDTH, HEIGHT);
391 let mask = segmenter
392 .infer(i420_from_rgba(&source_rgba, WIDTH, HEIGHT))
393 .expect("mask");
394 let reference = LumaGrid::of(&source);
395 let source_band = edge_band(&source_truth);
396 for (speed_index, speed) in SPEEDS.into_iter().enumerate() {
397 for (delay_index, delay) in DELAYS.into_iter().enumerate() {
398 let (rgba, truth) = moved(sample, &backdrop, (speed * delay, speed * delay / 4));
399 let current = i420_from_rgba(&rgba, WIDTH, HEIGHT);
400 let band: Vec<bool> = edge_band(&truth)
401 .iter()
402 .zip(&source_band)
403 .map(|(now, before)| *now || *before)
404 .collect();
405 let started = Instant::now();
406 let (propagated, moved) =
407 propagate_for_display(&mask, &reference, &LumaGrid::of(&current));
408 propagate_ms += started.elapsed().as_secs_f64() * 1000.;
409 propagations += 1;
410 let shipped = Mask {
411 matte: propagated.matte && !moved,
412 ..propagated.clone()
413 };
414 let candidates = [
415 mask.clone(),
416 guided(&mask),
417 propagated.clone(),
418 guided(&propagated),
419 shipped,
420 ];
421 for (method, candidate) in candidates.iter().enumerate() {
422 let matte = refine_with(candidate, Planes::of(&current), settings());
423 errors[speed_index * DELAYS.len() + delay_index][method] +=
424 band_error(&matte, &truth, &band);
425 }
426 }
427 }
428 }
429 let count = all.len().max(1) as f64;
430 println!(
431 "{} {} images, motion edge_mse x1000 (band = old and new edge), propagate {:.2} ms",
432 spec.name,
433 all.len(),
434 propagate_ms / propagations.max(1) as f64
435 );
436 println!("| speed px/frame | late frames | {} |", METHODS.join(" | "));
437 for (speed_index, speed) in SPEEDS.into_iter().enumerate() {
438 for (delay_index, delay) in DELAYS.into_iter().enumerate() {
439 let row = &errors[speed_index * DELAYS.len() + delay_index];
440 println!(
441 "| {speed} | {delay} | {} |",
442 row.iter()
443 .map(|error| format!("{:.1}", error / count))
444 .collect::<Vec<_>>()
445 .join(" | ")
446 );
447 }
448 }
449}
450
451fn main() {
452 let mut arguments: Vec<String> = std::env::args().skip(1).collect();
453 let flag = |arguments: &mut Vec<String>, name: &str| -> Option<usize> {
454 let position = arguments.iter().position(|argument| argument == name)?;
455 let value = arguments.remove(position + 1).parse().ok();
456 arguments.remove(position);
457 value
458 };
459 let model = arguments
460 .iter()
461 .position(|argument| argument == "--model")
462 .map(|position| {
463 let name = arguments.remove(position + 1);
464 arguments.remove(position);
465 name
466 });
467 let spec: ModelSpec = [MEDIAPIPE, MODNET_SMALL, MODNET_LARGE]
468 .into_iter()
469 .find(|spec| Some(spec.name) == model.as_deref())
470 .unwrap_or(MEDIAPIPE);
471 let gpu = arguments
472 .iter()
473 .position(|argument| argument == "--gpu")
474 .map(|position| arguments.remove(position))
475 .is_some();
476 let motion = arguments
477 .iter()
478 .position(|argument| argument == "--motion")
479 .map(|position| arguments.remove(position))
480 .is_some();
481 let shots = flag(&mut arguments, "--shots").unwrap_or(6);
482 let limit = flag(&mut arguments, "--limit").unwrap_or(usize::MAX);
483 let out = PathBuf::from(arguments.first().expect("out dir"));
484 let sets: Vec<PathBuf> = arguments[1..].iter().map(PathBuf::from).collect();
485 std::fs::create_dir_all(&out).expect("out dir");
486 let mut segmenter = FixedSegmenter::new(
487 spec,
488 if gpu {
489 Device::Gpu
490 } else {
491 Device::Cpu { threads: 4 }
492 },
493 )
494 .expect("model");
495 let all = samples(&sets);
496 if motion {
497 motion_eval(&mut segmenter, spec, &all[..all.len().min(limit)]);
498 return;
499 }
500 let mut total = Score::default();
501 let mut lines = vec!["name,mse,edge_mse,sad,flicker,infer_ms,refine_ms".to_owned()];
502 let count = all.len().min(limit);
503 for (index, sample) in all.iter().take(limit).enumerate() {
504 let (result, matte) = score(&mut segmenter, sample);
505 lines.push(format!(
506 "{},{:.3},{:.3},{:.2},{:.3},{:.2},{:.2}",
507 sample.name,
508 result.mse,
509 result.edge_mse,
510 result.sad,
511 result.flicker,
512 result.infer_ms,
513 result.refine_ms
514 ));
515 total.mse += result.mse;
516 total.edge_mse += result.edge_mse;
517 total.sad += result.sad;
518 total.flicker += result.flicker;
519 total.infer_ms += result.infer_ms;
520 total.refine_ms += result.refine_ms;
521 if index < shots {
522 save_sheet(&out, sample, &matte);
523 }
524 }
525 std::fs::write(out.join("scores.csv"), lines.join("\n")).expect("csv written");
526 let mean = |value: f64| value / count.max(1) as f64;
527 println!(
528 "{} {count} images: mse {:.2} edge_mse {:.2} sad {:.1} flicker {:.2} infer {:.1} ms refine {:.1} ms",
529 spec.name,
530 mean(total.mse),
531 mean(total.edge_mse),
532 mean(total.sad),
533 mean(total.flicker),
534 mean(total.infer_ms),
535 mean(total.refine_ms)
536 );
537}