oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=image.json schema_version=1 generator_version=64
// schema_sha256=850fff7da094fda90deb1885822908eb59de961a0e67423335fc6de4de68b058
//! Per-channel image color transforms.

use crate::{
	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
	runtime::{
		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
		KernelId, PushConstant,
	},
};

/// Three-channel normalization parameters.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NormalizationConfig {
	pub mean: [f32; 3],
	pub std: [f32; 3],
}

impl Default for NormalizationConfig {
	fn default() -> Self {
		Self {
			mean: [0.0; 3],
			std: [1.0; 3],
		}
	}
}

/// Apply `(pixel - mean[channel]) / std[channel]` to up to three channels.
pub fn normalize(input: &Image, parameters: NormalizationConfig) -> Result<Image> {
	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(
			"image::normalize requires an FP32 NCHW or CHW image",
		));
	}
	if input.channels() > 3 || input.batch_size() == 0 || input.height() == 0 || input.width() == 0 {
		return Err(Error::invalid_argument(
			"image::normalize requires a nonempty image with at most three channels",
		));
	}
	for channel in 0..input.channels() {
		if !parameters.mean[channel].is_finite()
			|| !parameters.std[channel].is_finite()
			|| parameters.std[channel] <= 0.0
		{
			return Err(Error::invalid_argument(
				"image::normalize requires finite means and positive finite standard deviations",
			));
		}
	}
	let batch = u32::try_from(input.batch_size())
		.map_err(|_| Error::out_of_range("image::normalize batch exceeds u32"))?;
	let channels = u32::try_from(input.channels())
		.map_err(|_| Error::out_of_range("image::normalize channels exceed u32"))?;
	let height = u32::try_from(input.height())
		.map_err(|_| Error::out_of_range("image::normalize height exceeds u32"))?;
	let width = u32::try_from(input.width())
		.map_err(|_| Error::out_of_range("image::normalize width exceeds u32"))?;
	let elements = input.as_matrix().num_elements();
	let matrix = Matrix::allocate(
		input.runtime(),
		input.as_matrix().shape().to_vec(),
		elements,
		DType::F32,
	)?;
	let output = Image::new(matrix, input.layout(), input.format())?;
	let attributes = [
		float("mean_0", parameters.mean[0]),
		float("mean_1", parameters.mean[1]),
		float("mean_2", parameters.mean[2]),
		float("std_0", parameters.std[0]),
		float("std_1", parameters.std[1]),
		float("std_2", parameters.std[2]),
	];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageNormalizeF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(height),
				PushConstant::U32(width),
				PushConstant::F32(parameters.mean[0]),
				PushConstant::F32(parameters.mean[1]),
				PushConstant::F32(parameters.mean[2]),
				PushConstant::F32(parameters.std[0]),
				PushConstant::F32(parameters.std[1]),
				PushConstant::F32(parameters.std[2]),
			],
			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::NORMALIZE,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Convert between three-channel RGB and BGR semantics, including identity.
pub fn convert_color(input: &Image, destination_format: crate::ImageFormat) -> Result<Image> {
	if !matches!(
		input.format(),
		crate::ImageFormat::Rgb | crate::ImageFormat::Bgr
	) || !matches!(
		destination_format,
		crate::ImageFormat::Rgb | crate::ImageFormat::Bgr
	) || input.dtype() != DType::F32
		|| !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(
			"image::convert_color currently admits FP32 NCHW/CHW RGB and BGR images",
		));
	}
	let batch = extent(input.batch_size(), "batch")?;
	let height = extent(input.height(), "height")?;
	let width = extent(input.width(), "width")?;
	if batch == 0 || height == 0 || width == 0 {
		return Err(Error::invalid_argument(
			"image::convert_color requires a nonempty image",
		));
	}
	let output = allocate(
		input,
		input.as_matrix().shape().to_vec(),
		destination_format,
	)?;
	let swap = u32::from(input.format() != destination_format);
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageConvertColorF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(height),
				PushConstant::U32(width),
				PushConstant::U32(swap),
			],
			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * 3],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CONVERT_COLOR,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &[
				enumeration("source_format", format_token(input.format())),
				enumeration("destination_format", format_token(destination_format)),
				enumeration("layout", layout_token(input.layout())),
			],
		},
	)?;
	Ok(output)
}

