BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / segmentation / model.rs

model.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
model.rs 4.2 KiB Download Raw
1use libwebrtc::native::yuv_helper::i420_to_abgr;
2use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
3
4use crate::mask::Mask;
5
6const CHANNELS: usize = 4;
7
8pub(crate) const MEDIAPIPE_BYTES: &[u8] =
9 include_bytes!("../../assets/selfie_segmentation_landscape.onnx");
10pub(crate) const MODNET_BYTES: &[u8] =
11 include_bytes!("../../assets/modnet_webcam_portrait_matting.onnx");
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum InputRange {
15 Unit,
16 Signed,
17}
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum Network {
21 MediaPipe,
22 Modnet,
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct ModelSpec {
27 pub name: &'static str,
28 pub network: Network,
29 pub width: usize,
30 pub height: usize,
31 pub range: InputRange,
32}
33
34pub const MEDIAPIPE: ModelSpec = ModelSpec {
35 name: "mediapipe-256x144",
36 network: Network::MediaPipe,
37 width: 256,
38 height: 144,
39 range: InputRange::Unit,
40};
41pub const MODNET_SMALL: ModelSpec = ModelSpec {
42 name: "modnet-320x192",
43 network: Network::Modnet,
44 width: 320,
45 height: 192,
46 range: InputRange::Signed,
47};
48pub const MODNET_LARGE: ModelSpec = ModelSpec {
49 name: "modnet-512x288",
50 network: Network::Modnet,
51 width: 512,
52 height: 288,
53 range: InputRange::Signed,
54};
55
56impl ModelSpec {
57 pub(crate) fn bytes(&self) -> &'static [u8] {
58 match self.network {
59 Network::MediaPipe => MEDIAPIPE_BYTES,
60 Network::Modnet => MODNET_BYTES,
61 }
62 }
63
64 pub fn input(&self, frame: &mut I420Buffer) -> Vec<f32> {
65 let (width, height) = (self.width as u32, self.height as u32);
66 let scaled = if (frame.width(), frame.height()) == (width, height) {
67 None
68 } else {
69 Some(frame.scale(width as i32, height as i32))
70 };
71 let source = scaled.as_ref().unwrap_or(&*frame);
72 let (stride_y, stride_u, stride_v) = source.strides();
73 let (plane_y, plane_u, plane_v) = source.data();
74 let mut rgba = vec![0u8; self.width * self.height * CHANNELS];
75 i420_to_abgr(
76 plane_y,
77 stride_y,
78 plane_u,
79 stride_u,
80 plane_v,
81 stride_v,
82 &mut rgba,
83 width * CHANNELS as u32,
84 width as i32,
85 height as i32,
86 );
87 self.input_from_rgba(&rgba)
88 }
89
90 pub(crate) fn input_from_rgba(&self, rgba: &[u8]) -> Vec<f32> {
91 let plane = self.width * self.height;
92 let (scale, offset) = match self.range {
93 InputRange::Unit => (1. / 255., 0.),
94 InputRange::Signed => (2. / 255., -1.),
95 };
96 let mut data = vec![0f32; 3 * plane];
97 for (index, pixel) in rgba.chunks_exact(CHANNELS).enumerate() {
98 for channel in 0..3 {
99 data[channel * plane + index] = f32::from(pixel[channel]) * scale + offset;
100 }
101 }
102 data
103 }
104
105 pub(crate) fn mask(&self, output: &[f32]) -> Option<Mask> {
106 if output.len() != self.width * self.height {
107 return None;
108 }
109 let mask = Mask::new(
110 self.width,
111 self.height,
112 output.iter().map(|value| value.clamp(0., 1.)).collect(),
113 );
114 Some(if self.network == Network::Modnet {
115 mask.into_matte()
116 } else {
117 mask
118 })
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125
126 #[test]
127 fn inputs_are_planar_and_scaled_to_the_model_range() {
128 let tiny = ModelSpec {
129 width: 2,
130 height: 1,
131 ..MODNET_SMALL
132 };
133 let rgba = [255, 0, 51, 255, 0, 255, 102, 255];
134 let signed = tiny.input_from_rgba(&rgba);
135 assert_eq!(signed.len(), 6);
136 assert!(
137 (signed[0] - 1.).abs() < 1e-6
138 && (signed[1] + 1.).abs() < 1e-6
139 && (signed[2] + 1.).abs() < 1e-6
140 );
141 let unit = ModelSpec {
142 range: InputRange::Unit,
143 ..tiny
144 }
145 .input_from_rgba(&rgba);
146 assert!((unit[4] - 0.2).abs() < 1e-6 && (unit[5] - 0.4).abs() < 1e-6);
147 assert!(tiny.mask(&[0.5]).is_none());
148 assert_eq!(tiny.mask(&[1.5, -0.2]).unwrap().values, vec![1., 0.]);
149 }
150}