| 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] |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::time::Instant; |
| 5 | |
| 6 | use calling::background::BackgroundPicture; |
| 7 | use calling::composite::{Backdrop, PicturePlanes, composite}; |
| 8 | use calling::blur::{MaskInference, compose_image}; |
| 9 | use calling::segmentation::FixedSegmenter; |
| 10 | use calling::segmentation::model::{MEDIAPIPE, MODNET_LARGE, MODNET_SMALL, ModelSpec}; |
| 11 | use calling::segmentation::runtime::Device; |
| 12 | use calling::camera::i420_from_rgba; |
| 13 | use calling::matte::{Matte, Planes, RefineSettings, refine_with}; |
| 14 | use image::imageops::FilterType; |
| 15 | use libwebrtc::native::yuv_helper::i420_to_abgr; |
| 16 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 17 | |
| 18 | const WIDTH: u32 = 1280; |
| 19 | const HEIGHT: u32 = 720; |
| 20 | const EDGE_RADIUS: usize = 12; |
| 21 | const JITTER_X: usize = 3; |
| 22 | const JITTER_Y: usize = 2; |
| 23 | |
| 24 | struct Sample { |
| 25 | name: String, |
| 26 | rgba: Vec<u8>, |
| 27 | truth: Vec<f32>, |
| 28 | } |
| 29 | |
| 30 | #[derive(Default, Clone, Copy)] |
| 31 | struct Score { |
| 32 | mse: f64, |
| 33 | edge_mse: f64, |
| 34 | sad: f64, |
| 35 | flicker: f64, |
| 36 | infer_ms: f64, |
| 37 | refine_ms: f64, |
| 38 | } |
| 39 | |
| 40 | fn load(foreground: &Path, alpha: &Path) -> Option<Sample> { |
| 41 | let photo = image::open(foreground).ok()?.resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle).to_rgba8().into_raw(); |
| 42 | let truth = image::open(alpha).ok()?.resize_to_fill(WIDTH, HEIGHT, FilterType::Triangle).to_luma8().into_raw(); |
| 43 | let name = foreground.file_stem()?.to_string_lossy().into_owned(); |
| 44 | Some(Sample { name, rgba: photo, truth: truth.iter().map(|&value| f32::from(value) / 255.).collect() }) |
| 45 | } |
| 46 | |
| 47 | fn samples(sets: &[PathBuf]) -> Vec<Sample> { |
| 48 | let mut found = Vec::new(); |
| 49 | for set in sets { |
| 50 | let Ok(entries) = std::fs::read_dir(set.join("fg")) else { continue }; |
| 51 | let mut paths: Vec<PathBuf> = entries.filter_map(|entry| entry.ok().map(|entry| entry.path())).collect(); |
| 52 | paths.sort(); |
| 53 | for path in paths { |
| 54 | let stem = path.file_stem().unwrap_or_default().to_string_lossy().into_owned(); |
| 55 | let alpha = ["png", "jpg"].iter().map(|extension| set.join("alpha").join(format!("{stem}.{extension}"))).find(|candidate| candidate.exists()); |
| 56 | if let Some(sample) = alpha.and_then(|alpha| load(&path, &alpha)) { |
| 57 | found.push(sample); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | found |
| 62 | } |
| 63 | |
| 64 | fn box_mean(values: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> { |
| 65 | let mut across = vec![0f32; values.len()]; |
| 66 | for row in 0..height { |
| 67 | let line = &values[row * width..][..width]; |
| 68 | let mut prefix = vec![0f32; width + 1]; |
| 69 | for (index, &value) in line.iter().enumerate() { |
| 70 | prefix[index + 1] = prefix[index] + value; |
| 71 | } |
| 72 | for column in 0..width { |
| 73 | let (low, high) = (column.saturating_sub(radius), (column + radius + 1).min(width)); |
| 74 | across[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32; |
| 75 | } |
| 76 | } |
| 77 | let mut output = vec![0f32; values.len()]; |
| 78 | for column in 0..width { |
| 79 | let mut prefix = vec![0f32; height + 1]; |
| 80 | for row in 0..height { |
| 81 | prefix[row + 1] = prefix[row] + across[row * width + column]; |
| 82 | } |
| 83 | for row in 0..height { |
| 84 | let (low, high) = (row.saturating_sub(radius), (row + radius + 1).min(height)); |
| 85 | output[row * width + column] = (prefix[high] - prefix[low]) / (high - low) as f32; |
| 86 | } |
| 87 | } |
| 88 | output |
| 89 | } |
| 90 | |
| 91 | fn edge_band(truth: &[f32]) -> Vec<bool> { |
| 92 | box_mean(truth, WIDTH as usize, HEIGHT as usize, EDGE_RADIUS).iter().map(|&mean| mean > 0.01 && mean < 0.99).collect() |
| 93 | } |
| 94 | |
| 95 | fn shifted(rgba: &[u8]) -> Vec<u8> { |
| 96 | let (width, height) = (WIDTH as usize, HEIGHT as usize); |
| 97 | let mut output = vec![0u8; rgba.len()]; |
| 98 | for row in 0..height { |
| 99 | for column in 0..width { |
| 100 | let (source_row, source_column) = (row.saturating_sub(JITTER_Y), column.saturating_sub(JITTER_X)); |
| 101 | let noise = ((row * 7919 + column * 104_729) % 9) as i16 - 4; |
| 102 | for channel in 0..4 { |
| 103 | let value = i16::from(rgba[(source_row * width + source_column) * 4 + channel]); |
| 104 | output[(row * width + column) * 4 + channel] = if channel == 3 { 255 } else { (value + noise).clamp(0, 255) as u8 }; |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | output |
| 109 | } |
| 110 | |
| 111 | fn settings() -> RefineSettings { |
| 112 | let read = |name: &str| std::env::var(name).ok().and_then(|value| value.parse::<f32>().ok()); |
| 113 | let defaults = RefineSettings::default(); |
| 114 | RefineSettings { |
| 115 | guide_width: read("GUIDE_WIDTH").map_or(defaults.guide_width, |value| value as usize), |
| 116 | edge_low: read("EDGE_LOW").unwrap_or(defaults.edge_low), |
| 117 | edge_high: read("EDGE_HIGH").unwrap_or(defaults.edge_high), |
| 118 | sure_person: read("SURE_PERSON").unwrap_or(defaults.sure_person), |
| 119 | sure_background: read("SURE_BACKGROUND").unwrap_or(defaults.sure_background), |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn matte_of(segmenter: &mut FixedSegmenter, rgba: &[u8]) -> (Matte, f64, f64) { |
| 124 | let camera = i420_from_rgba(rgba, WIDTH, HEIGHT); |
| 125 | let started = Instant::now(); |
| 126 | let mask = segmenter.infer(i420_from_rgba(rgba, WIDTH, HEIGHT)).expect("mask"); |
| 127 | let infer_ms = started.elapsed().as_secs_f64() * 1000.; |
| 128 | let started = Instant::now(); |
| 129 | let matte = refine_with(&mask, Planes::of(&camera), settings()); |
| 130 | (matte, infer_ms, started.elapsed().as_secs_f64() * 1000.) |
| 131 | } |
| 132 | |
| 133 | fn score(segmenter: &mut FixedSegmenter, sample: &Sample) -> (Score, Matte) { |
| 134 | let (matte, infer_ms, refine_ms) = matte_of(segmenter, &sample.rgba); |
| 135 | let band = edge_band(&sample.truth); |
| 136 | let (mut squared, mut edge_squared, mut edge_count, mut absolute) = (0f64, 0f64, 0usize, 0f64); |
| 137 | for ((&alpha, &truth), &edge) in matte.alpha.iter().zip(&sample.truth).zip(&band) { |
| 138 | let difference = f64::from(f32::from(alpha) / 255. - truth); |
| 139 | squared += difference * difference; |
| 140 | absolute += difference.abs(); |
| 141 | if edge { |
| 142 | edge_squared += difference * difference; |
| 143 | edge_count += 1; |
| 144 | } |
| 145 | } |
| 146 | let (jittered, ..) = matte_of(segmenter, &shifted(&sample.rgba)); |
| 147 | let (width, height) = (WIDTH as usize, HEIGHT as usize); |
| 148 | let mut flicker = 0f64; |
| 149 | let mut flicker_count = 0usize; |
| 150 | for row in JITTER_Y..height { |
| 151 | for column in JITTER_X..width { |
| 152 | let source = (row - JITTER_Y) * width + column - JITTER_X; |
| 153 | if band[source] { |
| 154 | flicker += f64::from(i16::from(jittered.alpha[row * width + column]).abs_diff(i16::from(matte.alpha[source]))); |
| 155 | flicker_count += 1; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | let pixels = (width * height) as f64; |
| 160 | let result = Score { |
| 161 | mse: squared / pixels * 1000., |
| 162 | edge_mse: edge_squared / edge_count.max(1) as f64 * 1000., |
| 163 | sad: absolute / 1000., |
| 164 | flicker: flicker / flicker_count.max(1) as f64, |
| 165 | infer_ms, |
| 166 | refine_ms, |
| 167 | }; |
| 168 | (result, matte) |
| 169 | } |
| 170 | |
| 171 | fn rgba_of(buffer: &I420Buffer) -> Vec<u8> { |
| 172 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 173 | let (plane_y, plane_u, plane_v) = buffer.data(); |
| 174 | let mut rgba = vec![0u8; (WIDTH * HEIGHT * 4) as usize]; |
| 175 | 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); |
| 176 | rgba |
| 177 | } |
| 178 | |
| 179 | fn backdrop() -> PicturePlanes { |
| 180 | let (width, height) = (64, 36); |
| 181 | let rgb = (0..width * height).flat_map(|index| { |
| 182 | let (x, y) = (index % width, index / width); |
| 183 | [(20 + x) as u8, (170 + y * 2) as u8, (60 + x * 2) as u8] |
| 184 | }); |
| 185 | let covered = BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop").covering(WIDTH as usize, HEIGHT as usize); |
| 186 | PicturePlanes::new(&covered, WIDTH as usize, HEIGHT as usize) |
| 187 | } |
| 188 | |
| 189 | fn gray_rgba(values: impl Iterator<Item = u8>) -> Vec<u8> { |
| 190 | values.flat_map(|value| [value, value, value, 255]).collect() |
| 191 | } |
| 192 | |
| 193 | fn save_sheet(out: &Path, sample: &Sample, matte: &Matte) { |
| 194 | let mut blurred = i420_from_rgba(&sample.rgba, WIDTH, HEIGHT); |
| 195 | composite(&mut blurred, matte, Backdrop::Blur); |
| 196 | let mut replaced = sample.rgba.clone(); |
| 197 | compose_image(&mut replaced, WIDTH as usize, HEIGHT as usize, matte, &backdrop()); |
| 198 | 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]; |
| 199 | let mut sheet = image::RgbaImage::new(WIDTH * 3, HEIGHT * 2); |
| 200 | for (index, tile) in tiles.into_iter().enumerate() { |
| 201 | let tile = image::RgbaImage::from_raw(WIDTH, HEIGHT, tile).expect("tile size"); |
| 202 | image::imageops::replace(&mut sheet, &tile, i64::from(WIDTH) * (index % 3) as i64, i64::from(HEIGHT) * (index / 3) as i64); |
| 203 | } |
| 204 | image::imageops::resize(&sheet, WIDTH * 3 / 2, HEIGHT, FilterType::Triangle).save(out.join(format!("{}.png", sample.name))).expect("sheet written"); |
| 205 | } |
| 206 | |
| 207 | fn main() { |
| 208 | let mut arguments: Vec<String> = std::env::args().skip(1).collect(); |
| 209 | let flag = |arguments: &mut Vec<String>, name: &str| -> Option<usize> { |
| 210 | let position = arguments.iter().position(|argument| argument == name)?; |
| 211 | let value = arguments.remove(position + 1).parse().ok(); |
| 212 | arguments.remove(position); |
| 213 | value |
| 214 | }; |
| 215 | let model = arguments.iter().position(|argument| argument == "--model").map(|position| { |
| 216 | let name = arguments.remove(position + 1); |
| 217 | arguments.remove(position); |
| 218 | name |
| 219 | }); |
| 220 | let spec: ModelSpec = [MEDIAPIPE, MODNET_SMALL, MODNET_LARGE].into_iter().find(|spec| Some(spec.name) == model.as_deref()).unwrap_or(MEDIAPIPE); |
| 221 | let gpu = arguments.iter().position(|argument| argument == "--gpu").map(|position| arguments.remove(position)).is_some(); |
| 222 | let shots = flag(&mut arguments, "--shots").unwrap_or(6); |
| 223 | let limit = flag(&mut arguments, "--limit").unwrap_or(usize::MAX); |
| 224 | let out = PathBuf::from(arguments.first().expect("out dir")); |
| 225 | let sets: Vec<PathBuf> = arguments[1..].iter().map(PathBuf::from).collect(); |
| 226 | std::fs::create_dir_all(&out).expect("out dir"); |
| 227 | let mut segmenter = FixedSegmenter::new(spec, if gpu { Device::Gpu } else { Device::Cpu { threads: 4 } }).expect("model"); |
| 228 | let all = samples(&sets); |
| 229 | let mut total = Score::default(); |
| 230 | let mut lines = vec!["name,mse,edge_mse,sad,flicker,infer_ms,refine_ms".to_owned()]; |
| 231 | let count = all.len().min(limit); |
| 232 | for (index, sample) in all.iter().take(limit).enumerate() { |
| 233 | let (result, matte) = score(&mut segmenter, sample); |
| 234 | 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)); |
| 235 | total.mse += result.mse; |
| 236 | total.edge_mse += result.edge_mse; |
| 237 | total.sad += result.sad; |
| 238 | total.flicker += result.flicker; |
| 239 | total.infer_ms += result.infer_ms; |
| 240 | total.refine_ms += result.refine_ms; |
| 241 | if index < shots { |
| 242 | save_sheet(&out, sample, &matte); |
| 243 | } |
| 244 | } |
| 245 | std::fs::write(out.join("scores.csv"), lines.join("\n")).expect("csv written"); |
| 246 | let mean = |value: f64| value / count.max(1) as f64; |
| 247 | println!( |
| 248 | "{} {count} images: mse {:.2} edge_mse {:.2} sad {:.1} flicker {:.2} infer {:.1} ms refine {:.1} ms", |
| 249 | spec.name, |
| 250 | mean(total.mse), |
| 251 | mean(total.edge_mse), |
| 252 | mean(total.sad), |
| 253 | mean(total.flicker), |
| 254 | mean(total.infer_ms), |
| 255 | mean(total.refine_ms) |
| 256 | ); |
| 257 | } |