/// Bilinearly resize and normalize in one semantic and executable operation.
pub fn resize_normalize(
	input: &Image,
	width: u32,
	height: u32,
	parameters: NormalizationConfig,
) -> Result<Image> {
	validate_normalization(input, parameters)?;
	if width == 0 || height == 0 {
		return Err(Error::invalid_argument(
			"image::resize_normalize target extent must be nonzero",
		));
	}
	let batch = extent(input.batch_size(), "batch")?;
	let channels = extent(input.channels(), "channels")?;
	let input_height = extent(input.height(), "input height")?;
	let input_width = extent(input.width(), "input width")?;
	let shape = match input.layout() {
		ImageLayout::Nchw => vec![
			batch as usize,
			channels as usize,
			height as usize,
			width as usize,
		],
		ImageLayout::Chw => vec![channels as usize, height as usize, width as usize],
		_ => unreachable!("normalization validation admitted unsupported layout"),
	};
	let output = allocate(input, shape, input.format())?;
	let attributes = [
		unsigned("width", width),
		unsigned("height", height),
		float("mean0", parameters.mean[0]),
		float("mean1", parameters.mean[1]),
		float("mean2", parameters.mean[2]),
		float("std0", parameters.std[0]),
		float("std1", parameters.std[1]),
		float("std2", parameters.std[2]),
	];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageResizeNormalizeF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(input_height),
				PushConstant::U32(input_width),
				PushConstant::U32(height),
				PushConstant::U32(width),
				PushConstant::F32(parameters.mean[0]),
				PushConstant::F32(parameters.mean[1]),
				PushConstant::F32(parameters.mean[2]),
				PushConstant::F32(parameters.std[0]),
				PushConstant::F32(parameters.std[1]),
				PushConstant::F32(parameters.std[2]),
				PushConstant::U32(0),
			],
			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::RESIZE_NORMALIZE,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Blend a class palette over an RGB/RGBA image using an I32 label map.
pub fn segmentation_overlay(
	input: &Image,
	mask: &Matrix,
	palette: &Matrix,
	alpha: f32,
) -> Result<Image> {
	if input.dtype() != DType::F32
		|| input.layout() != ImageLayout::Nchw
		|| !matches!(
			input.format(),
			crate::ImageFormat::Rgb | crate::ImageFormat::Rgba
		) {
		return Err(Error::invalid_argument(
			"image::segmentation_overlay requires an FP32 NCHW RGB/RGBA image",
		));
	}
	if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
		return Err(Error::invalid_argument(
			"image::segmentation_overlay alpha must be finite and in [0,1]",
		));
	}
	let batch = input.batch_size();
	let height = input.height();
	let width = input.width();
	let valid_mask = mask.dtype() == DType::I32
		&& (mask.shape() == [batch, height, width] || mask.shape() == [batch, 1, height, width]);
	let valid_palette = palette.dtype() == DType::F32
		&& palette.shape().len() == 2
		&& palette.shape()[0] > 0
		&& palette.shape()[1] == 3;
	if !valid_mask
		|| !valid_palette
		|| !input.runtime().same_as(mask.runtime())
		|| !input.runtime().same_as(palette.runtime())
	{
		return Err(Error::invalid_argument(
			"image::segmentation_overlay requires same-runtime I32 [B,H,W]/[B,1,H,W] labels and FP32 [K,3] palette",
		));
	}
	let batch_u32 = extent(batch, "batch")?;
	let channels = extent(input.channels(), "channels")?;
	let height_u32 = extent(height, "height")?;
	let width_u32 = extent(width, "width")?;
	let classes = extent(palette.shape()[0], "class count")?;
	let output = allocate(input, input.as_matrix().shape().to_vec(), input.format())?;
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageSegmentationOverlayF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::read(mask.storage()),
				BufferBinding::read(palette.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch_u32),
				PushConstant::U32(channels),
				PushConstant::U32(height_u32),
				PushConstant::U32(width_u32),
				PushConstant::U32(classes),
				PushConstant::F32(alpha),
			],
			workgroups: [
				width_u32.div_ceil(16),
				height_u32.div_ceil(16),
				batch_u32 * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::SEGMENTATION_OVERLAY,
			inputs: &[
				ImageSemanticInput::Image(input),
				ImageSemanticInput::Matrix(mask),
				ImageSemanticInput::Matrix(palette),
			],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &[float("alpha", alpha)],
		},
	)?;
	Ok(output)
}

/// Color-space conversion code used by [`cvt_color`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColorConversion {
	/// `COLOR_RGB2GRAY` luma reduction.
	#[default]
	RgbToGray,
	/// `COLOR_BGR2GRAY` luma reduction.
	BgrToGray,
	/// `COLOR_GRAY2RGB` luminance replication.
	GrayToRgb,
	/// `COLOR_RGB2HSV` (H `[0, 360]`, S/V `[0, 1]`).
	RgbToHsv,
	/// `COLOR_BGR2HSV` (H `[0, 360]`, S/V `[0, 1]`).
	BgrToHsv,
	/// `COLOR_HSV2RGB` inverse transform.
	HsvToRgb,
	/// `COLOR_HSV2BGR` inverse transform.
	HsvToBgr,
	/// `COLOR_RGB2LAB` D65 (L `[0, 100]`).
	RgbToLab,
	/// `COLOR_BGR2LAB` D65 (L `[0, 100]`).
	BgrToLab,
	/// `COLOR_LAB2RGB` D65 inverse transform.
	LabToRgb,
	/// `COLOR_LAB2BGR` D65 inverse transform.
	LabToBgr,
	/// `COLOR_RGB2YCrCb` F32 chroma offset.
	RgbToYcrcb,
	/// `COLOR_BGR2YCrCb` F32 chroma offset.
	BgrToYcrcb,
	/// `COLOR_YCrCb2RGB` inverse transform.
	YcrcbToRgb,
	/// `COLOR_YCrCb2BGR` inverse transform.
	YcrcbToBgr,
}

