Skip to main content

oa/image/
pixel.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=4c3af0f4b2504702bcaaa32134afcbd07ca92d06660d4847a5eeb5a0691dde61
4//! Stateless per-element image transformations.
5
6use crate::{
7	DType, Error, Image, ImageFormat, ImageLayout, Matrix, OpAttribute, Result,
8	runtime::{
9		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10		KernelId, PushConstant,
11	},
12};
13
14/// Replace values above `threshold` with `max_value` and all others with zero.
15pub fn threshold_binary(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
16	let contract = crate::core::operation::image::THRESHOLD_BINARY;
17	finite(&[threshold, max_value], "image::threshold_binary")?;
18	if input.dtype() != DType::F32 {
19		return Err(Error::invalid_argument(format!(
20			"{} requires f32 storage",
21			contract.name()
22		)));
23	}
24	let element_count = u32::try_from(input.as_matrix().num_elements())
25		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
26	if element_count == 0 {
27		return Err(Error::invalid_argument(format!(
28			"{} requires a nonempty image",
29			contract.name()
30		)));
31	}
32	let matrix = crate::Matrix::allocate(
33		input.engine_handle(),
34		input.as_matrix().shape().to_vec(),
35		input.as_matrix().num_elements(),
36		DType::F32,
37	)?;
38	let output = Image::new(matrix, input.layout(), input.format())?;
39	input.engine_handle().record_image_semantic(
40		ComputeDispatch {
41			kernel: KernelId::ImageThresholdBinaryF32,
42			buffers: &[
43				BufferBinding::read(input.storage()),
44				BufferBinding::write(output.storage()),
45			],
46			push_constants: &[
47				PushConstant::U32(element_count),
48				PushConstant::U32(0),
49				PushConstant::F32(threshold),
50				PushConstant::F32(max_value),
51				PushConstant::F32(0.0),
52				PushConstant::F32(0.0),
53			],
54			workgroups: KernelId::ImageThresholdBinaryF32.linear_workgroups(element_count),
55			indirect: None,
56		},
57		ImageSemanticDispatch {
58			contract,
59			inputs: &[ImageSemanticInput::Image(input)],
60			outputs: &[ImageSemanticOutput::Image(&output)],
61			attributes: &[float("threshold", threshold), float("max_value", max_value)],
62		},
63	)?;
64	Ok(output)
65}
66
67/// Replace values at or below `threshold` with `max_value` and all others with zero.
68pub fn threshold_binary_inv(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
69	let contract = crate::core::operation::image::THRESHOLD_BINARY_INV;
70	finite(&[threshold, max_value], "image::threshold_binary_inv")?;
71	if input.dtype() != DType::F32 {
72		return Err(Error::invalid_argument(format!(
73			"{} requires f32 storage",
74			contract.name()
75		)));
76	}
77	let element_count = u32::try_from(input.as_matrix().num_elements())
78		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
79	if element_count == 0 {
80		return Err(Error::invalid_argument(format!(
81			"{} requires a nonempty image",
82			contract.name()
83		)));
84	}
85	let matrix = crate::Matrix::allocate(
86		input.engine_handle(),
87		input.as_matrix().shape().to_vec(),
88		input.as_matrix().num_elements(),
89		DType::F32,
90	)?;
91	let output = Image::new(matrix, input.layout(), input.format())?;
92	input.engine_handle().record_image_semantic(
93		ComputeDispatch {
94			kernel: KernelId::ImageThresholdBinaryInvF32,
95			buffers: &[
96				BufferBinding::read(input.storage()),
97				BufferBinding::write(output.storage()),
98			],
99			push_constants: &[
100				PushConstant::U32(element_count),
101				PushConstant::U32(1),
102				PushConstant::F32(threshold),
103				PushConstant::F32(max_value),
104				PushConstant::F32(0.0),
105				PushConstant::F32(0.0),
106			],
107			workgroups: KernelId::ImageThresholdBinaryInvF32.linear_workgroups(element_count),
108			indirect: None,
109		},
110		ImageSemanticDispatch {
111			contract,
112			inputs: &[ImageSemanticInput::Image(input)],
113			outputs: &[ImageSemanticOutput::Image(&output)],
114			attributes: &[float("threshold", threshold), float("max_value", max_value)],
115		},
116	)?;
117	Ok(output)
118}
119
120/// Truncate values above `threshold`.
121pub fn threshold_truncate(input: &Image, threshold: f32) -> Result<Image> {
122	let contract = crate::core::operation::image::THRESHOLD_TRUNCATE;
123	finite(&[threshold], "image::threshold_truncate")?;
124	if input.dtype() != DType::F32 {
125		return Err(Error::invalid_argument(format!(
126			"{} requires f32 storage",
127			contract.name()
128		)));
129	}
130	let element_count = u32::try_from(input.as_matrix().num_elements())
131		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
132	if element_count == 0 {
133		return Err(Error::invalid_argument(format!(
134			"{} requires a nonempty image",
135			contract.name()
136		)));
137	}
138	let matrix = crate::Matrix::allocate(
139		input.engine_handle(),
140		input.as_matrix().shape().to_vec(),
141		input.as_matrix().num_elements(),
142		DType::F32,
143	)?;
144	let output = Image::new(matrix, input.layout(), input.format())?;
145	input.engine_handle().record_image_semantic(
146		ComputeDispatch {
147			kernel: KernelId::ImageThresholdTruncateF32,
148			buffers: &[
149				BufferBinding::read(input.storage()),
150				BufferBinding::write(output.storage()),
151			],
152			push_constants: &[
153				PushConstant::U32(element_count),
154				PushConstant::U32(2),
155				PushConstant::F32(threshold),
156				PushConstant::F32(0.0),
157				PushConstant::F32(0.0),
158				PushConstant::F32(0.0),
159			],
160			workgroups: KernelId::ImageThresholdTruncateF32.linear_workgroups(element_count),
161			indirect: None,
162		},
163		ImageSemanticDispatch {
164			contract,
165			inputs: &[ImageSemanticInput::Image(input)],
166			outputs: &[ImageSemanticOutput::Image(&output)],
167			attributes: &[float("threshold", threshold)],
168		},
169	)?;
170	Ok(output)
171}
172
173/// Replace values at or below `threshold` with zero.
174pub fn threshold_to_zero(input: &Image, threshold: f32) -> Result<Image> {
175	let contract = crate::core::operation::image::THRESHOLD_TO_ZERO;
176	finite(&[threshold], "image::threshold_to_zero")?;
177	if input.dtype() != DType::F32 {
178		return Err(Error::invalid_argument(format!(
179			"{} requires f32 storage",
180			contract.name()
181		)));
182	}
183	let element_count = u32::try_from(input.as_matrix().num_elements())
184		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
185	if element_count == 0 {
186		return Err(Error::invalid_argument(format!(
187			"{} requires a nonempty image",
188			contract.name()
189		)));
190	}
191	let matrix = crate::Matrix::allocate(
192		input.engine_handle(),
193		input.as_matrix().shape().to_vec(),
194		input.as_matrix().num_elements(),
195		DType::F32,
196	)?;
197	let output = Image::new(matrix, input.layout(), input.format())?;
198	input.engine_handle().record_image_semantic(
199		ComputeDispatch {
200			kernel: KernelId::ImageThresholdToZeroF32,
201			buffers: &[
202				BufferBinding::read(input.storage()),
203				BufferBinding::write(output.storage()),
204			],
205			push_constants: &[
206				PushConstant::U32(element_count),
207				PushConstant::U32(3),
208				PushConstant::F32(threshold),
209				PushConstant::F32(0.0),
210				PushConstant::F32(0.0),
211				PushConstant::F32(0.0),
212			],
213			workgroups: KernelId::ImageThresholdToZeroF32.linear_workgroups(element_count),
214			indirect: None,
215		},
216		ImageSemanticDispatch {
217			contract,
218			inputs: &[ImageSemanticInput::Image(input)],
219			outputs: &[ImageSemanticOutput::Image(&output)],
220			attributes: &[float("threshold", threshold)],
221		},
222	)?;
223	Ok(output)
224}
225
226/// Replace values above `threshold` with zero.
227pub fn threshold_to_zero_inv(input: &Image, threshold: f32) -> Result<Image> {
228	let contract = crate::core::operation::image::THRESHOLD_TO_ZERO_INV;
229	finite(&[threshold], "image::threshold_to_zero_inv")?;
230	if input.dtype() != DType::F32 {
231		return Err(Error::invalid_argument(format!(
232			"{} requires f32 storage",
233			contract.name()
234		)));
235	}
236	let element_count = u32::try_from(input.as_matrix().num_elements())
237		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
238	if element_count == 0 {
239		return Err(Error::invalid_argument(format!(
240			"{} requires a nonempty image",
241			contract.name()
242		)));
243	}
244	let matrix = crate::Matrix::allocate(
245		input.engine_handle(),
246		input.as_matrix().shape().to_vec(),
247		input.as_matrix().num_elements(),
248		DType::F32,
249	)?;
250	let output = Image::new(matrix, input.layout(), input.format())?;
251	input.engine_handle().record_image_semantic(
252		ComputeDispatch {
253			kernel: KernelId::ImageThresholdToZeroInvF32,
254			buffers: &[
255				BufferBinding::read(input.storage()),
256				BufferBinding::write(output.storage()),
257			],
258			push_constants: &[
259				PushConstant::U32(element_count),
260				PushConstant::U32(4),
261				PushConstant::F32(threshold),
262				PushConstant::F32(0.0),
263				PushConstant::F32(0.0),
264				PushConstant::F32(0.0),
265			],
266			workgroups: KernelId::ImageThresholdToZeroInvF32.linear_workgroups(element_count),
267			indirect: None,
268		},
269		ImageSemanticDispatch {
270			contract,
271			inputs: &[ImageSemanticInput::Image(input)],
272			outputs: &[ImageSemanticOutput::Image(&output)],
273			attributes: &[float("threshold", threshold)],
274		},
275	)?;
276	Ok(output)
277}
278
279/// Produce `true_value` for values inside the inclusive interval and zero outside it.
280pub fn in_range(input: &Image, low: f32, high: f32, true_value: f32) -> Result<Image> {
281	let contract = crate::core::operation::image::IN_RANGE;
282	finite(&[low, high, true_value], "image::in_range")?;
283	if low > high {
284		return Err(Error::invalid_argument(
285			"image::in_range low must not exceed high",
286		));
287	}
288	if input.dtype() != DType::F32 {
289		return Err(Error::invalid_argument(format!(
290			"{} requires f32 storage",
291			contract.name()
292		)));
293	}
294	let element_count = u32::try_from(input.as_matrix().num_elements())
295		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
296	if element_count == 0 {
297		return Err(Error::invalid_argument(format!(
298			"{} requires a nonempty image",
299			contract.name()
300		)));
301	}
302	let matrix = crate::Matrix::allocate(
303		input.engine_handle(),
304		input.as_matrix().shape().to_vec(),
305		input.as_matrix().num_elements(),
306		DType::F32,
307	)?;
308	let output = Image::new(matrix, input.layout(), input.format())?;
309	input.engine_handle().record_image_semantic(
310		ComputeDispatch {
311			kernel: KernelId::ImageInRangeF32,
312			buffers: &[
313				BufferBinding::read(input.storage()),
314				BufferBinding::write(output.storage()),
315			],
316			push_constants: &[
317				PushConstant::U32(element_count),
318				PushConstant::U32(5),
319				PushConstant::F32(low),
320				PushConstant::F32(high),
321				PushConstant::F32(true_value),
322				PushConstant::F32(0.0),
323			],
324			workgroups: KernelId::ImageInRangeF32.linear_workgroups(element_count),
325			indirect: None,
326		},
327		ImageSemanticDispatch {
328			contract,
329			inputs: &[ImageSemanticInput::Image(input)],
330			outputs: &[ImageSemanticOutput::Image(&output)],
331			attributes: &[
332				float("low", low),
333				float("high", high),
334				float("true_value", true_value),
335			],
336		},
337	)?;
338	Ok(output)
339}
340
341/// Clamp every pixel to the inclusive interval.
342pub fn clamp(input: &Image, low: f32, high: f32) -> Result<Image> {
343	let contract = crate::core::operation::image::CLAMP;
344	finite(&[low, high], "image::clamp")?;
345	if low > high {
346		return Err(Error::invalid_argument(
347			"image::clamp low must not exceed high",
348		));
349	}
350	if input.dtype() != DType::F32 {
351		return Err(Error::invalid_argument(format!(
352			"{} requires f32 storage",
353			contract.name()
354		)));
355	}
356	let element_count = u32::try_from(input.as_matrix().num_elements())
357		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
358	if element_count == 0 {
359		return Err(Error::invalid_argument(format!(
360			"{} requires a nonempty image",
361			contract.name()
362		)));
363	}
364	let matrix = crate::Matrix::allocate(
365		input.engine_handle(),
366		input.as_matrix().shape().to_vec(),
367		input.as_matrix().num_elements(),
368		DType::F32,
369	)?;
370	let output = Image::new(matrix, input.layout(), input.format())?;
371	input.engine_handle().record_image_semantic(
372		ComputeDispatch {
373			kernel: KernelId::ImageClampF32,
374			buffers: &[
375				BufferBinding::read(input.storage()),
376				BufferBinding::write(output.storage()),
377			],
378			push_constants: &[
379				PushConstant::U32(element_count),
380				PushConstant::U32(6),
381				PushConstant::F32(low),
382				PushConstant::F32(high),
383				PushConstant::F32(0.0),
384				PushConstant::F32(0.0),
385			],
386			workgroups: KernelId::ImageClampF32.linear_workgroups(element_count),
387			indirect: None,
388		},
389		ImageSemanticDispatch {
390			contract,
391			inputs: &[ImageSemanticInput::Image(input)],
392			outputs: &[ImageSemanticOutput::Image(&output)],
393			attributes: &[float("low", low), float("high", high)],
394		},
395	)?;
396	Ok(output)
397}
398
399/// Invert every value around `max_value`.
400pub fn invert(input: &Image, max_value: f32) -> Result<Image> {
401	let contract = crate::core::operation::image::INVERT;
402	finite(&[max_value], "image::invert")?;
403	if input.dtype() != DType::F32 {
404		return Err(Error::invalid_argument(format!(
405			"{} requires f32 storage",
406			contract.name()
407		)));
408	}
409	let element_count = u32::try_from(input.as_matrix().num_elements())
410		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
411	if element_count == 0 {
412		return Err(Error::invalid_argument(format!(
413			"{} requires a nonempty image",
414			contract.name()
415		)));
416	}
417	let matrix = crate::Matrix::allocate(
418		input.engine_handle(),
419		input.as_matrix().shape().to_vec(),
420		input.as_matrix().num_elements(),
421		DType::F32,
422	)?;
423	let output = Image::new(matrix, input.layout(), input.format())?;
424	input.engine_handle().record_image_semantic(
425		ComputeDispatch {
426			kernel: KernelId::ImageInvertF32,
427			buffers: &[
428				BufferBinding::read(input.storage()),
429				BufferBinding::write(output.storage()),
430			],
431			push_constants: &[
432				PushConstant::U32(element_count),
433				PushConstant::U32(7),
434				PushConstant::F32(max_value),
435				PushConstant::F32(0.0),
436				PushConstant::F32(0.0),
437				PushConstant::F32(0.0),
438			],
439			workgroups: KernelId::ImageInvertF32.linear_workgroups(element_count),
440			indirect: None,
441		},
442		ImageSemanticDispatch {
443			contract,
444			inputs: &[ImageSemanticInput::Image(input)],
445			outputs: &[ImageSemanticOutput::Image(&output)],
446			attributes: &[float("max_value", max_value)],
447		},
448	)?;
449	Ok(output)
450}
451
452/// Apply `value * contrast + brightness`.
453pub fn brightness_contrast(input: &Image, brightness: f32, contrast: f32) -> Result<Image> {
454	let contract = crate::core::operation::image::BRIGHTNESS_CONTRAST;
455	finite(&[brightness, contrast], "image::brightness_contrast")?;
456	if input.dtype() != DType::F32 {
457		return Err(Error::invalid_argument(format!(
458			"{} requires f32 storage",
459			contract.name()
460		)));
461	}
462	let element_count = u32::try_from(input.as_matrix().num_elements())
463		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
464	if element_count == 0 {
465		return Err(Error::invalid_argument(format!(
466			"{} requires a nonempty image",
467			contract.name()
468		)));
469	}
470	let matrix = crate::Matrix::allocate(
471		input.engine_handle(),
472		input.as_matrix().shape().to_vec(),
473		input.as_matrix().num_elements(),
474		DType::F32,
475	)?;
476	let output = Image::new(matrix, input.layout(), input.format())?;
477	input.engine_handle().record_image_semantic(
478		ComputeDispatch {
479			kernel: KernelId::ImageBrightnessContrastF32,
480			buffers: &[
481				BufferBinding::read(input.storage()),
482				BufferBinding::write(output.storage()),
483			],
484			push_constants: &[
485				PushConstant::U32(element_count),
486				PushConstant::U32(8),
487				PushConstant::F32(contrast),
488				PushConstant::F32(brightness),
489				PushConstant::F32(0.0),
490				PushConstant::F32(0.0),
491			],
492			workgroups: KernelId::ImageBrightnessContrastF32.linear_workgroups(element_count),
493			indirect: None,
494		},
495		ImageSemanticDispatch {
496			contract,
497			inputs: &[ImageSemanticInput::Image(input)],
498			outputs: &[ImageSemanticOutput::Image(&output)],
499			attributes: &[float("brightness", brightness), float("contrast", contrast)],
500		},
501	)?;
502	Ok(output)
503}
504
505/// Apply `max(value, 0)^gamma * gain`.
506pub fn gamma_contrast(input: &Image, gamma: f32, gain: f32) -> Result<Image> {
507	let contract = crate::core::operation::image::GAMMA_CONTRAST;
508	finite(&[gamma, gain], "image::gamma_contrast")?;
509	if gamma <= 0.0 {
510		return Err(Error::invalid_argument(
511			"image::gamma_contrast gamma must be positive",
512		));
513	}
514	if input.dtype() != DType::F32 {
515		return Err(Error::invalid_argument(format!(
516			"{} requires f32 storage",
517			contract.name()
518		)));
519	}
520	let element_count = u32::try_from(input.as_matrix().num_elements())
521		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
522	if element_count == 0 {
523		return Err(Error::invalid_argument(format!(
524			"{} requires a nonempty image",
525			contract.name()
526		)));
527	}
528	let matrix = crate::Matrix::allocate(
529		input.engine_handle(),
530		input.as_matrix().shape().to_vec(),
531		input.as_matrix().num_elements(),
532		DType::F32,
533	)?;
534	let output = Image::new(matrix, input.layout(), input.format())?;
535	input.engine_handle().record_image_semantic(
536		ComputeDispatch {
537			kernel: KernelId::ImageGammaContrastF32,
538			buffers: &[
539				BufferBinding::read(input.storage()),
540				BufferBinding::write(output.storage()),
541			],
542			push_constants: &[
543				PushConstant::U32(element_count),
544				PushConstant::U32(9),
545				PushConstant::F32(gamma),
546				PushConstant::F32(gain),
547				PushConstant::F32(0.0),
548				PushConstant::F32(0.0),
549			],
550			workgroups: KernelId::ImageGammaContrastF32.linear_workgroups(element_count),
551			indirect: None,
552		},
553		ImageSemanticDispatch {
554			contract,
555			inputs: &[ImageSemanticInput::Image(input)],
556			outputs: &[ImageSemanticOutput::Image(&output)],
557			attributes: &[float("gamma", gamma), float("gain", gain)],
558		},
559	)?;
560	Ok(output)
561}
562
563/// Invert values at or above `threshold` around `max_value`.
564pub fn solarize(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
565	let contract = crate::core::operation::image::SOLARIZE;
566	finite(&[threshold, max_value], "image::solarize")?;
567	if input.dtype() != DType::F32 {
568		return Err(Error::invalid_argument(format!(
569			"{} requires f32 storage",
570			contract.name()
571		)));
572	}
573	let element_count = u32::try_from(input.as_matrix().num_elements())
574		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
575	if element_count == 0 {
576		return Err(Error::invalid_argument(format!(
577			"{} requires a nonempty image",
578			contract.name()
579		)));
580	}
581	let matrix = crate::Matrix::allocate(
582		input.engine_handle(),
583		input.as_matrix().shape().to_vec(),
584		input.as_matrix().num_elements(),
585		DType::F32,
586	)?;
587	let output = Image::new(matrix, input.layout(), input.format())?;
588	input.engine_handle().record_image_semantic(
589		ComputeDispatch {
590			kernel: KernelId::ImageSolarizeF32,
591			buffers: &[
592				BufferBinding::read(input.storage()),
593				BufferBinding::write(output.storage()),
594			],
595			push_constants: &[
596				PushConstant::U32(element_count),
597				PushConstant::U32(10),
598				PushConstant::F32(threshold),
599				PushConstant::F32(max_value),
600				PushConstant::F32(0.0),
601				PushConstant::F32(0.0),
602			],
603			workgroups: KernelId::ImageSolarizeF32.linear_workgroups(element_count),
604			indirect: None,
605		},
606		ImageSemanticDispatch {
607			contract,
608			inputs: &[ImageSemanticInput::Image(input)],
609			outputs: &[ImageSemanticOutput::Image(&output)],
610			attributes: &[float("threshold", threshold), float("max_value", max_value)],
611		},
612	)?;
613	Ok(output)
614}
615
616/// Quantize `[low, high]` to `levels` evenly spaced values using round-half-up.
617pub fn posterize(input: &Image, levels: u32, low: f32, high: f32) -> Result<Image> {
618	let contract = crate::core::operation::image::POSTERIZE;
619	finite(&[low, high], "image::posterize")?;
620	if !(2..=65_536).contains(&levels) || low >= high {
621		return Err(Error::invalid_argument(
622			"image::posterize requires 2..=65536 levels and low < high",
623		));
624	}
625	if input.dtype() != DType::F32 {
626		return Err(Error::invalid_argument(format!(
627			"{} requires f32 storage",
628			contract.name()
629		)));
630	}
631	let element_count = u32::try_from(input.as_matrix().num_elements())
632		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
633	if element_count == 0 {
634		return Err(Error::invalid_argument(format!(
635			"{} requires a nonempty image",
636			contract.name()
637		)));
638	}
639	let matrix = crate::Matrix::allocate(
640		input.engine_handle(),
641		input.as_matrix().shape().to_vec(),
642		input.as_matrix().num_elements(),
643		DType::F32,
644	)?;
645	let output = Image::new(matrix, input.layout(), input.format())?;
646	input.engine_handle().record_image_semantic(
647		ComputeDispatch {
648			kernel: KernelId::ImagePosterizeF32,
649			buffers: &[
650				BufferBinding::read(input.storage()),
651				BufferBinding::write(output.storage()),
652			],
653			push_constants: &[
654				PushConstant::U32(element_count),
655				PushConstant::U32(11),
656				PushConstant::F32(levels as f32),
657				PushConstant::F32(low),
658				PushConstant::F32(high),
659				PushConstant::F32(0.0),
660			],
661			workgroups: KernelId::ImagePosterizeF32.linear_workgroups(element_count),
662			indirect: None,
663		},
664		ImageSemanticDispatch {
665			contract,
666			inputs: &[ImageSemanticInput::Image(input)],
667			outputs: &[ImageSemanticOutput::Image(&output)],
668			attributes: &[
669				unsigned("levels", levels),
670				float("low", low),
671				float("high", high),
672			],
673		},
674	)?;
675	Ok(output)
676}
677
678/// Convert an RGB or RGBA image to Rec.709 grayscale.
679pub fn grayscale(input: &Image) -> Result<Image> {
680	let (batch, channels, height, width) = image_extent(input, "image::grayscale")?;
681	if !matches!(input.format(), ImageFormat::Rgb | ImageFormat::Rgba) {
682		return Err(Error::invalid_argument(
683			"image::grayscale requires RGB or RGBA channel semantics",
684		));
685	}
686	let shape = match input.layout() {
687		ImageLayout::Nchw => vec![batch as usize, 1, height as usize, width as usize],
688		ImageLayout::Chw => vec![1, height as usize, width as usize],
689		_ => unreachable!("image extent admitted an unsupported layout"),
690	};
691	let output = allocate(input, shape, ImageFormat::Gray, "image::grayscale")?;
692	input.engine_handle().record_image_semantic(
693		ComputeDispatch {
694			kernel: KernelId::ImageGrayscaleF32,
695			buffers: &[
696				BufferBinding::read(input.storage()),
697				BufferBinding::write(output.storage()),
698			],
699			push_constants: &[
700				PushConstant::U32(batch),
701				PushConstant::U32(channels),
702				PushConstant::U32(height),
703				PushConstant::U32(width),
704			],
705			workgroups: [width.div_ceil(16), height.div_ceil(16), batch],
706			indirect: None,
707		},
708		ImageSemanticDispatch {
709			contract: crate::core::operation::image::GRAYSCALE,
710			inputs: &[ImageSemanticInput::Image(input)],
711			outputs: &[ImageSemanticOutput::Image(&output)],
712			attributes: &[],
713		},
714	)?;
715	Ok(output)
716}
717
718/// Blend two equal semantic images using `left * (1-alpha) + right * alpha`.
719pub fn alpha_blend(left: &Image, right: &Image, alpha: f32) -> Result<Image> {
720	finite(&[alpha], "image::alpha_blend")?;
721	if !(0.0..=1.0).contains(&alpha) {
722		return Err(Error::invalid_argument(
723			"image::alpha_blend alpha must be in [0, 1]",
724		));
725	}
726	validate_matching_images(left, right, "image::alpha_blend")?;
727	let contract = crate::core::operation::image::ALPHA_BLEND;
728	let (batch, channels, height, width) = image_extent(left, contract.name())?;
729	let mask_channels = u32::try_from(left.channels())
730		.map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
731	let output = allocate(
732		left,
733		left.as_matrix().shape().to_vec(),
734		left.format(),
735		contract.name(),
736	)?;
737	let buffers = [
738		BufferBinding::read(left.storage()),
739		BufferBinding::read(right.storage()),
740		BufferBinding::read(left.storage()),
741		BufferBinding::write(output.storage()),
742	];
743	let push_constants = [
744		PushConstant::U32(batch),
745		PushConstant::U32(channels),
746		PushConstant::U32(height),
747		PushConstant::U32(width),
748		PushConstant::U32(0),
749		PushConstant::U32(mask_channels),
750		PushConstant::U32(0),
751		PushConstant::U32(0),
752		PushConstant::U32(0),
753		PushConstant::U32(0),
754		PushConstant::F32(alpha),
755		PushConstant::F32(0.0),
756	];
757	left.engine_handle().record_image_semantic(
758		ComputeDispatch {
759			kernel: KernelId::ImageAlphaBlendF32,
760			buffers: &buffers,
761			push_constants: &push_constants,
762			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
763			indirect: None,
764		},
765		ImageSemanticDispatch {
766			contract,
767			inputs: &[
768				ImageSemanticInput::Image(left),
769				ImageSemanticInput::Image(right),
770			],
771			outputs: &[ImageSemanticOutput::Image(&output)],
772			attributes: &[float("alpha", alpha)],
773		},
774	)?;
775	Ok(output)
776}
777
778/// Composite two equal images with a clamped Gray or per-channel mask.
779pub fn composite(left: &Image, right: &Image, mask: &Image) -> Result<Image> {
780	let (batch, channels, height, width) = image_extent(left, "image::composite")?;
781	validate_matching_images(left, right, "image::composite")?;
782	let (mask_batch, mask_channels, mask_height, mask_width) =
783		image_extent(mask, "image::composite")?;
784	if !left.engine_handle().same_as(mask.engine_handle())
785		|| mask_batch != batch
786		|| mask_height != height
787		|| mask_width != width
788		|| !matches!(mask_channels, 1) && mask_channels != channels
789	{
790		return Err(Error::invalid_argument(
791			"image::composite mask must share batch/spatial extents and have one or matching channels",
792		));
793	}
794	let contract = crate::core::operation::image::COMPOSITE;
795	let (batch, channels, height, width) = image_extent(left, contract.name())?;
796	let mask_channels = u32::try_from(mask.channels())
797		.map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
798	let output = allocate(
799		left,
800		left.as_matrix().shape().to_vec(),
801		left.format(),
802		contract.name(),
803	)?;
804	let buffers = [
805		BufferBinding::read(left.storage()),
806		BufferBinding::read(right.storage()),
807		BufferBinding::read(mask.storage()),
808		BufferBinding::write(output.storage()),
809	];
810	let push_constants = [
811		PushConstant::U32(batch),
812		PushConstant::U32(channels),
813		PushConstant::U32(height),
814		PushConstant::U32(width),
815		PushConstant::U32(1),
816		PushConstant::U32(mask_channels),
817		PushConstant::U32(0),
818		PushConstant::U32(0),
819		PushConstant::U32(0),
820		PushConstant::U32(0),
821		PushConstant::F32(0.0),
822		PushConstant::F32(0.0),
823	];
824	left.engine_handle().record_image_semantic(
825		ComputeDispatch {
826			kernel: KernelId::ImageCompositeF32,
827			buffers: &buffers,
828			push_constants: &push_constants,
829			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
830			indirect: None,
831		},
832		ImageSemanticDispatch {
833			contract,
834			inputs: &[
835				ImageSemanticInput::Image(left),
836				ImageSemanticInput::Image(right),
837				ImageSemanticInput::Image(mask),
838			],
839			outputs: &[ImageSemanticOutput::Image(&output)],
840			attributes: &[],
841		},
842	)?;
843	Ok(output)
844}
845
846/// Fill the intersection of a rectangle and the image with one finite value.
847pub fn erase(input: &Image, x: u32, y: u32, width: u32, height: u32, value: f32) -> Result<Image> {
848	finite(&[value], "image::erase")?;
849	let (_, _, image_height, image_width) = image_extent(input, "image::erase")?;
850	if width == 0 || height == 0 || x >= image_width || y >= image_height {
851		return Err(Error::invalid_argument(
852			"image::erase requires a nonzero rectangle with an in-bounds origin",
853		));
854	}
855	let contract = crate::core::operation::image::ERASE;
856	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
857	let mask_channels = u32::try_from(input.channels())
858		.map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
859	let output = allocate(
860		input,
861		input.as_matrix().shape().to_vec(),
862		input.format(),
863		contract.name(),
864	)?;
865	let buffers = [
866		BufferBinding::read(input.storage()),
867		BufferBinding::read(input.storage()),
868		BufferBinding::read(input.storage()),
869		BufferBinding::write(output.storage()),
870	];
871	let push_constants = [
872		PushConstant::U32(batch),
873		PushConstant::U32(channels),
874		PushConstant::U32(image_height),
875		PushConstant::U32(image_width),
876		PushConstant::U32(2),
877		PushConstant::U32(mask_channels),
878		PushConstant::U32(x),
879		PushConstant::U32(y),
880		PushConstant::U32(width),
881		PushConstant::U32(height),
882		PushConstant::F32(0.0),
883		PushConstant::F32(value),
884	];
885	input.engine_handle().record_image_semantic(
886		ComputeDispatch {
887			kernel: KernelId::ImageEraseF32,
888			buffers: &buffers,
889			push_constants: &push_constants,
890			workgroups: [
891				image_width.div_ceil(16),
892				image_height.div_ceil(16),
893				batch * channels,
894			],
895			indirect: None,
896		},
897		ImageSemanticDispatch {
898			contract,
899			inputs: &[ImageSemanticInput::Image(input)],
900			outputs: &[ImageSemanticOutput::Image(&output)],
901			attributes: &[
902				unsigned("x", x),
903				unsigned("y", y),
904				unsigned("width", width),
905				unsigned("height", height),
906				float("value", value),
907			],
908		},
909	)?;
910	Ok(output)
911}
912
913/// Apply one shared FP32 `[3, 4]` affine color transform to RGB channels.
914pub fn color_twist(input: &Image, transform: &Matrix) -> Result<Image> {
915	let (batch, channels, height, width) = image_extent(input, "image::color_twist")?;
916	if !matches!(input.format(), ImageFormat::Rgb | ImageFormat::Rgba)
917		|| transform.dtype() != DType::F32
918		|| transform.shape() != [3, 4]
919		|| !input.engine_handle().same_as(transform.engine_handle())
920	{
921		return Err(Error::invalid_argument(
922			"image::color_twist requires RGB/RGBA input and a same-engine FP32 [3, 4] transform",
923		));
924	}
925	let output = allocate(
926		input,
927		input.as_matrix().shape().to_vec(),
928		input.format(),
929		"image::color_twist",
930	)?;
931	let workgroups = [width.div_ceil(16), height.div_ceil(16), batch * channels];
932	input.engine_handle().record_image_semantic(
933		ComputeDispatch {
934			kernel: KernelId::ImageColorTwistF32,
935			buffers: &[
936				BufferBinding::read(input.storage()),
937				BufferBinding::read(transform.storage()),
938				BufferBinding::write(output.storage()),
939			],
940			push_constants: &[
941				PushConstant::U32(batch),
942				PushConstant::U32(channels),
943				PushConstant::U32(height),
944				PushConstant::U32(width),
945			],
946			workgroups,
947			indirect: None,
948		},
949		ImageSemanticDispatch {
950			contract: crate::core::operation::image::COLOR_TWIST,
951			inputs: &[
952				ImageSemanticInput::Image(input),
953				ImageSemanticInput::Matrix(transform),
954			],
955			outputs: &[ImageSemanticOutput::Image(&output)],
956			attributes: &[],
957		},
958	)?;
959	Ok(output)
960}
961
962/// Reorder one to four channels and explicitly assign the resulting format.
963///
964/// `order[c]` selects the source channel for output channel `c`. The output
965/// format must have the same channel count as the input so pixel data and
966/// semantic metadata cannot diverge.
967pub fn channel_reorder(
968	input: &Image,
969	order: [u32; 4],
970	output_format: ImageFormat,
971) -> Result<Image> {
972	let (batch, channels, height, width) = image_extent(input, "image::channel_reorder")?;
973	if output_format.channels() != input.channels()
974		|| order[..channels as usize]
975			.iter()
976			.any(|channel| *channel >= channels)
977	{
978		return Err(Error::invalid_argument(
979			"image::channel_reorder requires in-range source channels and an equal-width output format",
980		));
981	}
982	let output = allocate(
983		input,
984		input.as_matrix().shape().to_vec(),
985		output_format,
986		"image::channel_reorder",
987	)?;
988	input.engine_handle().record_image_semantic(
989		ComputeDispatch {
990			kernel: KernelId::ImageChannelReorderF32,
991			buffers: &[
992				BufferBinding::read(input.storage()),
993				BufferBinding::write(output.storage()),
994			],
995			push_constants: &[
996				PushConstant::U32(batch),
997				PushConstant::U32(channels),
998				PushConstant::U32(height),
999				PushConstant::U32(width),
1000				PushConstant::U32(order[0]),
1001				PushConstant::U32(order[1]),
1002				PushConstant::U32(order[2]),
1003				PushConstant::U32(order[3]),
1004			],
1005			workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
1006			indirect: None,
1007		},
1008		ImageSemanticDispatch {
1009			contract: crate::core::operation::image::CHANNEL_REORDER,
1010			inputs: &[ImageSemanticInput::Image(input)],
1011			outputs: &[ImageSemanticOutput::Image(&output)],
1012			attributes: &[
1013				unsigned("channel_0", order[0]),
1014				unsigned("channel_1", order[1]),
1015				unsigned("channel_2", order[2]),
1016				unsigned("channel_3", order[3]),
1017				enumeration("output_format", image_format_token(output_format)),
1018			],
1019		},
1020	)?;
1021	Ok(output)
1022}
1023
1024/// Add explicit-seed Philox Gaussian noise to every pixel.
1025pub fn gaussian_noise(input: &Image, mean: f32, stddev: f32, seed: u64) -> Result<Image> {
1026	finite(&[mean, stddev], "image::gaussian_noise")?;
1027	if stddev < 0.0 {
1028		return Err(Error::invalid_argument(
1029			"image::gaussian_noise standard deviation must be nonnegative",
1030		));
1031	}
1032	let contract = crate::core::operation::image::GAUSSIAN_NOISE;
1033	image_extent(input, contract.name())?;
1034	let element_count = u32::try_from(input.as_matrix().num_elements())
1035		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
1036	let output = allocate(
1037		input,
1038		input.as_matrix().shape().to_vec(),
1039		input.format(),
1040		contract.name(),
1041	)?;
1042	let push_constants = [
1043		PushConstant::U32(element_count),
1044		PushConstant::U32(seed as u32),
1045		PushConstant::U32((seed >> 32) as u32),
1046		PushConstant::F32(mean),
1047		PushConstant::F32(stddev),
1048	];
1049	input.engine_handle().record_image_semantic(
1050		ComputeDispatch {
1051			kernel: KernelId::ImageGaussianNoiseF32,
1052			buffers: &[
1053				BufferBinding::read(input.storage()),
1054				BufferBinding::write(output.storage()),
1055			],
1056			push_constants: &push_constants,
1057			workgroups: KernelId::ImageGaussianNoiseF32.linear_workgroups(element_count),
1058			indirect: None,
1059		},
1060		ImageSemanticDispatch {
1061			contract,
1062			inputs: &[ImageSemanticInput::Image(input)],
1063			outputs: &[ImageSemanticOutput::Image(&output)],
1064			attributes: &[
1065				float("mean", mean),
1066				float("stddev", stddev),
1067				unsigned64("seed", seed),
1068			],
1069		},
1070	)?;
1071	Ok(output)
1072}
1073
1074/// Replace a seeded fraction of pixels with salt or pepper values.
1075pub fn salt_pepper_noise(
1076	input: &Image,
1077	probability: f32,
1078	salt_value: f32,
1079	pepper_value: f32,
1080	seed: u64,
1081) -> Result<Image> {
1082	finite(
1083		&[probability, salt_value, pepper_value],
1084		"image::salt_pepper_noise",
1085	)?;
1086	if !(0.0..=1.0).contains(&probability) {
1087		return Err(Error::invalid_argument(
1088			"image::salt_pepper_noise probability must be in [0, 1]",
1089		));
1090	}
1091	let contract = crate::core::operation::image::SALT_PEPPER_NOISE;
1092	image_extent(input, contract.name())?;
1093	let element_count = u32::try_from(input.as_matrix().num_elements())
1094		.map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
1095	let output = allocate(
1096		input,
1097		input.as_matrix().shape().to_vec(),
1098		input.format(),
1099		contract.name(),
1100	)?;
1101	let push_constants = [
1102		PushConstant::U32(element_count),
1103		PushConstant::U32(seed as u32),
1104		PushConstant::U32((seed >> 32) as u32),
1105		PushConstant::F32(probability),
1106		PushConstant::F32(salt_value),
1107		PushConstant::F32(pepper_value),
1108	];
1109	input.engine_handle().record_image_semantic(
1110		ComputeDispatch {
1111			kernel: KernelId::ImageSaltPepperNoiseF32,
1112			buffers: &[
1113				BufferBinding::read(input.storage()),
1114				BufferBinding::write(output.storage()),
1115			],
1116			push_constants: &push_constants,
1117			workgroups: KernelId::ImageSaltPepperNoiseF32.linear_workgroups(element_count),
1118			indirect: None,
1119		},
1120		ImageSemanticDispatch {
1121			contract,
1122			inputs: &[ImageSemanticInput::Image(input)],
1123			outputs: &[ImageSemanticOutput::Image(&output)],
1124			attributes: &[
1125				float("probability", probability),
1126				float("salt_value", salt_value),
1127				float("pepper_value", pepper_value),
1128				unsigned64("seed", seed),
1129			],
1130		},
1131	)?;
1132	Ok(output)
1133}
1134
1135fn validate_matching_images(a: &Image, b: &Image, operation: &str) -> Result<()> {
1136	image_extent(a, operation)?;
1137	if a.as_matrix().shape() != b.as_matrix().shape()
1138		|| a.dtype() != b.dtype()
1139		|| a.layout() != b.layout()
1140		|| a.format() != b.format()
1141		|| !a.engine_handle().same_as(b.engine_handle())
1142	{
1143		return Err(Error::invalid_argument(format!(
1144			"{operation} images must have identical shape, dtype, layout, format, and engine"
1145		)));
1146	}
1147	Ok(())
1148}
1149
1150fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
1151	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
1152	{
1153		return Err(Error::invalid_argument(format!(
1154			"{operation} requires an FP32 NCHW or CHW image"
1155		)));
1156	}
1157	let extent = (
1158		u32::try_from(input.batch_size()),
1159		u32::try_from(input.channels()),
1160		u32::try_from(input.height()),
1161		u32::try_from(input.width()),
1162	);
1163	let (batch, channels, height, width) = match extent {
1164		(Ok(batch), Ok(channels), Ok(height), Ok(width)) => (batch, channels, height, width),
1165		_ => {
1166			return Err(Error::out_of_range(format!(
1167				"{operation} extent exceeds u32"
1168			)));
1169		}
1170	};
1171	if batch == 0 || channels == 0 || height == 0 || width == 0 {
1172		return Err(Error::invalid_argument(format!(
1173			"{operation} requires a nonempty image"
1174		)));
1175	}
1176	Ok((batch, channels, height, width))
1177}
1178
1179fn allocate(
1180	input: &Image,
1181	shape: Vec<usize>,
1182	format: ImageFormat,
1183	operation: &str,
1184) -> Result<Image> {
1185	let elements = shape.iter().copied().try_fold(1_usize, |count, extent| {
1186		count
1187			.checked_mul(extent)
1188			.ok_or_else(|| Error::out_of_range(format!("{operation} output size exceeds usize")))
1189	})?;
1190	u32::try_from(elements)
1191		.map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
1192	let matrix = Matrix::allocate(input.engine_handle(), shape, elements, DType::F32)?;
1193	Image::new(matrix, input.layout(), format)
1194}
1195
1196#[allow(clippy::too_many_arguments)]
1197fn finite(values: &[f32], operation: &str) -> Result<()> {
1198	if values.iter().all(|value| value.is_finite()) {
1199		Ok(())
1200	} else {
1201		Err(Error::invalid_argument(format!(
1202			"{operation} parameters must be finite"
1203		)))
1204	}
1205}
1206
1207fn float(name: &str, value: f32) -> OpAttribute {
1208	OpAttribute::Float {
1209		name: name.into(),
1210		value: f64::from(value),
1211	}
1212}
1213
1214fn unsigned(name: &str, value: u32) -> OpAttribute {
1215	OpAttribute::UnsignedInteger {
1216		name: name.into(),
1217		value: u64::from(value),
1218	}
1219}
1220
1221fn unsigned64(name: &str, value: u64) -> OpAttribute {
1222	OpAttribute::UnsignedInteger {
1223		name: name.into(),
1224		value,
1225	}
1226}
1227
1228fn enumeration(name: &str, value: &str) -> OpAttribute {
1229	OpAttribute::Enum {
1230		name: name.into(),
1231		value: value.into(),
1232	}
1233}
1234
1235const fn image_format_token(format: ImageFormat) -> &'static str {
1236	match format {
1237		ImageFormat::Gray => "gray",
1238		ImageFormat::GrayAlpha => "gray_alpha",
1239		ImageFormat::Rgb => "rgb",
1240		ImageFormat::Rgba => "rgba",
1241		ImageFormat::Bgr => "bgr",
1242		ImageFormat::Bgra => "bgra",
1243	}
1244}