1use crate::{
7 DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
8 runtime::{
9 BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10 KernelId, PushConstant,
11 },
12};
13
14#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct NormalizationConfig {
17 pub mean: [f32; 3],
18 pub std: [f32; 3],
19}
20
21impl Default for NormalizationConfig {
22 fn default() -> Self {
23 Self {
24 mean: [0.0; 3],
25 std: [1.0; 3],
26 }
27 }
28}
29
30pub fn normalize(input: &Image, parameters: NormalizationConfig) -> Result<Image> {
32 if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
33 {
34 return Err(Error::invalid_argument(
35 "image::normalize requires an FP32 NCHW or CHW image",
36 ));
37 }
38 if input.channels() > 3 || input.batch_size() == 0 || input.height() == 0 || input.width() == 0 {
39 return Err(Error::invalid_argument(
40 "image::normalize requires a nonempty image with at most three channels",
41 ));
42 }
43 for channel in 0..input.channels() {
44 if !parameters.mean[channel].is_finite()
45 || !parameters.std[channel].is_finite()
46 || parameters.std[channel] <= 0.0
47 {
48 return Err(Error::invalid_argument(
49 "image::normalize requires finite means and positive finite standard deviations",
50 ));
51 }
52 }
53 let batch = u32::try_from(input.batch_size())
54 .map_err(|_| Error::out_of_range("image::normalize batch exceeds u32"))?;
55 let channels = u32::try_from(input.channels())
56 .map_err(|_| Error::out_of_range("image::normalize channels exceed u32"))?;
57 let height = u32::try_from(input.height())
58 .map_err(|_| Error::out_of_range("image::normalize height exceeds u32"))?;
59 let width = u32::try_from(input.width())
60 .map_err(|_| Error::out_of_range("image::normalize width exceeds u32"))?;
61 let elements = input.as_matrix().num_elements();
62 let matrix = Matrix::allocate(
63 input.engine_handle(),
64 input.as_matrix().shape().to_vec(),
65 elements,
66 DType::F32,
67 )?;
68 let output = Image::new(matrix, input.layout(), input.format())?;
69 let attributes = [
70 float("mean_0", parameters.mean[0]),
71 float("mean_1", parameters.mean[1]),
72 float("mean_2", parameters.mean[2]),
73 float("std_0", parameters.std[0]),
74 float("std_1", parameters.std[1]),
75 float("std_2", parameters.std[2]),
76 ];
77 input.engine_handle().record_image_semantic(
78 ComputeDispatch {
79 kernel: KernelId::ImageNormalizeF32,
80 buffers: &[
81 BufferBinding::read(input.storage()),
82 BufferBinding::write(output.storage()),
83 ],
84 push_constants: &[
85 PushConstant::U32(batch),
86 PushConstant::U32(channels),
87 PushConstant::U32(height),
88 PushConstant::U32(width),
89 PushConstant::F32(parameters.mean[0]),
90 PushConstant::F32(parameters.mean[1]),
91 PushConstant::F32(parameters.mean[2]),
92 PushConstant::F32(parameters.std[0]),
93 PushConstant::F32(parameters.std[1]),
94 PushConstant::F32(parameters.std[2]),
95 ],
96 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
97 indirect: None,
98 },
99 ImageSemanticDispatch {
100 contract: crate::core::operation::image::NORMALIZE,
101 inputs: &[ImageSemanticInput::Image(input)],
102 outputs: &[ImageSemanticOutput::Image(&output)],
103 attributes: &attributes,
104 },
105 )?;
106 Ok(output)
107}
108
109pub fn convert_color(input: &Image, destination_format: crate::ImageFormat) -> Result<Image> {
111 if !matches!(
112 input.format(),
113 crate::ImageFormat::Rgb | crate::ImageFormat::Bgr
114 ) || !matches!(
115 destination_format,
116 crate::ImageFormat::Rgb | crate::ImageFormat::Bgr
117 ) || input.dtype() != DType::F32
118 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
119 {
120 return Err(Error::invalid_argument(
121 "image::convert_color currently admits FP32 NCHW/CHW RGB and BGR images",
122 ));
123 }
124 let batch = extent(input.batch_size(), "batch")?;
125 let height = extent(input.height(), "height")?;
126 let width = extent(input.width(), "width")?;
127 if batch == 0 || height == 0 || width == 0 {
128 return Err(Error::invalid_argument(
129 "image::convert_color requires a nonempty image",
130 ));
131 }
132 let output = allocate(
133 input,
134 input.as_matrix().shape().to_vec(),
135 destination_format,
136 )?;
137 let swap = u32::from(input.format() != destination_format);
138 input.engine_handle().record_image_semantic(
139 ComputeDispatch {
140 kernel: KernelId::ImageConvertColorF32,
141 buffers: &[
142 BufferBinding::read(input.storage()),
143 BufferBinding::write(output.storage()),
144 ],
145 push_constants: &[
146 PushConstant::U32(batch),
147 PushConstant::U32(height),
148 PushConstant::U32(width),
149 PushConstant::U32(swap),
150 ],
151 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * 3],
152 indirect: None,
153 },
154 ImageSemanticDispatch {
155 contract: crate::core::operation::image::CONVERT_COLOR,
156 inputs: &[ImageSemanticInput::Image(input)],
157 outputs: &[ImageSemanticOutput::Image(&output)],
158 attributes: &[
159 enumeration("source_format", format_token(input.format())),
160 enumeration("destination_format", format_token(destination_format)),
161 enumeration("layout", layout_token(input.layout())),
162 ],
163 },
164 )?;
165 Ok(output)
166}
167
168pub fn resize_normalize(
170 input: &Image,
171 width: u32,
172 height: u32,
173 parameters: NormalizationConfig,
174) -> Result<Image> {
175 validate_normalization(input, parameters)?;
176 if width == 0 || height == 0 {
177 return Err(Error::invalid_argument(
178 "image::resize_normalize target extent must be nonzero",
179 ));
180 }
181 let batch = extent(input.batch_size(), "batch")?;
182 let channels = extent(input.channels(), "channels")?;
183 let input_height = extent(input.height(), "input height")?;
184 let input_width = extent(input.width(), "input width")?;
185 let shape = match input.layout() {
186 ImageLayout::Nchw => vec![
187 batch as usize,
188 channels as usize,
189 height as usize,
190 width as usize,
191 ],
192 ImageLayout::Chw => vec![channels as usize, height as usize, width as usize],
193 _ => unreachable!("normalization validation admitted unsupported layout"),
194 };
195 let output = allocate(input, shape, input.format())?;
196 let attributes = [
197 unsigned("width", width),
198 unsigned("height", height),
199 float("mean0", parameters.mean[0]),
200 float("mean1", parameters.mean[1]),
201 float("mean2", parameters.mean[2]),
202 float("std0", parameters.std[0]),
203 float("std1", parameters.std[1]),
204 float("std2", parameters.std[2]),
205 ];
206 input.engine_handle().record_image_semantic(
207 ComputeDispatch {
208 kernel: KernelId::ImageResizeNormalizeF32,
209 buffers: &[
210 BufferBinding::read(input.storage()),
211 BufferBinding::write(output.storage()),
212 ],
213 push_constants: &[
214 PushConstant::U32(batch),
215 PushConstant::U32(channels),
216 PushConstant::U32(input_height),
217 PushConstant::U32(input_width),
218 PushConstant::U32(height),
219 PushConstant::U32(width),
220 PushConstant::F32(parameters.mean[0]),
221 PushConstant::F32(parameters.mean[1]),
222 PushConstant::F32(parameters.mean[2]),
223 PushConstant::F32(parameters.std[0]),
224 PushConstant::F32(parameters.std[1]),
225 PushConstant::F32(parameters.std[2]),
226 PushConstant::U32(0),
227 ],
228 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
229 indirect: None,
230 },
231 ImageSemanticDispatch {
232 contract: crate::core::operation::image::RESIZE_NORMALIZE,
233 inputs: &[ImageSemanticInput::Image(input)],
234 outputs: &[ImageSemanticOutput::Image(&output)],
235 attributes: &attributes,
236 },
237 )?;
238 Ok(output)
239}
240
241pub fn segmentation_overlay(
243 input: &Image,
244 mask: &Matrix,
245 palette: &Matrix,
246 alpha: f32,
247) -> Result<Image> {
248 if input.dtype() != DType::F32
249 || input.layout() != ImageLayout::Nchw
250 || !matches!(
251 input.format(),
252 crate::ImageFormat::Rgb | crate::ImageFormat::Rgba
253 ) {
254 return Err(Error::invalid_argument(
255 "image::segmentation_overlay requires an FP32 NCHW RGB/RGBA image",
256 ));
257 }
258 if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
259 return Err(Error::invalid_argument(
260 "image::segmentation_overlay alpha must be finite and in [0,1]",
261 ));
262 }
263 let batch = input.batch_size();
264 let height = input.height();
265 let width = input.width();
266 let valid_mask = mask.dtype() == DType::I32
267 && (mask.shape() == [batch, height, width] || mask.shape() == [batch, 1, height, width]);
268 let valid_palette = palette.dtype() == DType::F32
269 && palette.shape().len() == 2
270 && palette.shape()[0] > 0
271 && palette.shape()[1] == 3;
272 if !valid_mask
273 || !valid_palette
274 || !input.engine_handle().same_as(mask.engine_handle())
275 || !input.engine_handle().same_as(palette.engine_handle())
276 {
277 return Err(Error::invalid_argument(
278 "image::segmentation_overlay requires same-engine I32 [B,H,W]/[B,1,H,W] labels and FP32 [K,3] palette",
279 ));
280 }
281 let batch_u32 = extent(batch, "batch")?;
282 let channels = extent(input.channels(), "channels")?;
283 let height_u32 = extent(height, "height")?;
284 let width_u32 = extent(width, "width")?;
285 let classes = extent(palette.shape()[0], "class count")?;
286 let output = allocate(input, input.as_matrix().shape().to_vec(), input.format())?;
287 input.engine_handle().record_image_semantic(
288 ComputeDispatch {
289 kernel: KernelId::ImageSegmentationOverlayF32,
290 buffers: &[
291 BufferBinding::read(input.storage()),
292 BufferBinding::read(mask.storage()),
293 BufferBinding::read(palette.storage()),
294 BufferBinding::write(output.storage()),
295 ],
296 push_constants: &[
297 PushConstant::U32(batch_u32),
298 PushConstant::U32(channels),
299 PushConstant::U32(height_u32),
300 PushConstant::U32(width_u32),
301 PushConstant::U32(classes),
302 PushConstant::F32(alpha),
303 ],
304 workgroups: [
305 width_u32.div_ceil(16),
306 height_u32.div_ceil(16),
307 batch_u32 * channels,
308 ],
309 indirect: None,
310 },
311 ImageSemanticDispatch {
312 contract: crate::core::operation::image::SEGMENTATION_OVERLAY,
313 inputs: &[
314 ImageSemanticInput::Image(input),
315 ImageSemanticInput::Matrix(mask),
316 ImageSemanticInput::Matrix(palette),
317 ],
318 outputs: &[ImageSemanticOutput::Image(&output)],
319 attributes: &[float("alpha", alpha)],
320 },
321 )?;
322 Ok(output)
323}
324
325fn validate_normalization(input: &Image, parameters: NormalizationConfig) -> Result<()> {
326 if input.dtype() != DType::F32
327 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
328 || input.channels() > 3
329 || input.batch_size() == 0
330 || input.height() == 0
331 || input.width() == 0
332 {
333 return Err(Error::invalid_argument(
334 "image normalization requires a nonempty FP32 NCHW/CHW image with at most three channels",
335 ));
336 }
337 for channel in 0..input.channels() {
338 if !parameters.mean[channel].is_finite()
339 || !parameters.std[channel].is_finite()
340 || parameters.std[channel] <= 0.0
341 {
342 return Err(Error::invalid_argument(
343 "image normalization requires finite means and positive finite standard deviations",
344 ));
345 }
346 }
347 Ok(())
348}
349
350fn allocate(input: &Image, shape: Vec<usize>, format: crate::ImageFormat) -> Result<Image> {
351 let elements = shape.iter().copied().try_fold(1usize, |count, value| {
352 count
353 .checked_mul(value)
354 .ok_or_else(|| Error::out_of_range("image output size exceeds usize"))
355 })?;
356 u32::try_from(elements).map_err(|_| Error::out_of_range("image output size exceeds u32"))?;
357 Image::new(
358 Matrix::allocate(input.engine_handle(), shape, elements, DType::F32)?,
359 input.layout(),
360 format,
361 )
362}
363
364fn extent(value: usize, label: &str) -> Result<u32> {
365 u32::try_from(value).map_err(|_| Error::out_of_range(format!("image {label} exceeds u32")))
366}
367fn unsigned(name: &str, value: u32) -> OpAttribute {
368 OpAttribute::UnsignedInteger {
369 name: name.into(),
370 value: u64::from(value),
371 }
372}
373fn enumeration(name: &str, value: &str) -> OpAttribute {
374 OpAttribute::Enum {
375 name: name.into(),
376 value: value.into(),
377 }
378}
379const fn format_token(format: crate::ImageFormat) -> &'static str {
380 match format {
381 crate::ImageFormat::Gray => "gray",
382 crate::ImageFormat::GrayAlpha => "gray_alpha",
383 crate::ImageFormat::Rgb => "rgb",
384 crate::ImageFormat::Rgba => "rgba",
385 crate::ImageFormat::Bgr => "bgr",
386 crate::ImageFormat::Bgra => "bgra",
387 }
388}
389
390const fn layout_token(layout: crate::ImageLayout) -> &'static str {
391 match layout {
392 crate::ImageLayout::Nchw => "nchw",
393 crate::ImageLayout::Nhwc => "nhwc",
394 crate::ImageLayout::Chw => "chw",
395 crate::ImageLayout::Hwc => "hwc",
396 crate::ImageLayout::Hw => "hw",
397 }
398}
399
400fn float(name: &str, value: f32) -> OpAttribute {
401 OpAttribute::Float {
402 name: name.into(),
403 value: f64::from(value),
404 }
405}