impl ColorConversion {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::RgbToGray => "rgb_to_gray",
			Self::BgrToGray => "bgr_to_gray",
			Self::GrayToRgb => "gray_to_rgb",
			Self::RgbToHsv => "rgb_to_hsv",
			Self::BgrToHsv => "bgr_to_hsv",
			Self::HsvToRgb => "hsv_to_rgb",
			Self::HsvToBgr => "hsv_to_bgr",
			Self::RgbToLab => "rgb_to_lab",
			Self::BgrToLab => "bgr_to_lab",
			Self::LabToRgb => "lab_to_rgb",
			Self::LabToBgr => "lab_to_bgr",
			Self::RgbToYcrcb => "rgb_to_ycrcb",
			Self::BgrToYcrcb => "bgr_to_ycrcb",
			Self::YcrcbToRgb => "ycrcb_to_rgb",
			Self::YcrcbToBgr => "ycrcb_to_bgr",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::RgbToGray => 0,
			Self::BgrToGray => 1,
			Self::GrayToRgb => 2,
			Self::RgbToHsv => 3,
			Self::BgrToHsv => 4,
			Self::HsvToRgb => 5,
			Self::HsvToBgr => 6,
			Self::RgbToLab => 7,
			Self::BgrToLab => 8,
			Self::LabToRgb => 9,
			Self::LabToBgr => 10,
			Self::RgbToYcrcb => 11,
			Self::BgrToYcrcb => 12,
			Self::YcrcbToRgb => 13,
			Self::YcrcbToBgr => 14,
		}
	}
}

/// Convert an FP32 image between color spaces following `cvtColor`.
///
/// The conversion code owns the color-space contract, matching
/// OpenCV's `COLOR_*` pairs: channel-ordered inputs admit the
/// `Rgb`/`Bgr` sources and `Gray` admits the gray sources. The
/// output carries `Gray` for luminance results, `Rgb` for
/// gray-to-color results, and the input format otherwise; the
/// color-space interpretation of three-channel results follows the
/// conversion code exactly as it does for `cv::Mat`. HSV keeps
/// OpenCV's F32 ranges (H `[0, 360]`, S/V `[0, 1]`); Lab uses the
/// D65 XYZ intermediate (L `[0, 100]`, a/b signed); YCrCb applies
/// the F32 0.5 chroma offset.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW and
/// the source channel count matches the conversion.
pub fn cvt_color(input: &Image, conversion: ColorConversion) -> Result<Image> {
	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(
			"image::cvt_color requires an FP32 NCHW or CHW image",
		));
	}
	if input.batch_size() == 0 || input.height() == 0 || input.width() == 0 {
		return Err(Error::invalid_argument(
			"image::cvt_color requires a nonempty image",
		));
	}
	let (source_channels, output_channels, output_format) = match conversion {
		ColorConversion::GrayToRgb => (1usize, 3usize, crate::ImageFormat::Rgb),
		ColorConversion::RgbToGray | ColorConversion::BgrToGray => {
			(3usize, 1usize, crate::ImageFormat::Gray)
		}
		_ => (3usize, 3usize, input.format()),
	};
	if input.channels() != source_channels {
		return Err(Error::invalid_argument(
			"image::cvt_color source channel count does not match the conversion",
		));
	}
	let batch = extent(input.batch_size(), "batch")?;
	let image_height = extent(input.height(), "height")?;
	let image_width = extent(input.width(), "width")?;
	let mut shape = input.as_matrix().shape().to_vec();
	let rank = shape.len();
	shape[rank - 3] = output_channels;
	let output = allocate(input, shape, output_format)?;
	let attributes = [enumeration("conversion", conversion.token())];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageCvtColorF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(conversion.code()),
			],
			workgroups: [image_width.div_ceil(16), image_height.div_ceil(16), batch],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CVT_COLOR,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Analytic colormap used by [`apply_color_map`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColorMap {
	/// Blue-cyan-yellow-red ramp following `COLORMAP_JET`.
	#[default]
	Jet,
	/// Black-red-yellow-white ramp following `COLORMAP_HOT`.
	Hot,
	/// Full-saturation HSV hue wheel following `COLORMAP_HSV`.
	Hsv,
	/// Reversed-blue hue ramp following `COLORMAP_RAINBOW`.
	Rainbow,
}

impl ColorMap {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Jet => "jet",
			Self::Hot => "hot",
			Self::Hsv => "hsv",
			Self::Rainbow => "rainbow",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Jet => 0,
			Self::Hot => 1,
			Self::Hsv => 2,
			Self::Rainbow => 3,
		}
	}
}

