1use crate::{
7 DType, Error, Image, ImageFormat, ImageLayout, Matrix, OpAttribute, Result,
8 image::Connectivity,
9 runtime::{
10 BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
11 KernelId, PushConstant,
12 },
13};
14
15pub fn threshold_binary(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
17 let contract = crate::core::operation::image::THRESHOLD_BINARY;
18 finite(&[threshold, max_value], "image::threshold_binary")?;
19 if input.dtype() != DType::F32 {
20 return Err(Error::invalid_argument(format!(
21 "{} requires f32 storage",
22 contract.name()
23 )));
24 }
25 let element_count = u32::try_from(input.as_matrix().num_elements())
26 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
27 if element_count == 0 {
28 return Err(Error::invalid_argument(format!(
29 "{} requires a nonempty image",
30 contract.name()
31 )));
32 }
33 let matrix = crate::Matrix::allocate(
34 input.runtime(),
35 input.as_matrix().shape().to_vec(),
36 input.as_matrix().num_elements(),
37 DType::F32,
38 )?;
39 let output = Image::new(matrix, input.layout(), input.format())?;
40 input.runtime().record_image_semantic(
41 ComputeDispatch {
42 kernel: KernelId::ImageThresholdBinaryF32,
43 buffers: &[
44 BufferBinding::read(input.storage()),
45 BufferBinding::write(output.storage()),
46 ],
47 push_constants: &[
48 PushConstant::U32(element_count),
49 PushConstant::U32(0),
50 PushConstant::F32(threshold),
51 PushConstant::F32(max_value),
52 PushConstant::F32(0.0),
53 PushConstant::F32(0.0),
54 ],
55 workgroups: KernelId::ImageThresholdBinaryF32.linear_workgroups(element_count),
56 indirect: None,
57 },
58 ImageSemanticDispatch {
59 contract,
60 inputs: &[ImageSemanticInput::Image(input)],
61 outputs: &[ImageSemanticOutput::Image(&output)],
62 attributes: &[float("threshold", threshold), float("max_value", max_value)],
63 },
64 )?;
65 Ok(output)
66}
67
68pub fn threshold_binary_inv(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
70 let contract = crate::core::operation::image::THRESHOLD_BINARY_INV;
71 finite(&[threshold, max_value], "image::threshold_binary_inv")?;
72 if input.dtype() != DType::F32 {
73 return Err(Error::invalid_argument(format!(
74 "{} requires f32 storage",
75 contract.name()
76 )));
77 }
78 let element_count = u32::try_from(input.as_matrix().num_elements())
79 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
80 if element_count == 0 {
81 return Err(Error::invalid_argument(format!(
82 "{} requires a nonempty image",
83 contract.name()
84 )));
85 }
86 let matrix = crate::Matrix::allocate(
87 input.runtime(),
88 input.as_matrix().shape().to_vec(),
89 input.as_matrix().num_elements(),
90 DType::F32,
91 )?;
92 let output = Image::new(matrix, input.layout(), input.format())?;
93 input.runtime().record_image_semantic(
94 ComputeDispatch {
95 kernel: KernelId::ImageThresholdBinaryInvF32,
96 buffers: &[
97 BufferBinding::read(input.storage()),
98 BufferBinding::write(output.storage()),
99 ],
100 push_constants: &[
101 PushConstant::U32(element_count),
102 PushConstant::U32(1),
103 PushConstant::F32(threshold),
104 PushConstant::F32(max_value),
105 PushConstant::F32(0.0),
106 PushConstant::F32(0.0),
107 ],
108 workgroups: KernelId::ImageThresholdBinaryInvF32.linear_workgroups(element_count),
109 indirect: None,
110 },
111 ImageSemanticDispatch {
112 contract,
113 inputs: &[ImageSemanticInput::Image(input)],
114 outputs: &[ImageSemanticOutput::Image(&output)],
115 attributes: &[float("threshold", threshold), float("max_value", max_value)],
116 },
117 )?;
118 Ok(output)
119}
120
121pub fn threshold_truncate(input: &Image, threshold: f32) -> Result<Image> {
123 let contract = crate::core::operation::image::THRESHOLD_TRUNCATE;
124 finite(&[threshold], "image::threshold_truncate")?;
125 if input.dtype() != DType::F32 {
126 return Err(Error::invalid_argument(format!(
127 "{} requires f32 storage",
128 contract.name()
129 )));
130 }
131 let element_count = u32::try_from(input.as_matrix().num_elements())
132 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
133 if element_count == 0 {
134 return Err(Error::invalid_argument(format!(
135 "{} requires a nonempty image",
136 contract.name()
137 )));
138 }
139 let matrix = crate::Matrix::allocate(
140 input.runtime(),
141 input.as_matrix().shape().to_vec(),
142 input.as_matrix().num_elements(),
143 DType::F32,
144 )?;
145 let output = Image::new(matrix, input.layout(), input.format())?;
146 input.runtime().record_image_semantic(
147 ComputeDispatch {
148 kernel: KernelId::ImageThresholdTruncateF32,
149 buffers: &[
150 BufferBinding::read(input.storage()),
151 BufferBinding::write(output.storage()),
152 ],
153 push_constants: &[
154 PushConstant::U32(element_count),
155 PushConstant::U32(2),
156 PushConstant::F32(threshold),
157 PushConstant::F32(0.0),
158 PushConstant::F32(0.0),
159 PushConstant::F32(0.0),
160 ],
161 workgroups: KernelId::ImageThresholdTruncateF32.linear_workgroups(element_count),
162 indirect: None,
163 },
164 ImageSemanticDispatch {
165 contract,
166 inputs: &[ImageSemanticInput::Image(input)],
167 outputs: &[ImageSemanticOutput::Image(&output)],
168 attributes: &[float("threshold", threshold)],
169 },
170 )?;
171 Ok(output)
172}
173
174pub fn threshold_to_zero(input: &Image, threshold: f32) -> Result<Image> {
176 let contract = crate::core::operation::image::THRESHOLD_TO_ZERO;
177 finite(&[threshold], "image::threshold_to_zero")?;
178 if input.dtype() != DType::F32 {
179 return Err(Error::invalid_argument(format!(
180 "{} requires f32 storage",
181 contract.name()
182 )));
183 }
184 let element_count = u32::try_from(input.as_matrix().num_elements())
185 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
186 if element_count == 0 {
187 return Err(Error::invalid_argument(format!(
188 "{} requires a nonempty image",
189 contract.name()
190 )));
191 }
192 let matrix = crate::Matrix::allocate(
193 input.runtime(),
194 input.as_matrix().shape().to_vec(),
195 input.as_matrix().num_elements(),
196 DType::F32,
197 )?;
198 let output = Image::new(matrix, input.layout(), input.format())?;
199 input.runtime().record_image_semantic(
200 ComputeDispatch {
201 kernel: KernelId::ImageThresholdToZeroF32,
202 buffers: &[
203 BufferBinding::read(input.storage()),
204 BufferBinding::write(output.storage()),
205 ],
206 push_constants: &[
207 PushConstant::U32(element_count),
208 PushConstant::U32(3),
209 PushConstant::F32(threshold),
210 PushConstant::F32(0.0),
211 PushConstant::F32(0.0),
212 PushConstant::F32(0.0),
213 ],
214 workgroups: KernelId::ImageThresholdToZeroF32.linear_workgroups(element_count),
215 indirect: None,
216 },
217 ImageSemanticDispatch {
218 contract,
219 inputs: &[ImageSemanticInput::Image(input)],
220 outputs: &[ImageSemanticOutput::Image(&output)],
221 attributes: &[float("threshold", threshold)],
222 },
223 )?;
224 Ok(output)
225}
226
227pub fn threshold_to_zero_inv(input: &Image, threshold: f32) -> Result<Image> {
229 let contract = crate::core::operation::image::THRESHOLD_TO_ZERO_INV;
230 finite(&[threshold], "image::threshold_to_zero_inv")?;
231 if input.dtype() != DType::F32 {
232 return Err(Error::invalid_argument(format!(
233 "{} requires f32 storage",
234 contract.name()
235 )));
236 }
237 let element_count = u32::try_from(input.as_matrix().num_elements())
238 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
239 if element_count == 0 {
240 return Err(Error::invalid_argument(format!(
241 "{} requires a nonempty image",
242 contract.name()
243 )));
244 }
245 let matrix = crate::Matrix::allocate(
246 input.runtime(),
247 input.as_matrix().shape().to_vec(),
248 input.as_matrix().num_elements(),
249 DType::F32,
250 )?;
251 let output = Image::new(matrix, input.layout(), input.format())?;
252 input.runtime().record_image_semantic(
253 ComputeDispatch {
254 kernel: KernelId::ImageThresholdToZeroInvF32,
255 buffers: &[
256 BufferBinding::read(input.storage()),
257 BufferBinding::write(output.storage()),
258 ],
259 push_constants: &[
260 PushConstant::U32(element_count),
261 PushConstant::U32(4),
262 PushConstant::F32(threshold),
263 PushConstant::F32(0.0),
264 PushConstant::F32(0.0),
265 PushConstant::F32(0.0),
266 ],
267 workgroups: KernelId::ImageThresholdToZeroInvF32.linear_workgroups(element_count),
268 indirect: None,
269 },
270 ImageSemanticDispatch {
271 contract,
272 inputs: &[ImageSemanticInput::Image(input)],
273 outputs: &[ImageSemanticOutput::Image(&output)],
274 attributes: &[float("threshold", threshold)],
275 },
276 )?;
277 Ok(output)
278}
279
280pub fn in_range(input: &Image, low: f32, high: f32, true_value: f32) -> Result<Image> {
282 let contract = crate::core::operation::image::IN_RANGE;
283 finite(&[low, high, true_value], "image::in_range")?;
284 if low > high {
285 return Err(Error::invalid_argument(
286 "image::in_range low must not exceed high",
287 ));
288 }
289 if input.dtype() != DType::F32 {
290 return Err(Error::invalid_argument(format!(
291 "{} requires f32 storage",
292 contract.name()
293 )));
294 }
295 let element_count = u32::try_from(input.as_matrix().num_elements())
296 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
297 if element_count == 0 {
298 return Err(Error::invalid_argument(format!(
299 "{} requires a nonempty image",
300 contract.name()
301 )));
302 }
303 let matrix = crate::Matrix::allocate(
304 input.runtime(),
305 input.as_matrix().shape().to_vec(),
306 input.as_matrix().num_elements(),
307 DType::F32,
308 )?;
309 let output = Image::new(matrix, input.layout(), input.format())?;
310 input.runtime().record_image_semantic(
311 ComputeDispatch {
312 kernel: KernelId::ImageInRangeF32,
313 buffers: &[
314 BufferBinding::read(input.storage()),
315 BufferBinding::write(output.storage()),
316 ],
317 push_constants: &[
318 PushConstant::U32(element_count),
319 PushConstant::U32(5),
320 PushConstant::F32(low),
321 PushConstant::F32(high),
322 PushConstant::F32(true_value),
323 PushConstant::F32(0.0),
324 ],
325 workgroups: KernelId::ImageInRangeF32.linear_workgroups(element_count),
326 indirect: None,
327 },
328 ImageSemanticDispatch {
329 contract,
330 inputs: &[ImageSemanticInput::Image(input)],
331 outputs: &[ImageSemanticOutput::Image(&output)],
332 attributes: &[
333 float("low", low),
334 float("high", high),
335 float("true_value", true_value),
336 ],
337 },
338 )?;
339 Ok(output)
340}
341
342pub fn clamp(input: &Image, low: f32, high: f32) -> Result<Image> {
344 let contract = crate::core::operation::image::CLAMP;
345 finite(&[low, high], "image::clamp")?;
346 if low > high {
347 return Err(Error::invalid_argument(
348 "image::clamp low must not exceed high",
349 ));
350 }
351 if input.dtype() != DType::F32 {
352 return Err(Error::invalid_argument(format!(
353 "{} requires f32 storage",
354 contract.name()
355 )));
356 }
357 let element_count = u32::try_from(input.as_matrix().num_elements())
358 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
359 if element_count == 0 {
360 return Err(Error::invalid_argument(format!(
361 "{} requires a nonempty image",
362 contract.name()
363 )));
364 }
365 let matrix = crate::Matrix::allocate(
366 input.runtime(),
367 input.as_matrix().shape().to_vec(),
368 input.as_matrix().num_elements(),
369 DType::F32,
370 )?;
371 let output = Image::new(matrix, input.layout(), input.format())?;
372 input.runtime().record_image_semantic(
373 ComputeDispatch {
374 kernel: KernelId::ImageClampF32,
375 buffers: &[
376 BufferBinding::read(input.storage()),
377 BufferBinding::write(output.storage()),
378 ],
379 push_constants: &[
380 PushConstant::U32(element_count),
381 PushConstant::U32(6),
382 PushConstant::F32(low),
383 PushConstant::F32(high),
384 PushConstant::F32(0.0),
385 PushConstant::F32(0.0),
386 ],
387 workgroups: KernelId::ImageClampF32.linear_workgroups(element_count),
388 indirect: None,
389 },
390 ImageSemanticDispatch {
391 contract,
392 inputs: &[ImageSemanticInput::Image(input)],
393 outputs: &[ImageSemanticOutput::Image(&output)],
394 attributes: &[float("low", low), float("high", high)],
395 },
396 )?;
397 Ok(output)
398}
399
400pub fn invert(input: &Image, max_value: f32) -> Result<Image> {
402 let contract = crate::core::operation::image::INVERT;
403 finite(&[max_value], "image::invert")?;
404 if input.dtype() != DType::F32 {
405 return Err(Error::invalid_argument(format!(
406 "{} requires f32 storage",
407 contract.name()
408 )));
409 }
410 let element_count = u32::try_from(input.as_matrix().num_elements())
411 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
412 if element_count == 0 {
413 return Err(Error::invalid_argument(format!(
414 "{} requires a nonempty image",
415 contract.name()
416 )));
417 }
418 let matrix = crate::Matrix::allocate(
419 input.runtime(),
420 input.as_matrix().shape().to_vec(),
421 input.as_matrix().num_elements(),
422 DType::F32,
423 )?;
424 let output = Image::new(matrix, input.layout(), input.format())?;
425 input.runtime().record_image_semantic(
426 ComputeDispatch {
427 kernel: KernelId::ImageInvertF32,
428 buffers: &[
429 BufferBinding::read(input.storage()),
430 BufferBinding::write(output.storage()),
431 ],
432 push_constants: &[
433 PushConstant::U32(element_count),
434 PushConstant::U32(7),
435 PushConstant::F32(max_value),
436 PushConstant::F32(0.0),
437 PushConstant::F32(0.0),
438 PushConstant::F32(0.0),
439 ],
440 workgroups: KernelId::ImageInvertF32.linear_workgroups(element_count),
441 indirect: None,
442 },
443 ImageSemanticDispatch {
444 contract,
445 inputs: &[ImageSemanticInput::Image(input)],
446 outputs: &[ImageSemanticOutput::Image(&output)],
447 attributes: &[float("max_value", max_value)],
448 },
449 )?;
450 Ok(output)
451}
452
453pub fn brightness_contrast(input: &Image, brightness: f32, contrast: f32) -> Result<Image> {
455 let contract = crate::core::operation::image::BRIGHTNESS_CONTRAST;
456 finite(&[brightness, contrast], "image::brightness_contrast")?;
457 if input.dtype() != DType::F32 {
458 return Err(Error::invalid_argument(format!(
459 "{} requires f32 storage",
460 contract.name()
461 )));
462 }
463 let element_count = u32::try_from(input.as_matrix().num_elements())
464 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
465 if element_count == 0 {
466 return Err(Error::invalid_argument(format!(
467 "{} requires a nonempty image",
468 contract.name()
469 )));
470 }
471 let matrix = crate::Matrix::allocate(
472 input.runtime(),
473 input.as_matrix().shape().to_vec(),
474 input.as_matrix().num_elements(),
475 DType::F32,
476 )?;
477 let output = Image::new(matrix, input.layout(), input.format())?;
478 input.runtime().record_image_semantic(
479 ComputeDispatch {
480 kernel: KernelId::ImageBrightnessContrastF32,
481 buffers: &[
482 BufferBinding::read(input.storage()),
483 BufferBinding::write(output.storage()),
484 ],
485 push_constants: &[
486 PushConstant::U32(element_count),
487 PushConstant::U32(8),
488 PushConstant::F32(contrast),
489 PushConstant::F32(brightness),
490 PushConstant::F32(0.0),
491 PushConstant::F32(0.0),
492 ],
493 workgroups: KernelId::ImageBrightnessContrastF32.linear_workgroups(element_count),
494 indirect: None,
495 },
496 ImageSemanticDispatch {
497 contract,
498 inputs: &[ImageSemanticInput::Image(input)],
499 outputs: &[ImageSemanticOutput::Image(&output)],
500 attributes: &[float("brightness", brightness), float("contrast", contrast)],
501 },
502 )?;
503 Ok(output)
504}
505
506pub fn gamma_contrast(input: &Image, gamma: f32, gain: f32) -> Result<Image> {
508 let contract = crate::core::operation::image::GAMMA_CONTRAST;
509 finite(&[gamma, gain], "image::gamma_contrast")?;
510 if gamma <= 0.0 {
511 return Err(Error::invalid_argument(
512 "image::gamma_contrast gamma must be positive",
513 ));
514 }
515 if input.dtype() != DType::F32 {
516 return Err(Error::invalid_argument(format!(
517 "{} requires f32 storage",
518 contract.name()
519 )));
520 }
521 let element_count = u32::try_from(input.as_matrix().num_elements())
522 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
523 if element_count == 0 {
524 return Err(Error::invalid_argument(format!(
525 "{} requires a nonempty image",
526 contract.name()
527 )));
528 }
529 let matrix = crate::Matrix::allocate(
530 input.runtime(),
531 input.as_matrix().shape().to_vec(),
532 input.as_matrix().num_elements(),
533 DType::F32,
534 )?;
535 let output = Image::new(matrix, input.layout(), input.format())?;
536 input.runtime().record_image_semantic(
537 ComputeDispatch {
538 kernel: KernelId::ImageGammaContrastF32,
539 buffers: &[
540 BufferBinding::read(input.storage()),
541 BufferBinding::write(output.storage()),
542 ],
543 push_constants: &[
544 PushConstant::U32(element_count),
545 PushConstant::U32(9),
546 PushConstant::F32(gamma),
547 PushConstant::F32(gain),
548 PushConstant::F32(0.0),
549 PushConstant::F32(0.0),
550 ],
551 workgroups: KernelId::ImageGammaContrastF32.linear_workgroups(element_count),
552 indirect: None,
553 },
554 ImageSemanticDispatch {
555 contract,
556 inputs: &[ImageSemanticInput::Image(input)],
557 outputs: &[ImageSemanticOutput::Image(&output)],
558 attributes: &[float("gamma", gamma), float("gain", gain)],
559 },
560 )?;
561 Ok(output)
562}
563
564pub fn solarize(input: &Image, threshold: f32, max_value: f32) -> Result<Image> {
566 let contract = crate::core::operation::image::SOLARIZE;
567 finite(&[threshold, max_value], "image::solarize")?;
568 if input.dtype() != DType::F32 {
569 return Err(Error::invalid_argument(format!(
570 "{} requires f32 storage",
571 contract.name()
572 )));
573 }
574 let element_count = u32::try_from(input.as_matrix().num_elements())
575 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
576 if element_count == 0 {
577 return Err(Error::invalid_argument(format!(
578 "{} requires a nonempty image",
579 contract.name()
580 )));
581 }
582 let matrix = crate::Matrix::allocate(
583 input.runtime(),
584 input.as_matrix().shape().to_vec(),
585 input.as_matrix().num_elements(),
586 DType::F32,
587 )?;
588 let output = Image::new(matrix, input.layout(), input.format())?;
589 input.runtime().record_image_semantic(
590 ComputeDispatch {
591 kernel: KernelId::ImageSolarizeF32,
592 buffers: &[
593 BufferBinding::read(input.storage()),
594 BufferBinding::write(output.storage()),
595 ],
596 push_constants: &[
597 PushConstant::U32(element_count),
598 PushConstant::U32(10),
599 PushConstant::F32(threshold),
600 PushConstant::F32(max_value),
601 PushConstant::F32(0.0),
602 PushConstant::F32(0.0),
603 ],
604 workgroups: KernelId::ImageSolarizeF32.linear_workgroups(element_count),
605 indirect: None,
606 },
607 ImageSemanticDispatch {
608 contract,
609 inputs: &[ImageSemanticInput::Image(input)],
610 outputs: &[ImageSemanticOutput::Image(&output)],
611 attributes: &[float("threshold", threshold), float("max_value", max_value)],
612 },
613 )?;
614 Ok(output)
615}
616
617pub fn posterize(input: &Image, levels: u32, low: f32, high: f32) -> Result<Image> {
619 let contract = crate::core::operation::image::POSTERIZE;
620 finite(&[low, high], "image::posterize")?;
621 if !(2..=65_536).contains(&levels) || low >= high {
622 return Err(Error::invalid_argument(
623 "image::posterize requires 2..=65536 levels and low < high",
624 ));
625 }
626 if input.dtype() != DType::F32 {
627 return Err(Error::invalid_argument(format!(
628 "{} requires f32 storage",
629 contract.name()
630 )));
631 }
632 let element_count = u32::try_from(input.as_matrix().num_elements())
633 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
634 if element_count == 0 {
635 return Err(Error::invalid_argument(format!(
636 "{} requires a nonempty image",
637 contract.name()
638 )));
639 }
640 let matrix = crate::Matrix::allocate(
641 input.runtime(),
642 input.as_matrix().shape().to_vec(),
643 input.as_matrix().num_elements(),
644 DType::F32,
645 )?;
646 let output = Image::new(matrix, input.layout(), input.format())?;
647 input.runtime().record_image_semantic(
648 ComputeDispatch {
649 kernel: KernelId::ImagePosterizeF32,
650 buffers: &[
651 BufferBinding::read(input.storage()),
652 BufferBinding::write(output.storage()),
653 ],
654 push_constants: &[
655 PushConstant::U32(element_count),
656 PushConstant::U32(11),
657 PushConstant::F32(levels as f32),
658 PushConstant::F32(low),
659 PushConstant::F32(high),
660 PushConstant::F32(0.0),
661 ],
662 workgroups: KernelId::ImagePosterizeF32.linear_workgroups(element_count),
663 indirect: None,
664 },
665 ImageSemanticDispatch {
666 contract,
667 inputs: &[ImageSemanticInput::Image(input)],
668 outputs: &[ImageSemanticOutput::Image(&output)],
669 attributes: &[
670 unsigned("levels", levels),
671 float("low", low),
672 float("high", high),
673 ],
674 },
675 )?;
676 Ok(output)
677}
678
679pub fn grayscale(input: &Image) -> Result<Image> {
681 let (batch, channels, height, width) = image_extent(input, "image::grayscale")?;
682 if !matches!(input.format(), ImageFormat::Rgb | ImageFormat::Rgba) {
683 return Err(Error::invalid_argument(
684 "image::grayscale requires RGB or RGBA channel semantics",
685 ));
686 }
687 let shape = match input.layout() {
688 ImageLayout::Nchw => vec![batch as usize, 1, height as usize, width as usize],
689 ImageLayout::Chw => vec![1, height as usize, width as usize],
690 _ => unreachable!("image extent admitted an unsupported layout"),
691 };
692 let output = allocate(input, shape, ImageFormat::Gray, "image::grayscale")?;
693 input.runtime().record_image_semantic(
694 ComputeDispatch {
695 kernel: KernelId::ImageGrayscaleF32,
696 buffers: &[
697 BufferBinding::read(input.storage()),
698 BufferBinding::write(output.storage()),
699 ],
700 push_constants: &[
701 PushConstant::U32(batch),
702 PushConstant::U32(channels),
703 PushConstant::U32(height),
704 PushConstant::U32(width),
705 ],
706 workgroups: [width.div_ceil(16), height.div_ceil(16), batch],
707 indirect: None,
708 },
709 ImageSemanticDispatch {
710 contract: crate::core::operation::image::GRAYSCALE,
711 inputs: &[ImageSemanticInput::Image(input)],
712 outputs: &[ImageSemanticOutput::Image(&output)],
713 attributes: &[],
714 },
715 )?;
716 Ok(output)
717}
718
719pub fn alpha_blend(left: &Image, right: &Image, alpha: f32) -> Result<Image> {
721 finite(&[alpha], "image::alpha_blend")?;
722 if !(0.0..=1.0).contains(&alpha) {
723 return Err(Error::invalid_argument(
724 "image::alpha_blend alpha must be in [0, 1]",
725 ));
726 }
727 validate_matching_images(left, right, "image::alpha_blend")?;
728 let contract = crate::core::operation::image::ALPHA_BLEND;
729 let (batch, channels, height, width) = image_extent(left, contract.name())?;
730 let mask_channels = u32::try_from(left.channels())
731 .map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
732 let output = allocate(
733 left,
734 left.as_matrix().shape().to_vec(),
735 left.format(),
736 contract.name(),
737 )?;
738 let buffers = [
739 BufferBinding::read(left.storage()),
740 BufferBinding::read(right.storage()),
741 BufferBinding::read(left.storage()),
742 BufferBinding::write(output.storage()),
743 ];
744 let push_constants = [
745 PushConstant::U32(batch),
746 PushConstant::U32(channels),
747 PushConstant::U32(height),
748 PushConstant::U32(width),
749 PushConstant::U32(0),
750 PushConstant::U32(mask_channels),
751 PushConstant::U32(0),
752 PushConstant::U32(0),
753 PushConstant::U32(0),
754 PushConstant::U32(0),
755 PushConstant::F32(alpha),
756 PushConstant::F32(0.0),
757 ];
758 left.runtime().record_image_semantic(
759 ComputeDispatch {
760 kernel: KernelId::ImageAlphaBlendF32,
761 buffers: &buffers,
762 push_constants: &push_constants,
763 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
764 indirect: None,
765 },
766 ImageSemanticDispatch {
767 contract,
768 inputs: &[
769 ImageSemanticInput::Image(left),
770 ImageSemanticInput::Image(right),
771 ],
772 outputs: &[ImageSemanticOutput::Image(&output)],
773 attributes: &[float("alpha", alpha)],
774 },
775 )?;
776 Ok(output)
777}
778
779pub fn composite(left: &Image, right: &Image, mask: &Image) -> Result<Image> {
781 let (batch, channels, height, width) = image_extent(left, "image::composite")?;
782 validate_matching_images(left, right, "image::composite")?;
783 let (mask_batch, mask_channels, mask_height, mask_width) =
784 image_extent(mask, "image::composite")?;
785 if !left.runtime().same_as(mask.runtime())
786 || mask_batch != batch
787 || mask_height != height
788 || mask_width != width
789 || !matches!(mask_channels, 1) && mask_channels != channels
790 {
791 return Err(Error::invalid_argument(
792 "image::composite mask must share batch/spatial extents and have one or matching channels",
793 ));
794 }
795 let contract = crate::core::operation::image::COMPOSITE;
796 let (batch, channels, height, width) = image_extent(left, contract.name())?;
797 let mask_channels = u32::try_from(mask.channels())
798 .map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
799 let output = allocate(
800 left,
801 left.as_matrix().shape().to_vec(),
802 left.format(),
803 contract.name(),
804 )?;
805 let buffers = [
806 BufferBinding::read(left.storage()),
807 BufferBinding::read(right.storage()),
808 BufferBinding::read(mask.storage()),
809 BufferBinding::write(output.storage()),
810 ];
811 let push_constants = [
812 PushConstant::U32(batch),
813 PushConstant::U32(channels),
814 PushConstant::U32(height),
815 PushConstant::U32(width),
816 PushConstant::U32(1),
817 PushConstant::U32(mask_channels),
818 PushConstant::U32(0),
819 PushConstant::U32(0),
820 PushConstant::U32(0),
821 PushConstant::U32(0),
822 PushConstant::F32(0.0),
823 PushConstant::F32(0.0),
824 ];
825 left.runtime().record_image_semantic(
826 ComputeDispatch {
827 kernel: KernelId::ImageCompositeF32,
828 buffers: &buffers,
829 push_constants: &push_constants,
830 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
831 indirect: None,
832 },
833 ImageSemanticDispatch {
834 contract,
835 inputs: &[
836 ImageSemanticInput::Image(left),
837 ImageSemanticInput::Image(right),
838 ImageSemanticInput::Image(mask),
839 ],
840 outputs: &[ImageSemanticOutput::Image(&output)],
841 attributes: &[],
842 },
843 )?;
844 Ok(output)
845}
846
847pub fn erase(input: &Image, x: u32, y: u32, width: u32, height: u32, value: f32) -> Result<Image> {
849 finite(&[value], "image::erase")?;
850 let (_, _, image_height, image_width) = image_extent(input, "image::erase")?;
851 if width == 0 || height == 0 || x >= image_width || y >= image_height {
852 return Err(Error::invalid_argument(
853 "image::erase requires a nonzero rectangle with an in-bounds origin",
854 ));
855 }
856 let contract = crate::core::operation::image::ERASE;
857 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
858 let mask_channels = u32::try_from(input.channels())
859 .map_err(|_| Error::out_of_range(format!("{} mask channels exceed u32", contract.name())))?;
860 let output = allocate(
861 input,
862 input.as_matrix().shape().to_vec(),
863 input.format(),
864 contract.name(),
865 )?;
866 let buffers = [
867 BufferBinding::read(input.storage()),
868 BufferBinding::read(input.storage()),
869 BufferBinding::read(input.storage()),
870 BufferBinding::write(output.storage()),
871 ];
872 let push_constants = [
873 PushConstant::U32(batch),
874 PushConstant::U32(channels),
875 PushConstant::U32(image_height),
876 PushConstant::U32(image_width),
877 PushConstant::U32(2),
878 PushConstant::U32(mask_channels),
879 PushConstant::U32(x),
880 PushConstant::U32(y),
881 PushConstant::U32(width),
882 PushConstant::U32(height),
883 PushConstant::F32(0.0),
884 PushConstant::F32(value),
885 ];
886 input.runtime().record_image_semantic(
887 ComputeDispatch {
888 kernel: KernelId::ImageEraseF32,
889 buffers: &buffers,
890 push_constants: &push_constants,
891 workgroups: [
892 image_width.div_ceil(16),
893 image_height.div_ceil(16),
894 batch * channels,
895 ],
896 indirect: None,
897 },
898 ImageSemanticDispatch {
899 contract,
900 inputs: &[ImageSemanticInput::Image(input)],
901 outputs: &[ImageSemanticOutput::Image(&output)],
902 attributes: &[
903 unsigned("x", x),
904 unsigned("y", y),
905 unsigned("width", width),
906 unsigned("height", height),
907 float("value", value),
908 ],
909 },
910 )?;
911 Ok(output)
912}
913
914pub fn color_twist(input: &Image, transform: &Matrix) -> Result<Image> {
916 let (batch, channels, height, width) = image_extent(input, "image::color_twist")?;
917 if !matches!(input.format(), ImageFormat::Rgb | ImageFormat::Rgba)
918 || transform.dtype() != DType::F32
919 || transform.shape() != [3, 4]
920 || !input.runtime().same_as(transform.runtime())
921 {
922 return Err(Error::invalid_argument(
923 "image::color_twist requires RGB/RGBA input and a same-runtime FP32 [3, 4] transform",
924 ));
925 }
926 let output = allocate(
927 input,
928 input.as_matrix().shape().to_vec(),
929 input.format(),
930 "image::color_twist",
931 )?;
932 let workgroups = [width.div_ceil(16), height.div_ceil(16), batch * channels];
933 input.runtime().record_image_semantic(
934 ComputeDispatch {
935 kernel: KernelId::ImageColorTwistF32,
936 buffers: &[
937 BufferBinding::read(input.storage()),
938 BufferBinding::read(transform.storage()),
939 BufferBinding::write(output.storage()),
940 ],
941 push_constants: &[
942 PushConstant::U32(batch),
943 PushConstant::U32(channels),
944 PushConstant::U32(height),
945 PushConstant::U32(width),
946 ],
947 workgroups,
948 indirect: None,
949 },
950 ImageSemanticDispatch {
951 contract: crate::core::operation::image::COLOR_TWIST,
952 inputs: &[
953 ImageSemanticInput::Image(input),
954 ImageSemanticInput::Matrix(transform),
955 ],
956 outputs: &[ImageSemanticOutput::Image(&output)],
957 attributes: &[],
958 },
959 )?;
960 Ok(output)
961}
962
963pub fn channel_reorder(
969 input: &Image,
970 order: [u32; 4],
971 output_format: ImageFormat,
972) -> Result<Image> {
973 let (batch, channels, height, width) = image_extent(input, "image::channel_reorder")?;
974 if output_format.channels() != input.channels()
975 || order[..channels as usize]
976 .iter()
977 .any(|channel| *channel >= channels)
978 {
979 return Err(Error::invalid_argument(
980 "image::channel_reorder requires in-range source channels and an equal-width output format",
981 ));
982 }
983 let output = allocate(
984 input,
985 input.as_matrix().shape().to_vec(),
986 output_format,
987 "image::channel_reorder",
988 )?;
989 input.runtime().record_image_semantic(
990 ComputeDispatch {
991 kernel: KernelId::ImageChannelReorderF32,
992 buffers: &[
993 BufferBinding::read(input.storage()),
994 BufferBinding::write(output.storage()),
995 ],
996 push_constants: &[
997 PushConstant::U32(batch),
998 PushConstant::U32(channels),
999 PushConstant::U32(height),
1000 PushConstant::U32(width),
1001 PushConstant::U32(order[0]),
1002 PushConstant::U32(order[1]),
1003 PushConstant::U32(order[2]),
1004 PushConstant::U32(order[3]),
1005 ],
1006 workgroups: [width.div_ceil(16), height.div_ceil(16), batch * channels],
1007 indirect: None,
1008 },
1009 ImageSemanticDispatch {
1010 contract: crate::core::operation::image::CHANNEL_REORDER,
1011 inputs: &[ImageSemanticInput::Image(input)],
1012 outputs: &[ImageSemanticOutput::Image(&output)],
1013 attributes: &[
1014 unsigned("channel_0", order[0]),
1015 unsigned("channel_1", order[1]),
1016 unsigned("channel_2", order[2]),
1017 unsigned("channel_3", order[3]),
1018 enumeration("output_format", image_format_token(output_format)),
1019 ],
1020 },
1021 )?;
1022 Ok(output)
1023}
1024
1025pub fn gaussian_noise(input: &Image, mean: f32, stddev: f32, seed: u64) -> Result<Image> {
1027 finite(&[mean, stddev], "image::gaussian_noise")?;
1028 if stddev < 0.0 {
1029 return Err(Error::invalid_argument(
1030 "image::gaussian_noise standard deviation must be nonnegative",
1031 ));
1032 }
1033 let contract = crate::core::operation::image::GAUSSIAN_NOISE;
1034 image_extent(input, contract.name())?;
1035 let element_count = u32::try_from(input.as_matrix().num_elements())
1036 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
1037 let output = allocate(
1038 input,
1039 input.as_matrix().shape().to_vec(),
1040 input.format(),
1041 contract.name(),
1042 )?;
1043 let push_constants = [
1044 PushConstant::U32(element_count),
1045 PushConstant::U32(seed as u32),
1046 PushConstant::U32((seed >> 32) as u32),
1047 PushConstant::F32(mean),
1048 PushConstant::F32(stddev),
1049 ];
1050 input.runtime().record_image_semantic(
1051 ComputeDispatch {
1052 kernel: KernelId::ImageGaussianNoiseF32,
1053 buffers: &[
1054 BufferBinding::read(input.storage()),
1055 BufferBinding::write(output.storage()),
1056 ],
1057 push_constants: &push_constants,
1058 workgroups: KernelId::ImageGaussianNoiseF32.linear_workgroups(element_count),
1059 indirect: None,
1060 },
1061 ImageSemanticDispatch {
1062 contract,
1063 inputs: &[ImageSemanticInput::Image(input)],
1064 outputs: &[ImageSemanticOutput::Image(&output)],
1065 attributes: &[
1066 float("mean", mean),
1067 float("stddev", stddev),
1068 unsigned64("seed", seed),
1069 ],
1070 },
1071 )?;
1072 Ok(output)
1073}
1074
1075pub fn salt_pepper_noise(
1077 input: &Image,
1078 probability: f32,
1079 salt_value: f32,
1080 pepper_value: f32,
1081 seed: u64,
1082) -> Result<Image> {
1083 finite(
1084 &[probability, salt_value, pepper_value],
1085 "image::salt_pepper_noise",
1086 )?;
1087 if !(0.0..=1.0).contains(&probability) {
1088 return Err(Error::invalid_argument(
1089 "image::salt_pepper_noise probability must be in [0, 1]",
1090 ));
1091 }
1092 let contract = crate::core::operation::image::SALT_PEPPER_NOISE;
1093 image_extent(input, contract.name())?;
1094 let element_count = u32::try_from(input.as_matrix().num_elements())
1095 .map_err(|_| Error::out_of_range(format!("{} element count exceeds u32", contract.name())))?;
1096 let output = allocate(
1097 input,
1098 input.as_matrix().shape().to_vec(),
1099 input.format(),
1100 contract.name(),
1101 )?;
1102 let push_constants = [
1103 PushConstant::U32(element_count),
1104 PushConstant::U32(seed as u32),
1105 PushConstant::U32((seed >> 32) as u32),
1106 PushConstant::F32(probability),
1107 PushConstant::F32(salt_value),
1108 PushConstant::F32(pepper_value),
1109 ];
1110 input.runtime().record_image_semantic(
1111 ComputeDispatch {
1112 kernel: KernelId::ImageSaltPepperNoiseF32,
1113 buffers: &[
1114 BufferBinding::read(input.storage()),
1115 BufferBinding::write(output.storage()),
1116 ],
1117 push_constants: &push_constants,
1118 workgroups: KernelId::ImageSaltPepperNoiseF32.linear_workgroups(element_count),
1119 indirect: None,
1120 },
1121 ImageSemanticDispatch {
1122 contract,
1123 inputs: &[ImageSemanticInput::Image(input)],
1124 outputs: &[ImageSemanticOutput::Image(&output)],
1125 attributes: &[
1126 float("probability", probability),
1127 float("salt_value", salt_value),
1128 float("pepper_value", pepper_value),
1129 unsigned64("seed", seed),
1130 ],
1131 },
1132 )?;
1133 Ok(output)
1134}
1135
1136#[allow(clippy::too_many_arguments)]
1153pub fn flood_fill(
1154 input: &Image,
1155 seed_x: u32,
1156 seed_y: u32,
1157 value: f32,
1158 lo_diff: f32,
1159 up_diff: f32,
1160 connectivity: Connectivity,
1161 propagation_passes: u32,
1162) -> Result<Image> {
1163 let contract = crate::core::operation::image::FLOOD_FILL;
1164 finite(&[value, lo_diff, up_diff], "image::flood_fill")?;
1165 if lo_diff < 0.0 || up_diff < 0.0 {
1166 return Err(Error::invalid_argument(
1167 "image::flood_fill diffs must be nonnegative",
1168 ));
1169 }
1170 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1171 if seed_x >= image_width || seed_y >= image_height {
1172 return Err(Error::invalid_argument(
1173 "image::flood_fill seed must be in bounds",
1174 ));
1175 }
1176 let plane_count = batch
1177 .checked_mul(channels)
1178 .ok_or_else(|| Error::out_of_range("image::flood_fill plane count exceeds u32"))?;
1179 let element_count = u32::try_from(input.as_matrix().num_elements())
1180 .map_err(|_| Error::out_of_range("image::flood_fill element count exceeds u32"))?;
1181 let relax_passes = if propagation_passes == 0 {
1182 image_height
1183 .checked_add(image_width)
1184 .ok_or_else(|| Error::out_of_range("image::flood_fill propagation bound exceeds u32"))?
1185 } else {
1186 propagation_passes
1187 };
1188 let matrix = crate::Matrix::allocate(
1189 input.runtime(),
1190 input.as_matrix().shape().to_vec(),
1191 input.as_matrix().num_elements(),
1192 DType::F32,
1193 )?;
1194 let output = Image::new(matrix, input.layout(), input.format())?;
1195 let marker = Matrix::allocate(
1196 input.runtime(),
1197 vec![
1198 plane_count as usize,
1199 image_height as usize,
1200 image_width as usize,
1201 ],
1202 element_count as usize,
1203 DType::U32,
1204 )?;
1205 let mut workgroups = KernelId::ImageFloodFillInitF32.output_workgroups(image_width, image_height);
1206 workgroups[2] = plane_count;
1207 let init_buffers = [
1208 BufferBinding::read(input.storage()),
1209 BufferBinding::write(output.storage()),
1210 BufferBinding::write(marker.storage()),
1211 ];
1212 let init_push = [
1213 PushConstant::U32(batch),
1214 PushConstant::U32(channels),
1215 PushConstant::U32(image_height),
1216 PushConstant::U32(image_width),
1217 PushConstant::U32(seed_x),
1218 PushConstant::U32(seed_y),
1219 PushConstant::F32(value),
1220 ];
1221 let relax_buffers = [
1222 BufferBinding::read(input.storage()),
1223 BufferBinding::read_write(output.storage()),
1224 BufferBinding::read_write(marker.storage()),
1225 ];
1226 let relax_push = [
1227 PushConstant::U32(batch),
1228 PushConstant::U32(channels),
1229 PushConstant::U32(image_height),
1230 PushConstant::U32(image_width),
1231 PushConstant::U32(connectivity.code()),
1232 PushConstant::F32(lo_diff),
1233 PushConstant::F32(up_diff),
1234 PushConstant::F32(value),
1235 ];
1236 let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
1237 dispatches.push(ComputeDispatch {
1238 kernel: KernelId::ImageFloodFillInitF32,
1239 buffers: &init_buffers,
1240 push_constants: &init_push,
1241 workgroups,
1242 indirect: None,
1243 });
1244 for _ in 0..relax_passes {
1245 dispatches.push(ComputeDispatch {
1246 kernel: KernelId::ImageFloodFillRelaxF32,
1247 buffers: &relax_buffers,
1248 push_constants: &relax_push,
1249 workgroups,
1250 indirect: None,
1251 });
1252 }
1253 let attributes = [
1254 unsigned("seed_x", seed_x),
1255 unsigned("seed_y", seed_y),
1256 float("value", value),
1257 float("lo_diff", lo_diff),
1258 float("up_diff", up_diff),
1259 enumeration("connectivity", connectivity.token()),
1260 unsigned("propagation_passes", propagation_passes),
1261 ];
1262 input.runtime().record_image_split_semantic(
1263 &dispatches,
1264 ImageSemanticDispatch {
1265 contract,
1266 inputs: &[ImageSemanticInput::Image(input)],
1267 outputs: &[ImageSemanticOutput::Image(&output)],
1268 attributes: &attributes,
1269 },
1270 )?;
1271 Ok(output)
1272}
1273
1274#[allow(clippy::too_many_arguments)]
1286pub fn draw_line(
1287 input: &Image,
1288 x1: f32,
1289 y1: f32,
1290 x2: f32,
1291 y2: f32,
1292 color: f32,
1293 thickness: f32,
1294) -> Result<Image> {
1295 let contract = crate::core::operation::image::DRAW_LINE;
1296 finite(&[x1, y1, x2, y2, color, thickness], "image::draw_line")?;
1297 if thickness <= 0.0 {
1298 return Err(Error::invalid_argument(
1299 "image::draw_line thickness must be positive",
1300 ));
1301 }
1302 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1303 let element_count = u32::try_from(input.as_matrix().num_elements())
1304 .map_err(|_| Error::out_of_range("image::draw_line element count exceeds u32"))?;
1305 let matrix = crate::Matrix::allocate(
1306 input.runtime(),
1307 input.as_matrix().shape().to_vec(),
1308 input.as_matrix().num_elements(),
1309 DType::F32,
1310 )?;
1311 let output = Image::new(matrix, input.layout(), input.format())?;
1312 input.runtime().record_image_semantic(
1313 ComputeDispatch {
1314 kernel: KernelId::ImageDrawLineF32,
1315 buffers: &[
1316 BufferBinding::read(input.storage()),
1317 BufferBinding::write(output.storage()),
1318 ],
1319 push_constants: &[
1320 PushConstant::U32(batch),
1321 PushConstant::U32(channels),
1322 PushConstant::U32(element_count),
1323 PushConstant::U32(image_height),
1324 PushConstant::U32(image_width),
1325 PushConstant::F32(x1),
1326 PushConstant::F32(y1),
1327 PushConstant::F32(x2),
1328 PushConstant::F32(y2),
1329 PushConstant::F32(color),
1330 PushConstant::F32(thickness),
1331 ],
1332 workgroups: KernelId::ImageDrawLineF32.linear_workgroups(element_count),
1333 indirect: None,
1334 },
1335 ImageSemanticDispatch {
1336 contract,
1337 inputs: &[ImageSemanticInput::Image(input)],
1338 outputs: &[ImageSemanticOutput::Image(&output)],
1339 attributes: &[
1340 float("x1", x1),
1341 float("y1", y1),
1342 float("x2", x2),
1343 float("y2", y2),
1344 float("color", color),
1345 float("thickness", thickness),
1346 ],
1347 },
1348 )?;
1349 Ok(output)
1350}
1351
1352#[allow(clippy::too_many_arguments)]
1365pub fn draw_rectangle(
1366 input: &Image,
1367 x: f32,
1368 y: f32,
1369 width: f32,
1370 height: f32,
1371 color: f32,
1372 thickness: f32,
1373) -> Result<Image> {
1374 let contract = crate::core::operation::image::DRAW_RECTANGLE;
1375 finite(
1376 &[x, y, width, height, color, thickness],
1377 "image::draw_rectangle",
1378 )?;
1379 if width <= 0.0 || height <= 0.0 {
1380 return Err(Error::invalid_argument(
1381 "image::draw_rectangle width and height must be positive",
1382 ));
1383 }
1384 if thickness == 0.0 {
1385 return Err(Error::invalid_argument(
1386 "image::draw_rectangle thickness must be nonzero",
1387 ));
1388 }
1389 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1390 let element_count = u32::try_from(input.as_matrix().num_elements())
1391 .map_err(|_| Error::out_of_range("image::draw_rectangle element count exceeds u32"))?;
1392 let matrix = crate::Matrix::allocate(
1393 input.runtime(),
1394 input.as_matrix().shape().to_vec(),
1395 input.as_matrix().num_elements(),
1396 DType::F32,
1397 )?;
1398 let output = Image::new(matrix, input.layout(), input.format())?;
1399 input.runtime().record_image_semantic(
1400 ComputeDispatch {
1401 kernel: KernelId::ImageDrawRectangleF32,
1402 buffers: &[
1403 BufferBinding::read(input.storage()),
1404 BufferBinding::write(output.storage()),
1405 ],
1406 push_constants: &[
1407 PushConstant::U32(batch),
1408 PushConstant::U32(channels),
1409 PushConstant::U32(element_count),
1410 PushConstant::U32(image_height),
1411 PushConstant::U32(image_width),
1412 PushConstant::F32(x),
1413 PushConstant::F32(y),
1414 PushConstant::F32(width),
1415 PushConstant::F32(height),
1416 PushConstant::F32(color),
1417 PushConstant::F32(thickness),
1418 ],
1419 workgroups: KernelId::ImageDrawRectangleF32.linear_workgroups(element_count),
1420 indirect: None,
1421 },
1422 ImageSemanticDispatch {
1423 contract,
1424 inputs: &[ImageSemanticInput::Image(input)],
1425 outputs: &[ImageSemanticOutput::Image(&output)],
1426 attributes: &[
1427 float("x", x),
1428 float("y", y),
1429 float("width", width),
1430 float("height", height),
1431 float("color", color),
1432 float("thickness", thickness),
1433 ],
1434 },
1435 )?;
1436 Ok(output)
1437}
1438
1439pub fn draw_circle(
1451 input: &Image,
1452 cx: f32,
1453 cy: f32,
1454 radius: f32,
1455 color: f32,
1456 thickness: f32,
1457) -> Result<Image> {
1458 let contract = crate::core::operation::image::DRAW_CIRCLE;
1459 finite(&[cx, cy, radius, color, thickness], "image::draw_circle")?;
1460 if radius <= 0.0 {
1461 return Err(Error::invalid_argument(
1462 "image::draw_circle radius must be positive",
1463 ));
1464 }
1465 if thickness == 0.0 {
1466 return Err(Error::invalid_argument(
1467 "image::draw_circle thickness must be nonzero",
1468 ));
1469 }
1470 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1471 let element_count = u32::try_from(input.as_matrix().num_elements())
1472 .map_err(|_| Error::out_of_range("image::draw_circle element count exceeds u32"))?;
1473 let matrix = crate::Matrix::allocate(
1474 input.runtime(),
1475 input.as_matrix().shape().to_vec(),
1476 input.as_matrix().num_elements(),
1477 DType::F32,
1478 )?;
1479 let output = Image::new(matrix, input.layout(), input.format())?;
1480 input.runtime().record_image_semantic(
1481 ComputeDispatch {
1482 kernel: KernelId::ImageDrawCircleF32,
1483 buffers: &[
1484 BufferBinding::read(input.storage()),
1485 BufferBinding::write(output.storage()),
1486 ],
1487 push_constants: &[
1488 PushConstant::U32(batch),
1489 PushConstant::U32(channels),
1490 PushConstant::U32(element_count),
1491 PushConstant::U32(image_height),
1492 PushConstant::U32(image_width),
1493 PushConstant::F32(cx),
1494 PushConstant::F32(cy),
1495 PushConstant::F32(radius),
1496 PushConstant::F32(color),
1497 PushConstant::F32(thickness),
1498 ],
1499 workgroups: KernelId::ImageDrawCircleF32.linear_workgroups(element_count),
1500 indirect: None,
1501 },
1502 ImageSemanticDispatch {
1503 contract,
1504 inputs: &[ImageSemanticInput::Image(input)],
1505 outputs: &[ImageSemanticOutput::Image(&output)],
1506 attributes: &[
1507 float("cx", cx),
1508 float("cy", cy),
1509 float("radius", radius),
1510 float("color", color),
1511 float("thickness", thickness),
1512 ],
1513 },
1514 )?;
1515 Ok(output)
1516}
1517
1518pub fn fill_polygon(input: &Image, points: &Matrix, color: f32) -> Result<Image> {
1529 let contract = crate::core::operation::image::FILL_POLYGON;
1530 if !color.is_finite() {
1531 return Err(Error::invalid_argument(
1532 "image::fill_polygon color must be finite",
1533 ));
1534 }
1535 if points.dtype() != DType::F32 {
1536 return Err(Error::invalid_argument(
1537 "image::fill_polygon points must be f32",
1538 ));
1539 }
1540 if !input.runtime().same_as(points.runtime()) {
1541 return Err(Error::invalid_argument(
1542 "image::fill_polygon points must share the input runtime",
1543 ));
1544 }
1545 if points.shape().len() != 2 || points.shape()[1] != 2 || points.shape()[0] < 3 {
1546 return Err(Error::invalid_argument(
1547 "image::fill_polygon points must have shape [N, 2] with N >= 3",
1548 ));
1549 }
1550 let point_count_u32 = u32::try_from(points.shape()[0])
1551 .map_err(|_| Error::out_of_range("image::fill_polygon point count exceeds u32"))?;
1552 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1553 let element_count = u32::try_from(input.as_matrix().num_elements())
1554 .map_err(|_| Error::out_of_range("image::fill_polygon element count exceeds u32"))?;
1555 let matrix = crate::Matrix::allocate(
1556 input.runtime(),
1557 input.as_matrix().shape().to_vec(),
1558 input.as_matrix().num_elements(),
1559 DType::F32,
1560 )?;
1561 let output = Image::new(matrix, input.layout(), input.format())?;
1562 input.runtime().record_image_semantic(
1563 ComputeDispatch {
1564 kernel: KernelId::ImageFillPolygonF32,
1565 buffers: &[
1566 BufferBinding::read(input.storage()),
1567 BufferBinding::read(points.storage()),
1568 BufferBinding::write(output.storage()),
1569 ],
1570 push_constants: &[
1571 PushConstant::U32(batch),
1572 PushConstant::U32(channels),
1573 PushConstant::U32(element_count),
1574 PushConstant::U32(image_height),
1575 PushConstant::U32(image_width),
1576 PushConstant::U32(point_count_u32),
1577 PushConstant::F32(color),
1578 ],
1579 workgroups: KernelId::ImageFillPolygonF32.linear_workgroups(element_count),
1580 indirect: None,
1581 },
1582 ImageSemanticDispatch {
1583 contract,
1584 inputs: &[
1585 ImageSemanticInput::Image(input),
1586 ImageSemanticInput::Matrix(points),
1587 ],
1588 outputs: &[ImageSemanticOutput::Image(&output)],
1589 attributes: &[float("color", color)],
1590 },
1591 )?;
1592 Ok(output)
1593}
1594
1595fn validate_matching_images(a: &Image, b: &Image, operation: &str) -> Result<()> {
1596 image_extent(a, operation)?;
1597 if a.as_matrix().shape() != b.as_matrix().shape()
1598 || a.dtype() != b.dtype()
1599 || a.layout() != b.layout()
1600 || a.format() != b.format()
1601 || !a.runtime().same_as(b.runtime())
1602 {
1603 return Err(Error::invalid_argument(format!(
1604 "{operation} images must have identical shape, dtype, layout, format, and runtime"
1605 )));
1606 }
1607 Ok(())
1608}
1609
1610fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
1611 if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
1612 {
1613 return Err(Error::invalid_argument(format!(
1614 "{operation} requires an FP32 NCHW or CHW image"
1615 )));
1616 }
1617 let extent = (
1618 u32::try_from(input.batch_size()),
1619 u32::try_from(input.channels()),
1620 u32::try_from(input.height()),
1621 u32::try_from(input.width()),
1622 );
1623 let (batch, channels, height, width) = match extent {
1624 (Ok(batch), Ok(channels), Ok(height), Ok(width)) => (batch, channels, height, width),
1625 _ => {
1626 return Err(Error::out_of_range(format!(
1627 "{operation} extent exceeds u32"
1628 )));
1629 }
1630 };
1631 if batch == 0 || channels == 0 || height == 0 || width == 0 {
1632 return Err(Error::invalid_argument(format!(
1633 "{operation} requires a nonempty image"
1634 )));
1635 }
1636 Ok((batch, channels, height, width))
1637}
1638
1639fn allocate(
1640 input: &Image,
1641 shape: Vec<usize>,
1642 format: ImageFormat,
1643 operation: &str,
1644) -> Result<Image> {
1645 let elements = shape.iter().copied().try_fold(1_usize, |count, extent| {
1646 count
1647 .checked_mul(extent)
1648 .ok_or_else(|| Error::out_of_range(format!("{operation} output size exceeds usize")))
1649 })?;
1650 u32::try_from(elements)
1651 .map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
1652 let matrix = Matrix::allocate(input.runtime(), shape, elements, DType::F32)?;
1653 Image::new(matrix, input.layout(), format)
1654}
1655
1656#[allow(clippy::too_many_arguments)]
1657fn finite(values: &[f32], operation: &str) -> Result<()> {
1658 if values.iter().all(|value| value.is_finite()) {
1659 Ok(())
1660 } else {
1661 Err(Error::invalid_argument(format!(
1662 "{operation} parameters must be finite"
1663 )))
1664 }
1665}
1666
1667fn float(name: &str, value: f32) -> OpAttribute {
1668 OpAttribute::Float {
1669 name: name.into(),
1670 value: f64::from(value),
1671 }
1672}
1673
1674fn unsigned(name: &str, value: u32) -> OpAttribute {
1675 OpAttribute::UnsignedInteger {
1676 name: name.into(),
1677 value: u64::from(value),
1678 }
1679}
1680
1681fn unsigned64(name: &str, value: u64) -> OpAttribute {
1682 OpAttribute::UnsignedInteger {
1683 name: name.into(),
1684 value,
1685 }
1686}
1687
1688fn enumeration(name: &str, value: &str) -> OpAttribute {
1689 OpAttribute::Enum {
1690 name: name.into(),
1691 value: value.into(),
1692 }
1693}
1694
1695const fn image_format_token(format: ImageFormat) -> &'static str {
1696 match format {
1697 ImageFormat::Gray => "gray",
1698 ImageFormat::GrayAlpha => "gray_alpha",
1699 ImageFormat::Rgb => "rgb",
1700 ImageFormat::Rgba => "rgba",
1701 ImageFormat::Bgr => "bgr",
1702 ImageFormat::Bgra => "bgra",
1703 }
1704}