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.runtime(),
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.runtime().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.runtime().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.runtime().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.runtime().same_as(mask.runtime())
275 || !input.runtime().same_as(palette.runtime())
276 {
277 return Err(Error::invalid_argument(
278 "image::segmentation_overlay requires same-runtime 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.runtime().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
325#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
327pub enum ColorConversion {
328 #[default]
330 RgbToGray,
331 BgrToGray,
333 GrayToRgb,
335 RgbToHsv,
337 BgrToHsv,
339 HsvToRgb,
341 HsvToBgr,
343 RgbToLab,
345 BgrToLab,
347 LabToRgb,
349 LabToBgr,
351 RgbToYcrcb,
353 BgrToYcrcb,
355 YcrcbToRgb,
357 YcrcbToBgr,
359}
360
361impl ColorConversion {
362 pub(super) const fn token(self) -> &'static str {
363 match self {
364 Self::RgbToGray => "rgb_to_gray",
365 Self::BgrToGray => "bgr_to_gray",
366 Self::GrayToRgb => "gray_to_rgb",
367 Self::RgbToHsv => "rgb_to_hsv",
368 Self::BgrToHsv => "bgr_to_hsv",
369 Self::HsvToRgb => "hsv_to_rgb",
370 Self::HsvToBgr => "hsv_to_bgr",
371 Self::RgbToLab => "rgb_to_lab",
372 Self::BgrToLab => "bgr_to_lab",
373 Self::LabToRgb => "lab_to_rgb",
374 Self::LabToBgr => "lab_to_bgr",
375 Self::RgbToYcrcb => "rgb_to_ycrcb",
376 Self::BgrToYcrcb => "bgr_to_ycrcb",
377 Self::YcrcbToRgb => "ycrcb_to_rgb",
378 Self::YcrcbToBgr => "ycrcb_to_bgr",
379 }
380 }
381
382 pub(super) const fn code(self) -> u32 {
383 match self {
384 Self::RgbToGray => 0,
385 Self::BgrToGray => 1,
386 Self::GrayToRgb => 2,
387 Self::RgbToHsv => 3,
388 Self::BgrToHsv => 4,
389 Self::HsvToRgb => 5,
390 Self::HsvToBgr => 6,
391 Self::RgbToLab => 7,
392 Self::BgrToLab => 8,
393 Self::LabToRgb => 9,
394 Self::LabToBgr => 10,
395 Self::RgbToYcrcb => 11,
396 Self::BgrToYcrcb => 12,
397 Self::YcrcbToRgb => 13,
398 Self::YcrcbToBgr => 14,
399 }
400 }
401}
402
403pub fn cvt_color(input: &Image, conversion: ColorConversion) -> Result<Image> {
421 if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
422 {
423 return Err(Error::invalid_argument(
424 "image::cvt_color requires an FP32 NCHW or CHW image",
425 ));
426 }
427 if input.batch_size() == 0 || input.height() == 0 || input.width() == 0 {
428 return Err(Error::invalid_argument(
429 "image::cvt_color requires a nonempty image",
430 ));
431 }
432 let (source_channels, output_channels, output_format) = match conversion {
433 ColorConversion::GrayToRgb => (1usize, 3usize, crate::ImageFormat::Rgb),
434 ColorConversion::RgbToGray | ColorConversion::BgrToGray => {
435 (3usize, 1usize, crate::ImageFormat::Gray)
436 }
437 _ => (3usize, 3usize, input.format()),
438 };
439 if input.channels() != source_channels {
440 return Err(Error::invalid_argument(
441 "image::cvt_color source channel count does not match the conversion",
442 ));
443 }
444 let batch = extent(input.batch_size(), "batch")?;
445 let image_height = extent(input.height(), "height")?;
446 let image_width = extent(input.width(), "width")?;
447 let mut shape = input.as_matrix().shape().to_vec();
448 let rank = shape.len();
449 shape[rank - 3] = output_channels;
450 let output = allocate(input, shape, output_format)?;
451 let attributes = [enumeration("conversion", conversion.token())];
452 input.runtime().record_image_semantic(
453 ComputeDispatch {
454 kernel: KernelId::ImageCvtColorF32,
455 buffers: &[
456 BufferBinding::read(input.storage()),
457 BufferBinding::write(output.storage()),
458 ],
459 push_constants: &[
460 PushConstant::U32(batch),
461 PushConstant::U32(image_height),
462 PushConstant::U32(image_width),
463 PushConstant::U32(conversion.code()),
464 ],
465 workgroups: [image_width.div_ceil(16), image_height.div_ceil(16), batch],
466 indirect: None,
467 },
468 ImageSemanticDispatch {
469 contract: crate::core::operation::image::CVT_COLOR,
470 inputs: &[ImageSemanticInput::Image(input)],
471 outputs: &[ImageSemanticOutput::Image(&output)],
472 attributes: &attributes,
473 },
474 )?;
475 Ok(output)
476}
477
478#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
480pub enum ColorMap {
481 #[default]
483 Jet,
484 Hot,
486 Hsv,
488 Rainbow,
490}
491
492impl ColorMap {
493 pub(super) const fn token(self) -> &'static str {
494 match self {
495 Self::Jet => "jet",
496 Self::Hot => "hot",
497 Self::Hsv => "hsv",
498 Self::Rainbow => "rainbow",
499 }
500 }
501
502 pub(super) const fn code(self) -> u32 {
503 match self {
504 Self::Jet => 0,
505 Self::Hot => 1,
506 Self::Hsv => 2,
507 Self::Rainbow => 3,
508 }
509 }
510}
511
512pub fn apply_color_map(input: &Image, colormap: ColorMap) -> Result<Image> {
524 if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
525 {
526 return Err(Error::invalid_argument(
527 "image::apply_color_map requires an FP32 NCHW or CHW image",
528 ));
529 }
530 if input.batch_size() == 0 || input.height() == 0 || input.width() == 0 || input.channels() != 1 {
531 return Err(Error::invalid_argument(
532 "image::apply_color_map requires a nonempty single-channel image",
533 ));
534 }
535 let batch = extent(input.batch_size(), "batch")?;
536 let image_height = extent(input.height(), "height")?;
537 let image_width = extent(input.width(), "width")?;
538 let mut shape = input.as_matrix().shape().to_vec();
539 let rank = shape.len();
540 shape[rank - 3] = 3;
541 let output = allocate(input, shape, crate::ImageFormat::Rgb)?;
542 let attributes = [enumeration("colormap", colormap.token())];
543 input.runtime().record_image_semantic(
544 ComputeDispatch {
545 kernel: KernelId::ImageApplyColorMapF32,
546 buffers: &[
547 BufferBinding::read(input.storage()),
548 BufferBinding::write(output.storage()),
549 ],
550 push_constants: &[
551 PushConstant::U32(batch),
552 PushConstant::U32(image_height),
553 PushConstant::U32(image_width),
554 PushConstant::U32(colormap.code()),
555 ],
556 workgroups: [image_width.div_ceil(16), image_height.div_ceil(16), batch],
557 indirect: None,
558 },
559 ImageSemanticDispatch {
560 contract: crate::core::operation::image::APPLY_COLOR_MAP,
561 inputs: &[ImageSemanticInput::Image(input)],
562 outputs: &[ImageSemanticOutput::Image(&output)],
563 attributes: &attributes,
564 },
565 )?;
566 Ok(output)
567}
568
569fn validate_normalization(input: &Image, parameters: NormalizationConfig) -> Result<()> {
570 if input.dtype() != DType::F32
571 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
572 || input.channels() > 3
573 || input.batch_size() == 0
574 || input.height() == 0
575 || input.width() == 0
576 {
577 return Err(Error::invalid_argument(
578 "image normalization requires a nonempty FP32 NCHW/CHW image with at most three channels",
579 ));
580 }
581 for channel in 0..input.channels() {
582 if !parameters.mean[channel].is_finite()
583 || !parameters.std[channel].is_finite()
584 || parameters.std[channel] <= 0.0
585 {
586 return Err(Error::invalid_argument(
587 "image normalization requires finite means and positive finite standard deviations",
588 ));
589 }
590 }
591 Ok(())
592}
593
594fn allocate(input: &Image, shape: Vec<usize>, format: crate::ImageFormat) -> Result<Image> {
595 let elements = shape.iter().copied().try_fold(1usize, |count, value| {
596 count
597 .checked_mul(value)
598 .ok_or_else(|| Error::out_of_range("image output size exceeds usize"))
599 })?;
600 u32::try_from(elements).map_err(|_| Error::out_of_range("image output size exceeds u32"))?;
601 Image::new(
602 Matrix::allocate(input.runtime(), shape, elements, DType::F32)?,
603 input.layout(),
604 format,
605 )
606}
607
608fn extent(value: usize, label: &str) -> Result<u32> {
609 u32::try_from(value).map_err(|_| Error::out_of_range(format!("image {label} exceeds u32")))
610}
611fn unsigned(name: &str, value: u32) -> OpAttribute {
612 OpAttribute::UnsignedInteger {
613 name: name.into(),
614 value: u64::from(value),
615 }
616}
617fn enumeration(name: &str, value: &str) -> OpAttribute {
618 OpAttribute::Enum {
619 name: name.into(),
620 value: value.into(),
621 }
622}
623const fn format_token(format: crate::ImageFormat) -> &'static str {
624 match format {
625 crate::ImageFormat::Gray => "gray",
626 crate::ImageFormat::GrayAlpha => "gray_alpha",
627 crate::ImageFormat::Rgb => "rgb",
628 crate::ImageFormat::Rgba => "rgba",
629 crate::ImageFormat::Bgr => "bgr",
630 crate::ImageFormat::Bgra => "bgra",
631 }
632}
633
634const fn layout_token(layout: crate::ImageLayout) -> &'static str {
635 match layout {
636 crate::ImageLayout::Nchw => "nchw",
637 crate::ImageLayout::Nhwc => "nhwc",
638 crate::ImageLayout::Chw => "chw",
639 crate::ImageLayout::Hwc => "hwc",
640 crate::ImageLayout::Hw => "hw",
641 }
642}
643
644fn float(name: &str, value: f32) -> OpAttribute {
645 OpAttribute::Float {
646 name: name.into(),
647 value: f64::from(value),
648 }
649}