/// Map a single-channel FP32 image to RGB through a colormap.
///
/// Each luminance value is clamped to `[0, 1]` and mapped by the
/// admitted analytic colormap definition (`Jet`, `Hot`, `Hsv`, or
/// `Rainbow`) to an RGB triplet, producing a three-channel Rgb
/// image per plane following the `applyColorMap` contract.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW
/// with a single channel.
pub fn apply_color_map(input: &Image, colormap: ColorMap) -> Result<Image> {
	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(
			"image::apply_color_map requires an FP32 NCHW or CHW image",
		));
	}
	if input.batch_size() == 0 || input.height() == 0 || input.width() == 0 || input.channels() != 1 {
		return Err(Error::invalid_argument(
			"image::apply_color_map requires a nonempty single-channel image",
		));
	}
	let batch = extent(input.batch_size(), "batch")?;
	let image_height = extent(input.height(), "height")?;
	let image_width = extent(input.width(), "width")?;
	let mut shape = input.as_matrix().shape().to_vec();
	let rank = shape.len();
	shape[rank - 3] = 3;
	let output = allocate(input, shape, crate::ImageFormat::Rgb)?;
	let attributes = [enumeration("colormap", colormap.token())];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageApplyColorMapF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(colormap.code()),
			],
			workgroups: [image_width.div_ceil(16), image_height.div_ceil(16), batch],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::APPLY_COLOR_MAP,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

fn validate_normalization(input: &Image, parameters: NormalizationConfig) -> Result<()> {
	if input.dtype() != DType::F32
		|| !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
		|| input.channels() > 3
		|| input.batch_size() == 0
		|| input.height() == 0
		|| input.width() == 0
	{
		return Err(Error::invalid_argument(
			"image normalization requires a nonempty FP32 NCHW/CHW image with at most three channels",
		));
	}
	for channel in 0..input.channels() {
		if !parameters.mean[channel].is_finite()
			|| !parameters.std[channel].is_finite()
			|| parameters.std[channel] <= 0.0
		{
			return Err(Error::invalid_argument(
				"image normalization requires finite means and positive finite standard deviations",
			));
		}
	}
	Ok(())
}

fn allocate(input: &Image, shape: Vec<usize>, format: crate::ImageFormat) -> Result<Image> {
	let elements = shape.iter().copied().try_fold(1usize, |count, value| {
		count
			.checked_mul(value)
			.ok_or_else(|| Error::out_of_range("image output size exceeds usize"))
	})?;
	u32::try_from(elements).map_err(|_| Error::out_of_range("image output size exceeds u32"))?;
	Image::new(
		Matrix::allocate(input.runtime(), shape, elements, DType::F32)?,
		input.layout(),
		format,
	)
}

fn extent(value: usize, label: &str) -> Result<u32> {
	u32::try_from(value).map_err(|_| Error::out_of_range(format!("image {label} exceeds u32")))
}
fn unsigned(name: &str, value: u32) -> OpAttribute {
	OpAttribute::UnsignedInteger {
		name: name.into(),
		value: u64::from(value),
	}
}
fn enumeration(name: &str, value: &str) -> OpAttribute {
	OpAttribute::Enum {
		name: name.into(),
		value: value.into(),
	}
}
const fn format_token(format: crate::ImageFormat) -> &'static str {
	match format {
		crate::ImageFormat::Gray => "gray",
		crate::ImageFormat::GrayAlpha => "gray_alpha",
		crate::ImageFormat::Rgb => "rgb",
		crate::ImageFormat::Rgba => "rgba",
		crate::ImageFormat::Bgr => "bgr",
		crate::ImageFormat::Bgra => "bgra",
	}
}

const fn layout_token(layout: crate::ImageLayout) -> &'static str {
	match layout {
		crate::ImageLayout::Nchw => "nchw",
		crate::ImageLayout::Nhwc => "nhwc",
		crate::ImageLayout::Chw => "chw",
		crate::ImageLayout::Hwc => "hwc",
		crate::ImageLayout::Hw => "hw",
	}
}

fn float(name: &str, value: f32) -> OpAttribute {
	OpAttribute::Float {
		name: name.into(),
		value: f64::from(value),
	}
}