Skip to main content

oa/image/
geometric.gen.rs

1// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
2// schema=image.json schema_version=1 generator_version=64
3// schema_sha256=850fff7da094fda90deb1885822908eb59de961a0e67423335fc6de4de68b058
4//! Stateless geometric image transformations.
5
6use crate::{
7	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
8	runtime::{
9		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10		KernelId, PushConstant,
11	},
12};
13
14/// Sampling rule used by [`resize`].
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum InterpolationMode {
17	/// Select the source pixel containing the scaled output coordinate.
18	Nearest,
19	/// Use half-pixel-center bilinear sampling with `align_corners = false`.
20	#[default]
21	Bilinear,
22	/// Box average over the scaled source rectangle (downscale); degenerates to nearest-pixel replication for upscale.
23	Area,
24	/// Bicubic convolution over the 4x4 source neighborhood using the Keys a=-0.75 kernel.
25	Cubic,
26	/// Lanczos-4 sinc resampling over the 8x8 source neighborhood with downscale filter widening.
27	Lanczos,
28}
29
30impl InterpolationMode {
31	pub(super) const fn token(self) -> &'static str {
32		match self {
33			Self::Nearest => "nearest",
34			Self::Bilinear => "bilinear",
35			Self::Area => "area",
36			Self::Cubic => "cubic",
37			Self::Lanczos => "lanczos",
38		}
39	}
40
41	const fn kernel(self) -> KernelId {
42		match self {
43			Self::Nearest => KernelId::ImageResizeNearestF32,
44			Self::Bilinear => KernelId::ImageResizeBilinearF32,
45			Self::Area => KernelId::ImageResizeAreaF32,
46			Self::Cubic => KernelId::ImageResizeCubicF32,
47			Self::Lanczos => KernelId::ImageResizeLanczosF32,
48		}
49	}
50
51	pub(super) const fn code(self) -> u32 {
52		match self {
53			Self::Nearest => 0,
54			Self::Bilinear => 1,
55			Self::Area => 2,
56			Self::Cubic => 3,
57			Self::Lanczos => 4,
58		}
59	}
60}
61
62/// Sampling behavior for coordinates outside an image.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub enum BorderMode {
65	/// Return the caller-provided constant value.
66	#[default]
67	Constant,
68	/// Extend the nearest edge pixel.
69	Replicate,
70	/// Reflect coordinates while repeating the edge pixel.
71	Reflect,
72	/// Reflect coordinates without repeating the edge pixel.
73	Reflect101,
74	/// Wrap coordinates periodically.
75	Wrap,
76}
77
78impl BorderMode {
79	pub(super) const fn token(self) -> &'static str {
80		match self {
81			Self::Constant => "constant",
82			Self::Replicate => "replicate",
83			Self::Reflect => "reflect",
84			Self::Reflect101 => "reflect_101",
85			Self::Wrap => "wrap",
86		}
87	}
88
89	pub(super) const fn code(self) -> u32 {
90		match self {
91			Self::Constant => 0,
92			Self::Replicate => 1,
93			Self::Reflect => 2,
94			Self::Reflect101 => 3,
95			Self::Wrap => 4,
96		}
97	}
98}
99
100#[derive(Clone, Copy)]
101struct ImageExtent {
102	batch: u32,
103	channels: u32,
104	height: u32,
105	width: u32,
106}
107
108/// Resize an FP32 channel-first image while preserving its layout and format.
109///
110/// NCHW and CHW storage are supported. Nearest sampling follows the donor OA
111/// floor-coordinate rule. Bilinear sampling uses half-pixel centers with
112/// `align_corners = false`. Area performs a coverage-weighted box average
113/// for downscales and pixel replication for upscales, matching `INTER_AREA`.
114/// Cubic uses the Keys a=-0.75 bicubic kernel over the 4x4 source
115/// neighborhood, and Lanczos uses the a=4 sinc kernel over the 8x8 source
116/// neighborhood with the filter widened by the inverse scale when
117/// downscaling, matching `INTER_CUBIC` and `INTER_LANCZOS4`.
118///
119/// The call records work asynchronously and returns an Image immediately.
120/// Reading its backing matrix is an explicit submission and observation point.
121///
122/// # Errors
123///
124/// Returns an error for a zero target extent, an empty source extent, a dtype or
125/// layout outside the admitted checkpoint, checked-size overflow, or a runtime
126/// recording failure.
127pub fn resize(
128	input: &Image,
129	target_width: u32,
130	target_height: u32,
131	interpolation: InterpolationMode,
132) -> Result<Image> {
133	if target_width == 0 || target_height == 0 {
134		return Err(Error::invalid_argument(
135			"image::resize target width and height must be non-zero",
136		));
137	}
138	if input.dtype() != DType::F32 {
139		return Err(Error::invalid_argument(format!(
140			"image::resize requires f32 storage; received {}",
141			input.dtype().token()
142		)));
143	}
144	if !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw) {
145		return Err(Error::invalid_argument(format!(
146			"image::resize currently supports Nchw and Chw layouts; received {:?}",
147			input.layout()
148		)));
149	}
150	if input.batch_size() == 0 || input.width() == 0 || input.height() == 0 {
151		return Err(Error::invalid_argument(
152			"image::resize source batch, width, and height must be non-zero",
153		));
154	}
155
156	let batch = u32_extent(input.batch_size(), "image::resize batch")?;
157	let channels = u32_extent(input.channels(), "image::resize channels")?;
158	let input_height = u32_extent(input.height(), "image::resize input height")?;
159	let input_width = u32_extent(input.width(), "image::resize input width")?;
160	u32_extent(
161		input.as_matrix().num_elements(),
162		"image::resize input element count",
163	)?;
164	let batch_channels = batch
165		.checked_mul(channels)
166		.ok_or_else(|| Error::out_of_range("image::resize batch-channel dispatch exceeds u32"))?;
167	let target_width_usize = usize::try_from(target_width)
168		.map_err(|_| Error::out_of_range("image::resize target width exceeds usize"))?;
169	let target_height_usize = usize::try_from(target_height)
170		.map_err(|_| Error::out_of_range("image::resize target height exceeds usize"))?;
171	let output_shape = match input.layout() {
172		ImageLayout::Nchw => vec![
173			input.batch_size(),
174			input.channels(),
175			target_height_usize,
176			target_width_usize,
177		],
178		ImageLayout::Chw => vec![input.channels(), target_height_usize, target_width_usize],
179		_ => unreachable!("unsupported layouts returned above"),
180	};
181	let output_elements = output_shape
182		.iter()
183		.copied()
184		.try_fold(1_usize, |count, extent| {
185			count
186				.checked_mul(extent)
187				.ok_or_else(|| Error::out_of_range("image::resize output element count exceeds usize"))
188		})?;
189	u32_extent(output_elements, "image::resize output element count")?;
190	let output_matrix = Matrix::allocate(input.runtime(), output_shape, output_elements, DType::F32)?;
191	let output = Image::new(output_matrix, input.layout(), input.format())?;
192	let kernel = interpolation.kernel();
193	let buffers = [
194		BufferBinding::read(input.storage()),
195		BufferBinding::write(output.storage()),
196	];
197	let push_constants = [
198		PushConstant::U32(batch),
199		PushConstant::U32(channels),
200		PushConstant::U32(input_height),
201		PushConstant::U32(input_width),
202		PushConstant::U32(target_height),
203		PushConstant::U32(target_width),
204	];
205	let mut workgroups = kernel.output_workgroups(target_width, target_height);
206	workgroups[2] = batch_channels;
207	let attributes = [
208		OpAttribute::UnsignedInteger {
209			name: "target_width".into(),
210			value: u64::from(target_width),
211		},
212		OpAttribute::UnsignedInteger {
213			name: "target_height".into(),
214			value: u64::from(target_height),
215		},
216		OpAttribute::Enum {
217			name: "interpolation".into(),
218			value: interpolation.token().into(),
219		},
220	];
221	input.runtime().record_image_semantic(
222		ComputeDispatch {
223			kernel,
224			buffers: &buffers,
225			push_constants: &push_constants,
226			workgroups,
227			indirect: None,
228		},
229		ImageSemanticDispatch {
230			contract: crate::core::operation::image::RESIZE,
231			inputs: &[ImageSemanticInput::Image(input)],
232			outputs: &[ImageSemanticOutput::Image(&output)],
233			attributes: &attributes,
234		},
235	)?;
236	Ok(output)
237}
238
239/// Extract a region, clipping its right and bottom edges to the source extent.
240pub fn crop(input: &Image, x: u32, y: u32, width: u32, height: u32) -> Result<Image> {
241	let extent = validate_image(input, "image::crop")?;
242	if width == 0 || height == 0 || x >= extent.width || y >= extent.height {
243		return Err(Error::invalid_argument(
244			"image::crop requires a nonzero region whose origin is inside the image",
245		));
246	}
247	let output_width = width.min(extent.width - x);
248	let output_height = height.min(extent.height - y);
249	let output = allocate_image(input, output_width, output_height, "image::crop")?;
250	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
251	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
252	let planes = u32_extent(
253		output
254			.batch_size()
255			.checked_mul(output.channels())
256			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
257		"image operation batch-channel dispatch",
258	)?;
259	let mut workgroups = KernelId::ImageCropF32.output_workgroups(dispatch_width, dispatch_height);
260	workgroups[2] = planes;
261	input.runtime().record_image_semantic(
262		ComputeDispatch {
263			kernel: KernelId::ImageCropF32,
264			buffers: &[
265				BufferBinding::read(input.storage()),
266				BufferBinding::write(output.storage()),
267			],
268			push_constants: &[
269				PushConstant::U32(extent.batch),
270				PushConstant::U32(extent.channels),
271				PushConstant::U32(extent.height),
272				PushConstant::U32(extent.width),
273				PushConstant::U32(x),
274				PushConstant::U32(y),
275				PushConstant::U32(output_height),
276				PushConstant::U32(output_width),
277			],
278			workgroups,
279			indirect: None,
280		},
281		ImageSemanticDispatch {
282			contract: crate::core::operation::image::CROP,
283			inputs: &[ImageSemanticInput::Image(input)],
284			outputs: &[ImageSemanticOutput::Image(&output)],
285			attributes: &[
286				unsigned("x", x),
287				unsigned("y", y),
288				unsigned("width", width),
289				unsigned("height", height),
290			],
291		},
292	)?;
293	Ok(output)
294}
295
296/// Flip an image horizontally, vertically, or along both axes.
297pub fn flip(input: &Image, horizontal: bool, vertical: bool) -> Result<Image> {
298	let extent = validate_image(input, "image::flip")?;
299	let output = allocate_image(input, extent.width, extent.height, "image::flip")?;
300	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
301	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
302	let planes = u32_extent(
303		output
304			.batch_size()
305			.checked_mul(output.channels())
306			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
307		"image operation batch-channel dispatch",
308	)?;
309	let mut workgroups = KernelId::ImageFlipF32.output_workgroups(dispatch_width, dispatch_height);
310	workgroups[2] = planes;
311	input.runtime().record_image_semantic(
312		ComputeDispatch {
313			kernel: KernelId::ImageFlipF32,
314			buffers: &[
315				BufferBinding::read(input.storage()),
316				BufferBinding::write(output.storage()),
317			],
318			push_constants: &[
319				PushConstant::U32(extent.batch),
320				PushConstant::U32(extent.channels),
321				PushConstant::U32(extent.height),
322				PushConstant::U32(extent.width),
323				PushConstant::U32(u32::from(horizontal)),
324				PushConstant::U32(u32::from(vertical)),
325			],
326			workgroups,
327			indirect: None,
328		},
329		ImageSemanticDispatch {
330			contract: crate::core::operation::image::FLIP,
331			inputs: &[ImageSemanticInput::Image(input)],
332			outputs: &[ImageSemanticOutput::Image(&output)],
333			attributes: &[
334				boolean("horizontal", horizontal),
335				boolean("vertical", vertical),
336			],
337		},
338	)?;
339	Ok(output)
340}
341
342/// Rotate clockwise by a multiple of 90 degrees.
343pub fn rotate(input: &Image, degrees: u32) -> Result<Image> {
344	let extent = validate_image(input, "image::rotate")?;
345	let normalized = degrees % 360;
346	if !matches!(normalized, 0 | 90 | 180 | 270) {
347		return Err(Error::invalid_argument(
348			"image::rotate degrees must be a multiple of 90",
349		));
350	}
351	let (output_width, output_height) = if matches!(normalized, 90 | 270) {
352		(extent.height, extent.width)
353	} else {
354		(extent.width, extent.height)
355	};
356	let output = allocate_image(input, output_width, output_height, "image::rotate")?;
357	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
358	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
359	let planes = u32_extent(
360		output
361			.batch_size()
362			.checked_mul(output.channels())
363			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
364		"image operation batch-channel dispatch",
365	)?;
366	let mut workgroups = KernelId::ImageRotateF32.output_workgroups(dispatch_width, dispatch_height);
367	workgroups[2] = planes;
368	input.runtime().record_image_semantic(
369		ComputeDispatch {
370			kernel: KernelId::ImageRotateF32,
371			buffers: &[
372				BufferBinding::read(input.storage()),
373				BufferBinding::write(output.storage()),
374			],
375			push_constants: &[
376				PushConstant::U32(extent.batch),
377				PushConstant::U32(extent.channels),
378				PushConstant::U32(extent.height),
379				PushConstant::U32(extent.width),
380				PushConstant::U32(output_height),
381				PushConstant::U32(output_width),
382				PushConstant::U32(normalized),
383			],
384			workgroups,
385			indirect: None,
386		},
387		ImageSemanticDispatch {
388			contract: crate::core::operation::image::ROTATE,
389			inputs: &[ImageSemanticInput::Image(input)],
390			outputs: &[ImageSemanticOutput::Image(&output)],
391			attributes: &[unsigned("degrees", degrees)],
392		},
393	)?;
394	Ok(output)
395}
396
397/// Add asymmetric padding with an explicit border policy.
398#[allow(clippy::too_many_arguments)]
399pub fn pad(
400	input: &Image,
401	left: u32,
402	right: u32,
403	top: u32,
404	bottom: u32,
405	border: BorderMode,
406	border_value: f32,
407) -> Result<Image> {
408	let extent = validate_image(input, "image::pad")?;
409	if !border_value.is_finite() {
410		return Err(Error::invalid_argument(
411			"image::pad border value must be finite",
412		));
413	}
414	let output_width = extent
415		.width
416		.checked_add(left)
417		.and_then(|value| value.checked_add(right))
418		.ok_or_else(|| Error::out_of_range("image::pad output width exceeds u32"))?;
419	let output_height = extent
420		.height
421		.checked_add(top)
422		.and_then(|value| value.checked_add(bottom))
423		.ok_or_else(|| Error::out_of_range("image::pad output height exceeds u32"))?;
424	let output = allocate_image(input, output_width, output_height, "image::pad")?;
425	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
426	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
427	let planes = u32_extent(
428		output
429			.batch_size()
430			.checked_mul(output.channels())
431			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
432		"image operation batch-channel dispatch",
433	)?;
434	let mut workgroups = KernelId::ImagePadF32.output_workgroups(dispatch_width, dispatch_height);
435	workgroups[2] = planes;
436	input.runtime().record_image_semantic(
437		ComputeDispatch {
438			kernel: KernelId::ImagePadF32,
439			buffers: &[
440				BufferBinding::read(input.storage()),
441				BufferBinding::write(output.storage()),
442			],
443			push_constants: &[
444				PushConstant::U32(extent.batch),
445				PushConstant::U32(extent.channels),
446				PushConstant::U32(extent.height),
447				PushConstant::U32(extent.width),
448				PushConstant::U32(output_height),
449				PushConstant::U32(output_width),
450				PushConstant::U32(top),
451				PushConstant::U32(left),
452				PushConstant::U32(border.code()),
453				PushConstant::F32(border_value),
454			],
455			workgroups,
456			indirect: None,
457		},
458		ImageSemanticDispatch {
459			contract: crate::core::operation::image::PAD,
460			inputs: &[ImageSemanticInput::Image(input)],
461			outputs: &[ImageSemanticOutput::Image(&output)],
462			attributes: &[
463				unsigned("left", left),
464				unsigned("right", right),
465				unsigned("top", top),
466				unsigned("bottom", bottom),
467				enumeration("border", border.token()),
468				float("border_value", border_value),
469			],
470		},
471	)?;
472	Ok(output)
473}
474
475/// Extract a centered region with the requested exact extent.
476pub fn center_crop(input: &Image, width: u32, height: u32) -> Result<Image> {
477	let extent = validate_image(input, "image::center_crop")?;
478	if width == 0 || height == 0 || width > extent.width || height > extent.height {
479		return Err(Error::invalid_argument(
480			"image::center_crop extent must be nonzero and fit inside the image",
481		));
482	}
483	let x = (extent.width - width) / 2;
484	let y = (extent.height - height) / 2;
485	let output = allocate_image(input, width, height, "image::center_crop")?;
486	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
487	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
488	let planes = u32_extent(
489		output
490			.batch_size()
491			.checked_mul(output.channels())
492			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
493		"image operation batch-channel dispatch",
494	)?;
495	let mut workgroups =
496		KernelId::ImageCenterCropF32.output_workgroups(dispatch_width, dispatch_height);
497	workgroups[2] = planes;
498	input.runtime().record_image_semantic(
499		ComputeDispatch {
500			kernel: KernelId::ImageCenterCropF32,
501			buffers: &[
502				BufferBinding::read(input.storage()),
503				BufferBinding::write(output.storage()),
504			],
505			push_constants: &[
506				PushConstant::U32(extent.batch),
507				PushConstant::U32(extent.channels),
508				PushConstant::U32(extent.height),
509				PushConstant::U32(extent.width),
510				PushConstant::U32(x),
511				PushConstant::U32(y),
512				PushConstant::U32(height),
513				PushConstant::U32(width),
514			],
515			workgroups,
516			indirect: None,
517		},
518		ImageSemanticDispatch {
519			contract: crate::core::operation::image::CENTER_CROP,
520			inputs: &[ImageSemanticInput::Image(input)],
521			outputs: &[ImageSemanticOutput::Image(&output)],
522			attributes: &[unsigned("width", width), unsigned("height", height)],
523		},
524	)?;
525	Ok(output)
526}
527
528/// Resample an image from an FP32 absolute-coordinate map shaped
529/// `[1|batch, 2, output_height, output_width]`.
530pub fn remap(
531	input: &Image,
532	map: &Matrix,
533	interpolation: InterpolationMode,
534	border: BorderMode,
535	border_value: f32,
536) -> Result<Image> {
537	let extent = validate_warp_inputs(input, map, "image::remap", border_value)?;
538	if map.shape().len() != 4
539		|| map.shape()[1] != 2
540		|| map.shape()[2] == 0
541		|| map.shape()[3] == 0
542		|| !matches!(map.shape()[0], 1) && map.shape()[0] != input.batch_size()
543	{
544		return Err(Error::invalid_argument(
545			"image::remap map must have shape [1|batch, 2, output_height, output_width]",
546		));
547	}
548	let map_batch = u32_extent(map.shape()[0], "image::remap map batch")?;
549	let output_height = u32_extent(map.shape()[2], "image::remap output height")?;
550	let output_width = u32_extent(map.shape()[3], "image::remap output width")?;
551	let output = allocate_image(input, output_width, output_height, "image::remap")?;
552	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
553	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
554	let planes = u32_extent(
555		output
556			.batch_size()
557			.checked_mul(output.channels())
558			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
559		"image operation batch-channel dispatch",
560	)?;
561	let mut workgroups = KernelId::ImageRemapF32.output_workgroups(dispatch_width, dispatch_height);
562	workgroups[2] = planes;
563	input.runtime().record_image_semantic(
564		ComputeDispatch {
565			kernel: KernelId::ImageRemapF32,
566			buffers: &[
567				BufferBinding::read(input.storage()),
568				BufferBinding::read(map.storage()),
569				BufferBinding::write(output.storage()),
570			],
571			push_constants: &[
572				PushConstant::U32(extent.batch),
573				PushConstant::U32(extent.channels),
574				PushConstant::U32(extent.height),
575				PushConstant::U32(extent.width),
576				PushConstant::U32(output_height),
577				PushConstant::U32(output_width),
578				PushConstant::U32(interpolation.code()),
579				PushConstant::U32(border.code()),
580				PushConstant::U32(map_batch),
581				PushConstant::F32(border_value),
582			],
583			workgroups,
584			indirect: None,
585		},
586		ImageSemanticDispatch {
587			contract: crate::core::operation::image::REMAP,
588			inputs: &[
589				ImageSemanticInput::Image(input),
590				ImageSemanticInput::Matrix(map),
591			],
592			outputs: &[ImageSemanticOutput::Image(&output)],
593			attributes: &[
594				enumeration("interpolation", interpolation.token()),
595				enumeration("border", border.token()),
596				float("border_value", border_value),
597			],
598		},
599	)?;
600	Ok(output)
601}
602
603/// Apply an inverse FP32 2x3 affine transform to an image.
604#[allow(clippy::too_many_arguments)]
605pub fn warp_affine(
606	input: &Image,
607	transform: &Matrix,
608	width: u32,
609	height: u32,
610	interpolation: InterpolationMode,
611	border: BorderMode,
612	border_value: f32,
613) -> Result<Image> {
614	if transform.shape() != [2, 3] {
615		return Err(Error::invalid_argument(
616			"image::warp_affine transform must have shape [2, 3]",
617		));
618	}
619	if width == 0 || height == 0 {
620		return Err(Error::invalid_argument(
621			"image::warp_affine output width and height must be nonzero",
622		));
623	}
624	let extent = validate_warp_inputs(input, transform, "image::warp_affine", border_value)?;
625	let output = allocate_image(input, width, height, "image::warp_affine")?;
626	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
627	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
628	let planes = u32_extent(
629		output
630			.batch_size()
631			.checked_mul(output.channels())
632			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
633		"image operation batch-channel dispatch",
634	)?;
635	let mut workgroups =
636		KernelId::ImageWarpAffineF32.output_workgroups(dispatch_width, dispatch_height);
637	workgroups[2] = planes;
638	input.runtime().record_image_semantic(
639		ComputeDispatch {
640			kernel: KernelId::ImageWarpAffineF32,
641			buffers: &[
642				BufferBinding::read(input.storage()),
643				BufferBinding::read(transform.storage()),
644				BufferBinding::write(output.storage()),
645			],
646			push_constants: &[
647				PushConstant::U32(extent.batch),
648				PushConstant::U32(extent.channels),
649				PushConstant::U32(extent.height),
650				PushConstant::U32(extent.width),
651				PushConstant::U32(height),
652				PushConstant::U32(width),
653				PushConstant::U32(interpolation.code()),
654				PushConstant::U32(border.code()),
655				PushConstant::F32(border_value),
656			],
657			workgroups,
658			indirect: None,
659		},
660		ImageSemanticDispatch {
661			contract: crate::core::operation::image::WARP_AFFINE,
662			inputs: &[
663				ImageSemanticInput::Image(input),
664				ImageSemanticInput::Matrix(transform),
665			],
666			outputs: &[ImageSemanticOutput::Image(&output)],
667			attributes: &[
668				unsigned("width", width),
669				unsigned("height", height),
670				enumeration("interpolation", interpolation.token()),
671				enumeration("border", border.token()),
672				float("border_value", border_value),
673			],
674		},
675	)?;
676	Ok(output)
677}
678
679/// Apply an inverse FP32 3x3 perspective transform to an image.
680#[allow(clippy::too_many_arguments)]
681pub fn warp_perspective(
682	input: &Image,
683	transform: &Matrix,
684	width: u32,
685	height: u32,
686	interpolation: InterpolationMode,
687	border: BorderMode,
688	border_value: f32,
689) -> Result<Image> {
690	if transform.shape() != [3, 3] {
691		return Err(Error::invalid_argument(
692			"image::warp_perspective transform must have shape [3, 3]",
693		));
694	}
695	if width == 0 || height == 0 {
696		return Err(Error::invalid_argument(
697			"image::warp_perspective output width and height must be nonzero",
698		));
699	}
700	let extent = validate_warp_inputs(input, transform, "image::warp_perspective", border_value)?;
701	let output = allocate_image(input, width, height, "image::warp_perspective")?;
702	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
703	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
704	let planes = u32_extent(
705		output
706			.batch_size()
707			.checked_mul(output.channels())
708			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
709		"image operation batch-channel dispatch",
710	)?;
711	let mut workgroups =
712		KernelId::ImageWarpPerspectiveF32.output_workgroups(dispatch_width, dispatch_height);
713	workgroups[2] = planes;
714	input.runtime().record_image_semantic(
715		ComputeDispatch {
716			kernel: KernelId::ImageWarpPerspectiveF32,
717			buffers: &[
718				BufferBinding::read(input.storage()),
719				BufferBinding::read(transform.storage()),
720				BufferBinding::write(output.storage()),
721			],
722			push_constants: &[
723				PushConstant::U32(extent.batch),
724				PushConstant::U32(extent.channels),
725				PushConstant::U32(extent.height),
726				PushConstant::U32(extent.width),
727				PushConstant::U32(height),
728				PushConstant::U32(width),
729				PushConstant::U32(interpolation.code()),
730				PushConstant::U32(border.code()),
731				PushConstant::F32(border_value),
732			],
733			workgroups,
734			indirect: None,
735		},
736		ImageSemanticDispatch {
737			contract: crate::core::operation::image::WARP_PERSPECTIVE,
738			inputs: &[
739				ImageSemanticInput::Image(input),
740				ImageSemanticInput::Matrix(transform),
741			],
742			outputs: &[ImageSemanticOutput::Image(&output)],
743			attributes: &[
744				unsigned("width", width),
745				unsigned("height", height),
746				enumeration("interpolation", interpolation.token()),
747				enumeration("border", border.token()),
748				float("border_value", border_value),
749			],
750		},
751	)?;
752	Ok(output)
753}
754
755/// Halve an FP32 image with the `pyrDown` Gaussian-decimate contract.
756///
757/// Each output pixel gathers the 5x5 `[1, 4, 6, 4, 1]` Gaussian
758/// neighborhood centered on the doubled source coordinate, following
759/// OpenCV's `BORDER_DEFAULT` (reflect-101) edge rule. Output spatial
760/// extents are `(extent + 1) / 2` per axis; layout and format are
761/// preserved.
762///
763/// # Errors
764///
765/// Returns an error unless the image is nonempty FP32 NCHW/CHW and all
766/// sizes fit the shader ABI.
767pub fn pyr_down(input: &Image) -> Result<Image> {
768	let extent = validate_image(input, "image::pyr_down")?;
769	let output_width = extent.width.div_ceil(2);
770	let output_height = extent.height.div_ceil(2);
771	let output = allocate_image(input, output_width, output_height, "image::pyr_down")?;
772	let planes = extent
773		.batch
774		.checked_mul(extent.channels)
775		.ok_or_else(|| Error::out_of_range("image::pyr_down batch-channel dispatch exceeds u32"))?;
776	let workgroups = [
777		output_width.div_ceil(16),
778		output_height.div_ceil(16),
779		planes,
780	];
781	input.runtime().record_image_semantic(
782		ComputeDispatch {
783			kernel: KernelId::ImagePyrDownF32,
784			buffers: &[
785				BufferBinding::read(input.storage()),
786				BufferBinding::write(output.storage()),
787			],
788			push_constants: &[
789				PushConstant::U32(extent.batch),
790				PushConstant::U32(extent.channels),
791				PushConstant::U32(extent.height),
792				PushConstant::U32(extent.width),
793				PushConstant::U32(output_height),
794				PushConstant::U32(output_width),
795			],
796			workgroups,
797			indirect: None,
798		},
799		ImageSemanticDispatch {
800			contract: crate::core::operation::image::PYR_DOWN,
801			inputs: &[ImageSemanticInput::Image(input)],
802			outputs: &[ImageSemanticOutput::Image(&output)],
803			attributes: &[],
804		},
805	)?;
806	Ok(output)
807}
808
809/// Double an FP32 image with the `pyrUp` interpolate-blur contract.
810///
811/// The source is upsampled by two with zero rows and columns at odd
812/// positions, then convolved with the 5x5 `[1, 4, 6, 4, 1]` kernel
813/// scaled by four, following OpenCV's `BORDER_DEFAULT` (reflect-101)
814/// edge rule on the upsampled grid. Output spatial extents are `2 *
815/// extent` per axis; layout and format are preserved.
816///
817/// # Errors
818///
819/// Returns an error unless the image is nonempty FP32 NCHW/CHW and all
820/// sizes fit the shader ABI.
821pub fn pyr_up(input: &Image) -> Result<Image> {
822	let extent = validate_image(input, "image::pyr_up")?;
823	let output_width = extent
824		.width
825		.checked_mul(2)
826		.ok_or_else(|| Error::out_of_range("image::pyr_up output width exceeds u32"))?;
827	let output_height = extent
828		.height
829		.checked_mul(2)
830		.ok_or_else(|| Error::out_of_range("image::pyr_up output height exceeds u32"))?;
831	let output = allocate_image(input, output_width, output_height, "image::pyr_up")?;
832	let planes = extent
833		.batch
834		.checked_mul(extent.channels)
835		.ok_or_else(|| Error::out_of_range("image::pyr_up batch-channel dispatch exceeds u32"))?;
836	let workgroups = [
837		output_width.div_ceil(16),
838		output_height.div_ceil(16),
839		planes,
840	];
841	input.runtime().record_image_semantic(
842		ComputeDispatch {
843			kernel: KernelId::ImagePyrUpF32,
844			buffers: &[
845				BufferBinding::read(input.storage()),
846				BufferBinding::write(output.storage()),
847			],
848			push_constants: &[
849				PushConstant::U32(extent.batch),
850				PushConstant::U32(extent.channels),
851				PushConstant::U32(extent.height),
852				PushConstant::U32(extent.width),
853				PushConstant::U32(output_height),
854				PushConstant::U32(output_width),
855			],
856			workgroups,
857			indirect: None,
858		},
859		ImageSemanticDispatch {
860			contract: crate::core::operation::image::PYR_UP,
861			inputs: &[ImageSemanticInput::Image(input)],
862			outputs: &[ImageSemanticOutput::Image(&output)],
863			attributes: &[],
864		},
865	)?;
866	Ok(output)
867}
868
869/// Radial mapping used by [`warp_polar`].
870#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
871pub enum PolarMode {
872	/// `WARP_POLAR_LINEAR` uniform radial axis.
873	#[default]
874	Linear,
875	/// `WARP_POLAR_LOG` exponential radial axis.
876	SemiLog,
877}
878
879impl PolarMode {
880	pub(super) const fn token(self) -> &'static str {
881		match self {
882			Self::Linear => "linear",
883			Self::SemiLog => "semi_log",
884		}
885	}
886
887	pub(super) const fn code(self) -> u32 {
888		match self {
889			Self::Linear => 0,
890			Self::SemiLog => 1,
891		}
892	}
893}
894
895/// Warp each image plane to polar coordinates about a center, following
896/// `warpPolar`: output row `y` is the angular axis `[0, 2pi)` and column
897/// `x` is the radial axis — `x / width * max_radius` under `Linear` or
898/// `max_radius^(x / width)` under `SemiLog`. Source samples gather with
899/// the admitted interpolation and border policy.
900///
901/// # Errors
902///
903/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
904/// image, the center and radius are finite with `max_radius > 0`, the
905/// output extent is nonzero, `border_value` is finite, and all sizes
906/// fit the shader ABI.
907#[allow(clippy::too_many_arguments)]
908pub fn warp_polar(
909	input: &Image,
910	center_x: f32,
911	center_y: f32,
912	max_radius: f32,
913	out_width: u32,
914	out_height: u32,
915	mode: PolarMode,
916	interpolation: InterpolationMode,
917	border: BorderMode,
918	border_value: f32,
919) -> Result<Image> {
920	if out_width == 0 || out_height == 0 {
921		return Err(Error::invalid_argument(
922			"image::warp_polar output width and height must be nonzero",
923		));
924	}
925	if !center_x.is_finite()
926		|| !center_y.is_finite()
927		|| !max_radius.is_finite()
928		|| max_radius <= 0.0
929		|| !border_value.is_finite()
930	{
931		return Err(Error::invalid_argument(
932			"image::warp_polar requires finite center, positive max_radius, and finite border_value",
933		));
934	}
935	let extent = validate_image(input, "image::warp_polar")?;
936	let output = allocate_image(input, out_width, out_height, "image::warp_polar")?;
937	let log_max_radius = max_radius.ln();
938	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
939	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
940	let planes = u32_extent(
941		output
942			.batch_size()
943			.checked_mul(output.channels())
944			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
945		"image operation batch-channel dispatch",
946	)?;
947	let mut workgroups =
948		KernelId::ImageWarpPolarF32.output_workgroups(dispatch_width, dispatch_height);
949	workgroups[2] = planes;
950	let attributes = [
951		float("center_x", center_x),
952		float("center_y", center_y),
953		float("max_radius", max_radius),
954		unsigned("out_width", out_width),
955		unsigned("out_height", out_height),
956		enumeration("mode", mode.token()),
957		enumeration("interpolation", interpolation.token()),
958		enumeration("border", border.token()),
959		float("border_value", border_value),
960	];
961	input.runtime().record_image_semantic(
962		ComputeDispatch {
963			kernel: KernelId::ImageWarpPolarF32,
964			buffers: &[
965				BufferBinding::read(input.storage()),
966				BufferBinding::write(output.storage()),
967			],
968			push_constants: &[
969				PushConstant::U32(extent.batch),
970				PushConstant::U32(extent.channels),
971				PushConstant::U32(extent.height),
972				PushConstant::U32(extent.width),
973				PushConstant::U32(out_height),
974				PushConstant::U32(out_width),
975				PushConstant::U32(mode.code()),
976				PushConstant::U32(interpolation.code()),
977				PushConstant::U32(border.code()),
978				PushConstant::F32(center_x),
979				PushConstant::F32(center_y),
980				PushConstant::F32(max_radius),
981				PushConstant::F32(log_max_radius),
982				PushConstant::F32(border_value),
983			],
984			workgroups,
985			indirect: None,
986		},
987		ImageSemanticDispatch {
988			contract: crate::core::operation::image::WARP_POLAR,
989			inputs: &[ImageSemanticInput::Image(input)],
990			outputs: &[ImageSemanticOutput::Image(&output)],
991			attributes: &attributes,
992		},
993	)?;
994	Ok(output)
995}
996
997fn validate_image(input: &Image, operation: &str) -> Result<ImageExtent> {
998	if input.dtype() != DType::F32 {
999		return Err(Error::invalid_argument(format!(
1000			"{operation} requires f32 storage; received {}",
1001			input.dtype().token()
1002		)));
1003	}
1004	if !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw) {
1005		return Err(Error::invalid_argument(format!(
1006			"{operation} supports Nchw and Chw layouts; received {:?}",
1007			input.layout()
1008		)));
1009	}
1010	if input.batch_size() == 0 || input.channels() == 0 || input.height() == 0 || input.width() == 0 {
1011		return Err(Error::invalid_argument(format!(
1012			"{operation} requires a nonempty image"
1013		)));
1014	}
1015	Ok(ImageExtent {
1016		batch: u32_extent(input.batch_size(), &format!("{operation} batch"))?,
1017		channels: u32_extent(input.channels(), &format!("{operation} channels"))?,
1018		height: u32_extent(input.height(), &format!("{operation} height"))?,
1019		width: u32_extent(input.width(), &format!("{operation} width"))?,
1020	})
1021}
1022
1023fn validate_warp_inputs(
1024	input: &Image,
1025	coordinates: &Matrix,
1026	operation: &str,
1027	border_value: f32,
1028) -> Result<ImageExtent> {
1029	let extent = validate_image(input, operation)?;
1030	if coordinates.dtype() != DType::F32 {
1031		return Err(Error::invalid_argument(format!(
1032			"{operation} coordinates must use f32 storage"
1033		)));
1034	}
1035	if !input.runtime().same_as(coordinates.runtime()) {
1036		return Err(Error::invalid_argument(format!(
1037			"{operation} inputs must belong to the same runtime"
1038		)));
1039	}
1040	if !border_value.is_finite() {
1041		return Err(Error::invalid_argument(format!(
1042			"{operation} border value must be finite"
1043		)));
1044	}
1045	u32_extent(
1046		coordinates.num_elements(),
1047		&format!("{operation} coordinate element count"),
1048	)?;
1049	Ok(extent)
1050}
1051
1052fn allocate_image(input: &Image, width: u32, height: u32, operation: &str) -> Result<Image> {
1053	let width = usize::try_from(width)
1054		.map_err(|_| Error::out_of_range(format!("{operation} width exceeds usize")))?;
1055	let height = usize::try_from(height)
1056		.map_err(|_| Error::out_of_range(format!("{operation} height exceeds usize")))?;
1057	let shape = match input.layout() {
1058		ImageLayout::Nchw => vec![input.batch_size(), input.channels(), height, width],
1059		ImageLayout::Chw => vec![input.channels(), height, width],
1060		_ => unreachable!("layout was validated before allocation"),
1061	};
1062	let elements = shape.iter().copied().try_fold(1_usize, |count, extent| {
1063		count
1064			.checked_mul(extent)
1065			.ok_or_else(|| Error::out_of_range(format!("{operation} output size exceeds usize")))
1066	})?;
1067	u32_extent(elements, &format!("{operation} output element count"))?;
1068	let matrix = Matrix::allocate(input.runtime(), shape, elements, DType::F32)?;
1069	Image::new(matrix, input.layout(), input.format())
1070}
1071
1072fn unsigned(name: &str, value: u32) -> OpAttribute {
1073	OpAttribute::UnsignedInteger {
1074		name: name.into(),
1075		value: u64::from(value),
1076	}
1077}
1078
1079fn boolean(name: &str, value: bool) -> OpAttribute {
1080	OpAttribute::Boolean {
1081		name: name.into(),
1082		value,
1083	}
1084}
1085
1086fn enumeration(name: &str, value: &str) -> OpAttribute {
1087	OpAttribute::Enum {
1088		name: name.into(),
1089		value: value.into(),
1090	}
1091}
1092
1093fn float(name: &str, value: f32) -> OpAttribute {
1094	OpAttribute::Float {
1095		name: name.into(),
1096		value: f64::from(value),
1097	}
1098}
1099
1100fn u32_extent(value: usize, label: &str) -> Result<u32> {
1101	u32::try_from(value).map_err(|_| Error::out_of_range(format!("{label} exceeds u32")))
1102}