1use crate::{
7 DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
8 runtime::{
9 BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10 KernelId, PushConstant,
11 },
12};
13
14pub fn calc_hist(input: &Image, bins: u32, lower: f32, upper: f32) -> Result<Matrix> {
29 if bins == 0 || bins > 256 {
30 return Err(Error::invalid_argument(
31 "image::calc_hist bins must be in 1..=256",
32 ));
33 }
34 if !lower.is_finite() || !upper.is_finite() || lower >= upper {
35 return Err(Error::invalid_argument(
36 "image::calc_hist requires finite bounds with lower < upper",
37 ));
38 }
39 let (batch, channels, image_height, image_width) = image_extent(input, "image::calc_hist")?;
40 let mut shape = input.as_matrix().shape().to_vec();
41 shape.truncate(shape.len() - 2);
42 shape.push(bins as usize);
43 let histogram_elements = shape
44 .iter()
45 .try_fold(1u32, |count, value| {
46 count.checked_mul(u32::try_from(*value).ok()?)
47 })
48 .ok_or_else(|| Error::out_of_range("image::calc_hist output size exceeds u32"))?;
49 let histogram = Matrix::allocate(
50 input.runtime(),
51 shape,
52 histogram_elements as usize,
53 DType::U32,
54 )?;
55 let clear_buffers = [BufferBinding::write(histogram.storage())];
56 let clear_push = [PushConstant::U32(histogram_elements)];
57 let count_buffers = [
58 BufferBinding::read(input.storage()),
59 BufferBinding::read_write(histogram.storage()),
60 ];
61 let count_push = [
62 PushConstant::U32(batch),
63 PushConstant::U32(channels),
64 PushConstant::U32(image_height),
65 PushConstant::U32(image_width),
66 PushConstant::U32(bins),
67 PushConstant::F32(lower),
68 PushConstant::F32(upper),
69 ];
70 let dispatches = [
71 ComputeDispatch {
72 kernel: KernelId::ImageCalcHistClearU32,
73 buffers: &clear_buffers,
74 push_constants: &clear_push,
75 workgroups: KernelId::ImageCalcHistClearU32.linear_workgroups(histogram_elements),
76 indirect: None,
77 },
78 ComputeDispatch {
79 kernel: KernelId::ImageCalcHistF32,
80 buffers: &count_buffers,
81 push_constants: &count_push,
82 workgroups: [
83 image_width.div_ceil(16),
84 image_height.div_ceil(16),
85 batch * channels,
86 ],
87 indirect: None,
88 },
89 ];
90 let attributes = [
91 unsigned("bins", bins),
92 float("lower", lower),
93 float("upper", upper),
94 ];
95 input.runtime().record_image_split_semantic(
96 &dispatches,
97 ImageSemanticDispatch {
98 contract: crate::core::operation::image::CALC_HIST,
99 inputs: &[ImageSemanticInput::Image(input)],
100 outputs: &[ImageSemanticOutput::Matrix(&histogram)],
101 attributes: &attributes,
102 },
103 )?;
104 Ok(histogram)
105}
106
107pub fn equalize_hist(input: &Image) -> Result<Image> {
119 let (batch, channels, image_height, image_width) = image_extent(input, "image::equalize_hist")?;
120 let mut histogram_shape = input.as_matrix().shape().to_vec();
121 histogram_shape.truncate(histogram_shape.len() - 2);
122 histogram_shape.push(256);
123 let histogram_elements = histogram_shape
124 .iter()
125 .try_fold(1u32, |count, value| {
126 count.checked_mul(u32::try_from(*value).ok()?)
127 })
128 .ok_or_else(|| Error::out_of_range("image::equalize_hist workspace exceeds u32"))?;
129 let runtime = input.runtime();
130 let histogram = Matrix::allocate(
131 runtime,
132 histogram_shape.clone(),
133 histogram_elements as usize,
134 DType::U32,
135 )?;
136 let lut = Matrix::allocate(
137 runtime,
138 histogram_shape,
139 histogram_elements as usize,
140 DType::F32,
141 )?;
142 let output = allocate_like(input, "image::equalize_hist")?;
143 let clear_buffers = [BufferBinding::write(histogram.storage())];
144 let clear_push = [PushConstant::U32(histogram_elements)];
145 let count_buffers = [
146 BufferBinding::read(input.storage()),
147 BufferBinding::read_write(histogram.storage()),
148 ];
149 let count_push = [
150 PushConstant::U32(batch),
151 PushConstant::U32(channels),
152 PushConstant::U32(image_height),
153 PushConstant::U32(image_width),
154 ];
155 let lut_buffers = [
156 BufferBinding::read(histogram.storage()),
157 BufferBinding::write(lut.storage()),
158 ];
159 let lut_push = [PushConstant::U32(histogram_elements)];
160 let remap_buffers = [
161 BufferBinding::read(input.storage()),
162 BufferBinding::read(lut.storage()),
163 BufferBinding::write(output.storage()),
164 ];
165 let remap_push = [
166 PushConstant::U32(batch),
167 PushConstant::U32(channels),
168 PushConstant::U32(image_height),
169 PushConstant::U32(image_width),
170 ];
171 let dispatches = [
172 ComputeDispatch {
173 kernel: KernelId::ImageEqualizeHistClearU32,
174 buffers: &clear_buffers,
175 push_constants: &clear_push,
176 workgroups: KernelId::ImageEqualizeHistClearU32.linear_workgroups(histogram_elements),
177 indirect: None,
178 },
179 ComputeDispatch {
180 kernel: KernelId::ImageEqualizeHistF32,
181 buffers: &count_buffers,
182 push_constants: &count_push,
183 workgroups: [
184 image_width.div_ceil(16),
185 image_height.div_ceil(16),
186 batch * channels,
187 ],
188 indirect: None,
189 },
190 ComputeDispatch {
191 kernel: KernelId::ImageEqualizeHistLutF32,
192 buffers: &lut_buffers,
193 push_constants: &lut_push,
194 workgroups: KernelId::ImageEqualizeHistLutF32.linear_workgroups(histogram_elements),
195 indirect: None,
196 },
197 ComputeDispatch {
198 kernel: KernelId::ImageEqualizeHistRemapF32,
199 buffers: &remap_buffers,
200 push_constants: &remap_push,
201 workgroups: [
202 image_width.div_ceil(16),
203 image_height.div_ceil(16),
204 batch * channels,
205 ],
206 indirect: None,
207 },
208 ];
209 input.runtime().record_image_split_semantic(
210 &dispatches,
211 ImageSemanticDispatch {
212 contract: crate::core::operation::image::EQUALIZE_HIST,
213 inputs: &[ImageSemanticInput::Image(input)],
214 outputs: &[ImageSemanticOutput::Image(&output)],
215 attributes: &[],
216 },
217 )?;
218 Ok(output)
219}
220
221#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub enum HistogramComparison {
224 #[default]
226 Correlation,
227 ChiSquare,
229 Intersection,
231 Bhattacharyya,
233}
234
235impl HistogramComparison {
236 pub(super) const fn token(self) -> &'static str {
237 match self {
238 Self::Correlation => "correlation",
239 Self::ChiSquare => "chi_square",
240 Self::Intersection => "intersection",
241 Self::Bhattacharyya => "bhattacharyya",
242 }
243 }
244
245 pub(super) const fn code(self) -> u32 {
246 match self {
247 Self::Correlation => 0,
248 Self::ChiSquare => 1,
249 Self::Intersection => 2,
250 Self::Bhattacharyya => 3,
251 }
252 }
253}
254
255pub fn compare_hist(
268 first: &Matrix,
269 second: &Matrix,
270 method: HistogramComparison,
271) -> Result<Matrix> {
272 if first.dtype() != DType::U32
273 || second.dtype() != DType::U32
274 || first.shape() != second.shape()
275 || !first.runtime().same_as(second.runtime())
276 {
277 return Err(Error::invalid_argument(
278 "image::compare_hist requires same-shape same-runtime U32 histograms",
279 ));
280 }
281 let shape = first.shape();
282 if shape.len() < 2 || shape.contains(&0) {
283 return Err(Error::invalid_argument(
284 "image::compare_hist requires nonempty matrices of rank at least two",
285 ));
286 }
287 let bin_count = u32::try_from(shape[shape.len() - 1])
288 .map_err(|_| Error::out_of_range("image::compare_hist bin count exceeds u32"))?;
289 let row_count = shape[..shape.len() - 1]
290 .iter()
291 .try_fold(1u32, |count, value| {
292 count.checked_mul(u32::try_from(*value).ok()?)
293 })
294 .ok_or_else(|| Error::out_of_range("image::compare_hist row count exceeds u32"))?;
295 let output = Matrix::allocate(
296 first.runtime(),
297 shape[..shape.len() - 1].to_vec(),
298 row_count as usize,
299 DType::F32,
300 )?;
301 first.runtime().record_image_semantic(
302 ComputeDispatch {
303 kernel: KernelId::ImageCompareHistU32,
304 buffers: &[
305 BufferBinding::read(first.storage()),
306 BufferBinding::read(second.storage()),
307 BufferBinding::write(output.storage()),
308 ],
309 push_constants: &[
310 PushConstant::U32(row_count),
311 PushConstant::U32(bin_count),
312 PushConstant::U32(method.code()),
313 ],
314 workgroups: KernelId::ImageCompareHistU32.linear_workgroups(row_count),
315 indirect: None,
316 },
317 ImageSemanticDispatch {
318 contract: crate::core::operation::image::COMPARE_HIST,
319 inputs: &[
320 ImageSemanticInput::Matrix(first),
321 ImageSemanticInput::Matrix(second),
322 ],
323 outputs: &[ImageSemanticOutput::Matrix(&output)],
324 attributes: &[enumeration("method", method.token())],
325 },
326 )?;
327 Ok(output)
328}
329
330#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
332pub enum AutoThreshold {
333 #[default]
335 Otsu,
336 Triangle,
338}
339
340impl AutoThreshold {
341 pub(super) const fn token(self) -> &'static str {
342 match self {
343 Self::Otsu => "otsu",
344 Self::Triangle => "triangle",
345 }
346 }
347
348 pub(super) const fn code(self) -> u32 {
349 match self {
350 Self::Otsu => 0,
351 Self::Triangle => 1,
352 }
353 }
354}
355
356pub fn threshold_auto(
370 input: &Image,
371 method: AutoThreshold,
372 max_value: f32,
373) -> Result<(Image, Matrix)> {
374 if !max_value.is_finite() {
375 return Err(Error::invalid_argument(
376 "image::threshold_auto requires a finite max_value",
377 ));
378 }
379 let (batch, channels, image_height, image_width) = image_extent(input, "image::threshold_auto")?;
380 let plane_count = batch
381 .checked_mul(channels)
382 .ok_or_else(|| Error::out_of_range("image::threshold_auto plane count exceeds u32"))?;
383 let histogram_elements = plane_count
384 .checked_mul(256)
385 .ok_or_else(|| Error::out_of_range("image::threshold_auto workspace exceeds u32"))?;
386 let runtime = input.runtime();
387 let mut histogram_shape = input.as_matrix().shape().to_vec();
388 histogram_shape.truncate(histogram_shape.len() - 2);
389 histogram_shape.push(256);
390 let histogram = Matrix::allocate(
391 runtime,
392 histogram_shape,
393 histogram_elements as usize,
394 DType::U32,
395 )?;
396 let thresholds_shape = input.as_matrix().shape()[..input.as_matrix().shape().len() - 2].to_vec();
397 let thresholds = Matrix::allocate(runtime, thresholds_shape, plane_count as usize, DType::F32)?;
398 let output = allocate_like(input, "image::threshold_auto")?;
399 let clear_buffers = [BufferBinding::write(histogram.storage())];
400 let clear_push = [PushConstant::U32(histogram_elements)];
401 let count_buffers = [
402 BufferBinding::read(input.storage()),
403 BufferBinding::read_write(histogram.storage()),
404 ];
405 let count_push = [
406 PushConstant::U32(batch),
407 PushConstant::U32(channels),
408 PushConstant::U32(image_height),
409 PushConstant::U32(image_width),
410 ];
411 let select_buffers = [
412 BufferBinding::read(histogram.storage()),
413 BufferBinding::write(thresholds.storage()),
414 ];
415 let select_push = [
416 PushConstant::U32(plane_count),
417 PushConstant::U32(method.code()),
418 ];
419 let apply_buffers = [
420 BufferBinding::read(input.storage()),
421 BufferBinding::read(thresholds.storage()),
422 BufferBinding::write(output.storage()),
423 ];
424 let apply_push = [
425 PushConstant::U32(batch),
426 PushConstant::U32(channels),
427 PushConstant::U32(image_height),
428 PushConstant::U32(image_width),
429 PushConstant::F32(max_value),
430 ];
431 let dispatches = [
432 ComputeDispatch {
433 kernel: KernelId::ImageThresholdAutoClearU32,
434 buffers: &clear_buffers,
435 push_constants: &clear_push,
436 workgroups: KernelId::ImageThresholdAutoClearU32.linear_workgroups(histogram_elements),
437 indirect: None,
438 },
439 ComputeDispatch {
440 kernel: KernelId::ImageThresholdAutoF32,
441 buffers: &count_buffers,
442 push_constants: &count_push,
443 workgroups: [
444 image_width.div_ceil(16),
445 image_height.div_ceil(16),
446 batch * channels,
447 ],
448 indirect: None,
449 },
450 ComputeDispatch {
451 kernel: KernelId::ImageThresholdAutoSelectU32,
452 buffers: &select_buffers,
453 push_constants: &select_push,
454 workgroups: KernelId::ImageThresholdAutoSelectU32.linear_workgroups(plane_count),
455 indirect: None,
456 },
457 ComputeDispatch {
458 kernel: KernelId::ImageThresholdAutoApplyF32,
459 buffers: &apply_buffers,
460 push_constants: &apply_push,
461 workgroups: [
462 image_width.div_ceil(16),
463 image_height.div_ceil(16),
464 batch * channels,
465 ],
466 indirect: None,
467 },
468 ];
469 let attributes = [
470 enumeration("method", method.token()),
471 float("max_value", max_value),
472 ];
473 input.runtime().record_image_split_semantic(
474 &dispatches,
475 ImageSemanticDispatch {
476 contract: crate::core::operation::image::THRESHOLD_AUTO,
477 inputs: &[ImageSemanticInput::Image(input)],
478 outputs: &[
479 ImageSemanticOutput::Image(&output),
480 ImageSemanticOutput::Matrix(&thresholds),
481 ],
482 attributes: &attributes,
483 },
484 )?;
485 Ok((output, thresholds))
486}
487
488pub fn integral(input: &Image) -> Result<Matrix> {
502 let (batch, channels, image_height, image_width) = image_extent(input, "image::integral")?;
503 let plane_count = batch
504 .checked_mul(channels)
505 .ok_or_else(|| Error::out_of_range("image::integral plane count exceeds u32"))?;
506 let mut shape = input.as_matrix().shape().to_vec();
507 let rank = shape.len();
508 shape[rank - 2] += 1;
509 shape[rank - 1] += 1;
510 let elements = shape
511 .iter()
512 .try_fold(1u32, |count, value| {
513 count.checked_mul(u32::try_from(*value).ok()?)
514 })
515 .ok_or_else(|| Error::out_of_range("image::integral output size exceeds u32"))?;
516 let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
517 let row_buffers = [
518 BufferBinding::read(input.storage()),
519 BufferBinding::write(output.storage()),
520 ];
521 let row_push = [
522 PushConstant::U32(batch),
523 PushConstant::U32(channels),
524 PushConstant::U32(image_height),
525 PushConstant::U32(image_width),
526 ];
527 let col_buffers = [BufferBinding::read_write(output.storage())];
528 let col_push = [
529 PushConstant::U32(batch),
530 PushConstant::U32(channels),
531 PushConstant::U32(image_height),
532 PushConstant::U32(image_width),
533 ];
534 let dispatches = [
535 ComputeDispatch {
536 kernel: KernelId::ImageIntegralRowsF32,
537 buffers: &row_buffers,
538 push_constants: &row_push,
539 workgroups: KernelId::ImageIntegralRowsF32.linear_workgroups(plane_count * image_height),
540 indirect: None,
541 },
542 ComputeDispatch {
543 kernel: KernelId::ImageIntegralColsF32,
544 buffers: &col_buffers,
545 push_constants: &col_push,
546 workgroups: KernelId::ImageIntegralColsF32.linear_workgroups(plane_count * (image_width + 1)),
547 indirect: None,
548 },
549 ];
550 input.runtime().record_image_split_semantic(
551 &dispatches,
552 ImageSemanticDispatch {
553 contract: crate::core::operation::image::INTEGRAL,
554 inputs: &[ImageSemanticInput::Image(input)],
555 outputs: &[ImageSemanticOutput::Matrix(&output)],
556 attributes: &[],
557 },
558 )?;
559 Ok(output)
560}
561
562pub fn calc_back_project(
578 input: &Image,
579 histogram: &Matrix,
580 lower: f32,
581 upper: f32,
582) -> Result<Image> {
583 let (batch, channels, image_height, image_width) =
584 image_extent(input, "image::calc_back_project")?;
585 if histogram.dtype() != DType::U32 || histogram.shape().is_empty() {
586 return Err(Error::invalid_argument(
587 "image::calc_back_project requires a nonempty U32 histogram",
588 ));
589 }
590 let image_shape = input.as_matrix().shape();
591 let histogram_shape = histogram.shape();
592 if histogram_shape.len() != image_shape.len() - 1
593 || histogram_shape[..histogram_shape.len() - 1] != image_shape[..image_shape.len() - 2]
594 {
595 return Err(Error::invalid_argument(
596 "image::calc_back_project histogram leading shape must match the image planes",
597 ));
598 }
599 let bins = u32::try_from(histogram_shape[histogram_shape.len() - 1])
600 .map_err(|_| Error::out_of_range("image::calc_back_project bins exceed u32"))?;
601 if bins == 0 || bins > 256 {
602 return Err(Error::invalid_argument(
603 "image::calc_back_project histogram bins must be in 1..=256",
604 ));
605 }
606 if !lower.is_finite() || !upper.is_finite() || lower >= upper {
607 return Err(Error::invalid_argument(
608 "image::calc_back_project requires finite bounds with lower < upper",
609 ));
610 }
611 let output = allocate_like(input, "image::calc_back_project")?;
612 let attributes = [float("lower", lower), float("upper", upper)];
613 input.runtime().record_image_semantic(
614 ComputeDispatch {
615 kernel: KernelId::ImageCalcBackProjectF32,
616 buffers: &[
617 BufferBinding::read(input.storage()),
618 BufferBinding::read(histogram.storage()),
619 BufferBinding::write(output.storage()),
620 ],
621 push_constants: &[
622 PushConstant::U32(batch),
623 PushConstant::U32(channels),
624 PushConstant::U32(image_height),
625 PushConstant::U32(image_width),
626 PushConstant::U32(bins),
627 PushConstant::F32(lower),
628 PushConstant::F32(upper),
629 ],
630 workgroups: [
631 image_width.div_ceil(16),
632 image_height.div_ceil(16),
633 batch * channels,
634 ],
635 indirect: None,
636 },
637 ImageSemanticDispatch {
638 contract: crate::core::operation::image::CALC_BACK_PROJECT,
639 inputs: &[
640 ImageSemanticInput::Image(input),
641 ImageSemanticInput::Matrix(histogram),
642 ],
643 outputs: &[ImageSemanticOutput::Image(&output)],
644 attributes: &attributes,
645 },
646 )?;
647 Ok(output)
648}
649
650pub fn clahe(input: &Image, clip_limit: f32, tile_width: u32, tile_height: u32) -> Result<Image> {
664 let (batch, channels, image_height, image_width) = image_extent(input, "image::clahe")?;
665 if !clip_limit.is_finite() || clip_limit <= 0.0 {
666 return Err(Error::invalid_argument(
667 "image::clahe requires a finite positive clip_limit",
668 ));
669 }
670 if tile_width == 0 || tile_height == 0 {
671 return Err(Error::invalid_argument(
672 "image::clahe requires nonzero tile extents",
673 ));
674 }
675 let plane_count = batch
676 .checked_mul(channels)
677 .ok_or_else(|| Error::out_of_range("image::clahe plane count exceeds u32"))?;
678 let tiles_x = image_width.div_ceil(tile_width);
679 let tiles_y = image_height.div_ceil(tile_height);
680 let tile_count = plane_count
681 .checked_mul(tiles_x)
682 .and_then(|count| count.checked_mul(tiles_y))
683 .ok_or_else(|| Error::out_of_range("image::clahe tile count exceeds u32"))?;
684 let histogram_elements = tile_count
685 .checked_mul(256)
686 .ok_or_else(|| Error::out_of_range("image::clahe histogram size exceeds u32"))?;
687 let runtime = input.runtime();
688 let histogram = Matrix::allocate(
689 runtime,
690 vec![histogram_elements as usize],
691 histogram_elements as usize,
692 DType::U32,
693 )?;
694 let lut = Matrix::allocate(
695 runtime,
696 vec![histogram_elements as usize],
697 histogram_elements as usize,
698 DType::F32,
699 )?;
700 let output = allocate_like(input, "image::clahe")?;
701 let tile_area = tile_width as f32 * tile_height as f32;
702 let clear_buffers = [BufferBinding::write(histogram.storage())];
703 let clear_push = [PushConstant::U32(histogram_elements)];
704 let count_buffers = [
705 BufferBinding::read(input.storage()),
706 BufferBinding::read_write(histogram.storage()),
707 ];
708 let count_push = [
709 PushConstant::U32(batch),
710 PushConstant::U32(channels),
711 PushConstant::U32(image_height),
712 PushConstant::U32(image_width),
713 PushConstant::U32(tile_width),
714 PushConstant::U32(tile_height),
715 PushConstant::U32(tiles_x),
716 ];
717 let lut_buffers = [
718 BufferBinding::read(histogram.storage()),
719 BufferBinding::write(lut.storage()),
720 ];
721 let lut_push = [
722 PushConstant::U32(tile_count),
723 PushConstant::F32(clip_limit),
724 PushConstant::F32(tile_area),
725 ];
726 let remap_buffers = [
727 BufferBinding::read(input.storage()),
728 BufferBinding::read(lut.storage()),
729 BufferBinding::write(output.storage()),
730 ];
731 let remap_push = [
732 PushConstant::U32(batch),
733 PushConstant::U32(channels),
734 PushConstant::U32(image_height),
735 PushConstant::U32(image_width),
736 PushConstant::U32(tile_width),
737 PushConstant::U32(tile_height),
738 PushConstant::U32(tiles_x),
739 PushConstant::U32(tiles_y),
740 ];
741 let dispatches = [
742 ComputeDispatch {
743 kernel: KernelId::ImageClaheClearU32,
744 buffers: &clear_buffers,
745 push_constants: &clear_push,
746 workgroups: KernelId::ImageClaheClearU32.linear_workgroups(histogram_elements),
747 indirect: None,
748 },
749 ComputeDispatch {
750 kernel: KernelId::ImageClaheF32,
751 buffers: &count_buffers,
752 push_constants: &count_push,
753 workgroups: [
754 image_width.div_ceil(16),
755 image_height.div_ceil(16),
756 batch * channels,
757 ],
758 indirect: None,
759 },
760 ComputeDispatch {
761 kernel: KernelId::ImageClaheLutU32,
762 buffers: &lut_buffers,
763 push_constants: &lut_push,
764 workgroups: KernelId::ImageClaheLutU32.linear_workgroups(tile_count),
765 indirect: None,
766 },
767 ComputeDispatch {
768 kernel: KernelId::ImageClaheRemapF32,
769 buffers: &remap_buffers,
770 push_constants: &remap_push,
771 workgroups: [
772 image_width.div_ceil(16),
773 image_height.div_ceil(16),
774 batch * channels,
775 ],
776 indirect: None,
777 },
778 ];
779 let attributes = [
780 float("clip_limit", clip_limit),
781 unsigned("tile_width", tile_width),
782 unsigned("tile_height", tile_height),
783 ];
784 input.runtime().record_image_split_semantic(
785 &dispatches,
786 ImageSemanticDispatch {
787 contract: crate::core::operation::image::CLAHE,
788 inputs: &[ImageSemanticInput::Image(input)],
789 outputs: &[ImageSemanticOutput::Image(&output)],
790 attributes: &attributes,
791 },
792 )?;
793 Ok(output)
794}
795
796pub fn accumulate(input: &Image, accumulator: &Image) -> Result<Image> {
806 let (batch, channels, image_height, image_width) =
807 validate_accumulation_pair(input, accumulator, "image::accumulate")?;
808 let output = allocate_like(input, "image::accumulate")?;
809 input.runtime().record_image_semantic(
810 ComputeDispatch {
811 kernel: KernelId::ImageAccumulateF32,
812 buffers: &[
813 BufferBinding::read(input.storage()),
814 BufferBinding::read(accumulator.storage()),
815 BufferBinding::write(output.storage()),
816 ],
817 push_constants: &[
818 PushConstant::U32(batch),
819 PushConstant::U32(channels),
820 PushConstant::U32(image_height),
821 PushConstant::U32(image_width),
822 ],
823 workgroups: [
824 image_width.div_ceil(16),
825 image_height.div_ceil(16),
826 batch * channels,
827 ],
828 indirect: None,
829 },
830 ImageSemanticDispatch {
831 contract: crate::core::operation::image::ACCUMULATE,
832 inputs: &[
833 ImageSemanticInput::Image(input),
834 ImageSemanticInput::Image(accumulator),
835 ],
836 outputs: &[ImageSemanticOutput::Image(&output)],
837 attributes: &[],
838 },
839 )?;
840 Ok(output)
841}
842
843pub fn accumulate_weighted(input: &Image, accumulator: &Image, alpha: f32) -> Result<Image> {
853 let (batch, channels, image_height, image_width) =
854 validate_accumulation_pair(input, accumulator, "image::accumulate_weighted")?;
855 if !alpha.is_finite() {
856 return Err(Error::invalid_argument(
857 "image::accumulate_weighted requires a finite alpha",
858 ));
859 }
860 let output = allocate_like(input, "image::accumulate_weighted")?;
861 let attributes = [float("alpha", alpha)];
862 input.runtime().record_image_semantic(
863 ComputeDispatch {
864 kernel: KernelId::ImageAccumulateWeightedF32,
865 buffers: &[
866 BufferBinding::read(input.storage()),
867 BufferBinding::read(accumulator.storage()),
868 BufferBinding::write(output.storage()),
869 ],
870 push_constants: &[
871 PushConstant::U32(batch),
872 PushConstant::U32(channels),
873 PushConstant::U32(image_height),
874 PushConstant::U32(image_width),
875 PushConstant::F32(alpha),
876 ],
877 workgroups: [
878 image_width.div_ceil(16),
879 image_height.div_ceil(16),
880 batch * channels,
881 ],
882 indirect: None,
883 },
884 ImageSemanticDispatch {
885 contract: crate::core::operation::image::ACCUMULATE_WEIGHTED,
886 inputs: &[
887 ImageSemanticInput::Image(input),
888 ImageSemanticInput::Image(accumulator),
889 ],
890 outputs: &[ImageSemanticOutput::Image(&output)],
891 attributes: &attributes,
892 },
893 )?;
894 Ok(output)
895}
896
897pub fn moments(input: &Image) -> Result<Matrix> {
908 let (batch, channels, image_height, image_width) = image_extent(input, "image::moments")?;
909 let plane_count = batch
910 .checked_mul(channels)
911 .ok_or_else(|| Error::out_of_range("image::moments plane count exceeds u32"))?;
912 let mut shape = input.as_matrix().shape().to_vec();
913 shape.truncate(shape.len() - 2);
914 shape.push(10);
915 let output = Matrix::allocate(
916 input.runtime(),
917 shape,
918 plane_count
919 .checked_mul(10)
920 .ok_or_else(|| Error::out_of_range("image::moments output size exceeds u32"))? as usize,
921 DType::F32,
922 )?;
923 input.runtime().record_image_semantic(
924 ComputeDispatch {
925 kernel: KernelId::ImageMomentsF32,
926 buffers: &[
927 BufferBinding::read(input.storage()),
928 BufferBinding::write(output.storage()),
929 ],
930 push_constants: &[
931 PushConstant::U32(batch),
932 PushConstant::U32(channels),
933 PushConstant::U32(image_height),
934 PushConstant::U32(image_width),
935 ],
936 workgroups: KernelId::ImageMomentsF32.linear_workgroups(plane_count),
937 indirect: None,
938 },
939 ImageSemanticDispatch {
940 contract: crate::core::operation::image::MOMENTS,
941 inputs: &[ImageSemanticInput::Image(input)],
942 outputs: &[ImageSemanticOutput::Matrix(&output)],
943 attributes: &[],
944 },
945 )?;
946 Ok(output)
947}
948
949pub fn psnr(first: &Image, second: &Image, peak_value: f32) -> Result<Matrix> {
961 let (batch, channels, image_height, image_width) =
962 validate_accumulation_pair(first, second, "image::psnr")?;
963 if !peak_value.is_finite() || peak_value <= 0.0 {
964 return Err(Error::invalid_argument(
965 "image::psnr requires a finite positive peak_value",
966 ));
967 }
968 let plane_count = batch
969 .checked_mul(channels)
970 .ok_or_else(|| Error::out_of_range("image::psnr plane count exceeds u32"))?;
971 let mut shape = first.as_matrix().shape().to_vec();
972 shape.truncate(shape.len() - 2);
973 let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
974 let attributes = [float("peak_value", peak_value)];
975 first.runtime().record_image_semantic(
976 ComputeDispatch {
977 kernel: KernelId::ImagePsnrF32,
978 buffers: &[
979 BufferBinding::read(first.storage()),
980 BufferBinding::read(second.storage()),
981 BufferBinding::write(output.storage()),
982 ],
983 push_constants: &[
984 PushConstant::U32(batch),
985 PushConstant::U32(channels),
986 PushConstant::U32(image_height),
987 PushConstant::U32(image_width),
988 PushConstant::F32(peak_value),
989 ],
990 workgroups: KernelId::ImagePsnrF32.linear_workgroups(plane_count),
991 indirect: None,
992 },
993 ImageSemanticDispatch {
994 contract: crate::core::operation::image::PSNR,
995 inputs: &[
996 ImageSemanticInput::Image(first),
997 ImageSemanticInput::Image(second),
998 ],
999 outputs: &[ImageSemanticOutput::Matrix(&output)],
1000 attributes: &attributes,
1001 },
1002 )?;
1003 Ok(output)
1004}
1005
1006pub fn ssim(first: &Image, second: &Image) -> Result<Matrix> {
1018 let (batch, channels, image_height, image_width) =
1019 validate_accumulation_pair(first, second, "image::ssim")?;
1020 let plane_count = batch
1021 .checked_mul(channels)
1022 .ok_or_else(|| Error::out_of_range("image::ssim plane count exceeds u32"))?;
1023 let mut shape = first.as_matrix().shape().to_vec();
1024 shape.truncate(shape.len() - 2);
1025 let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
1026 first.runtime().record_image_semantic(
1027 ComputeDispatch {
1028 kernel: KernelId::ImageSsimF32,
1029 buffers: &[
1030 BufferBinding::read(first.storage()),
1031 BufferBinding::read(second.storage()),
1032 BufferBinding::write(output.storage()),
1033 ],
1034 push_constants: &[
1035 PushConstant::U32(batch),
1036 PushConstant::U32(channels),
1037 PushConstant::U32(image_height),
1038 PushConstant::U32(image_width),
1039 ],
1040 workgroups: KernelId::ImageSsimF32.linear_workgroups(plane_count),
1041 indirect: None,
1042 },
1043 ImageSemanticDispatch {
1044 contract: crate::core::operation::image::SSIM,
1045 inputs: &[
1046 ImageSemanticInput::Image(first),
1047 ImageSemanticInput::Image(second),
1048 ],
1049 outputs: &[ImageSemanticOutput::Matrix(&output)],
1050 attributes: &[],
1051 },
1052 )?;
1053 Ok(output)
1054}
1055
1056#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1058pub enum MatchTemplate {
1059 #[default]
1061 Sqdiff,
1062 SqdiffNormed,
1064 Ccorr,
1066 CcorrNormed,
1068 Ccoeff,
1070 CcoeffNormed,
1072}
1073
1074impl MatchTemplate {
1075 pub(super) const fn token(self) -> &'static str {
1076 match self {
1077 Self::Sqdiff => "sqdiff",
1078 Self::SqdiffNormed => "sqdiff_normed",
1079 Self::Ccorr => "ccorr",
1080 Self::CcorrNormed => "ccorr_normed",
1081 Self::Ccoeff => "ccoeff",
1082 Self::CcoeffNormed => "ccoeff_normed",
1083 }
1084 }
1085
1086 pub(super) const fn code(self) -> u32 {
1087 match self {
1088 Self::Sqdiff => 0,
1089 Self::SqdiffNormed => 1,
1090 Self::Ccorr => 2,
1091 Self::CcorrNormed => 3,
1092 Self::Ccoeff => 4,
1093 Self::CcoeffNormed => 5,
1094 }
1095 }
1096}
1097
1098pub fn match_template(input: &Image, template: &Image, method: MatchTemplate) -> Result<Matrix> {
1111 let (batch, channels, image_height, image_width) = image_extent(input, "image::match_template")?;
1112 if template.dtype() != DType::F32
1113 || !matches!(template.layout(), ImageLayout::Nchw | ImageLayout::Chw)
1114 || template.batch_size() != 1
1115 || template.channels() != input.channels()
1116 {
1117 return Err(Error::invalid_argument(
1118 "image::match_template requires a single-plane FP32 template with matching channels",
1119 ));
1120 }
1121 let template_height = u32::try_from(template.height())
1122 .map_err(|_| Error::out_of_range("image::match_template template height exceeds u32"))?;
1123 let template_width = u32::try_from(template.width())
1124 .map_err(|_| Error::out_of_range("image::match_template template width exceeds u32"))?;
1125 if template_height == 0
1126 || template_width == 0
1127 || template_height > image_height
1128 || template_width > image_width
1129 {
1130 return Err(Error::invalid_argument(
1131 "image::match_template requires a nonempty template no larger than the image planes",
1132 ));
1133 }
1134 let output_height = image_height - template_height + 1;
1135 let output_width = image_width - template_width + 1;
1136 let mut shape = input.as_matrix().shape().to_vec();
1137 let rank = shape.len();
1138 shape[rank - 2] = output_height as usize;
1139 shape[rank - 1] = output_width as usize;
1140 let elements = shape
1141 .iter()
1142 .try_fold(1u32, |count, value| {
1143 count.checked_mul(u32::try_from(*value).ok()?)
1144 })
1145 .ok_or_else(|| Error::out_of_range("image::match_template output size exceeds u32"))?;
1146 let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
1147 let attributes = [enumeration("method", method.token())];
1148 input.runtime().record_image_semantic(
1149 ComputeDispatch {
1150 kernel: KernelId::ImageMatchTemplateF32,
1151 buffers: &[
1152 BufferBinding::read(input.storage()),
1153 BufferBinding::read(template.storage()),
1154 BufferBinding::write(output.storage()),
1155 ],
1156 push_constants: &[
1157 PushConstant::U32(batch),
1158 PushConstant::U32(channels),
1159 PushConstant::U32(image_height),
1160 PushConstant::U32(image_width),
1161 PushConstant::U32(template_height),
1162 PushConstant::U32(template_width),
1163 PushConstant::U32(output_height),
1164 PushConstant::U32(output_width),
1165 PushConstant::U32(method.code()),
1166 ],
1167 workgroups: [
1168 output_width.div_ceil(16),
1169 output_height.div_ceil(16),
1170 batch * channels,
1171 ],
1172 indirect: None,
1173 },
1174 ImageSemanticDispatch {
1175 contract: crate::core::operation::image::MATCH_TEMPLATE,
1176 inputs: &[
1177 ImageSemanticInput::Image(input),
1178 ImageSemanticInput::Image(template),
1179 ],
1180 outputs: &[ImageSemanticOutput::Matrix(&output)],
1181 attributes: &attributes,
1182 },
1183 )?;
1184 Ok(output)
1185}
1186
1187#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1189pub enum Connectivity {
1190 Four,
1192 #[default]
1194 Eight,
1195}
1196
1197impl Connectivity {
1198 pub(super) const fn token(self) -> &'static str {
1199 match self {
1200 Self::Four => "four",
1201 Self::Eight => "eight",
1202 }
1203 }
1204
1205 pub(super) const fn code(self) -> u32 {
1206 match self {
1207 Self::Four => 4,
1208 Self::Eight => 8,
1209 }
1210 }
1211}
1212
1213pub fn connected_components(
1228 input: &Image,
1229 threshold: f32,
1230 connectivity: Connectivity,
1231 propagation_passes: u32,
1232) -> Result<Matrix> {
1233 if !threshold.is_finite() {
1234 return Err(Error::invalid_argument(
1235 "image::connected_components threshold must be finite",
1236 ));
1237 }
1238 let contract = crate::core::operation::image::CONNECTED_COMPONENTS;
1239 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1240 let plane_count = batch
1241 .checked_mul(channels)
1242 .ok_or_else(|| Error::out_of_range("image::connected_components plane count exceeds u32"))?;
1243 let plane_elements = plane_count
1244 .checked_mul(image_height)
1245 .and_then(|count| count.checked_mul(image_width))
1246 .ok_or_else(|| Error::out_of_range("image::connected_components label count exceeds u32"))?;
1247 let relax_passes = if propagation_passes == 0 {
1248 image_height.checked_add(image_width).ok_or_else(|| {
1249 Error::out_of_range("image::connected_components propagation bound exceeds u32")
1250 })?
1251 } else {
1252 propagation_passes
1253 };
1254 let labels = Matrix::allocate(
1255 input.runtime(),
1256 vec![
1257 plane_count as usize,
1258 image_height as usize,
1259 image_width as usize,
1260 ],
1261 plane_elements as usize,
1262 DType::U32,
1263 )?;
1264 let mut workgroups =
1265 KernelId::ImageConnectedComponentsInitU32.output_workgroups(image_width, image_height);
1266 workgroups[2] = plane_count;
1267 let init_buffers = [
1268 BufferBinding::read(input.storage()),
1269 BufferBinding::write(labels.storage()),
1270 ];
1271 let init_push = [
1272 PushConstant::U32(batch),
1273 PushConstant::U32(channels),
1274 PushConstant::U32(image_height),
1275 PushConstant::U32(image_width),
1276 PushConstant::F32(threshold),
1277 ];
1278 let relax_buffers = [BufferBinding::read_write(labels.storage())];
1279 let relax_push = [
1280 PushConstant::U32(batch),
1281 PushConstant::U32(channels),
1282 PushConstant::U32(image_height),
1283 PushConstant::U32(image_width),
1284 PushConstant::U32(connectivity.code()),
1285 ];
1286 let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
1287 dispatches.push(ComputeDispatch {
1288 kernel: KernelId::ImageConnectedComponentsInitU32,
1289 buffers: &init_buffers,
1290 push_constants: &init_push,
1291 workgroups,
1292 indirect: None,
1293 });
1294 for _ in 0..relax_passes {
1295 dispatches.push(ComputeDispatch {
1296 kernel: KernelId::ImageConnectedComponentsRelaxU32,
1297 buffers: &relax_buffers,
1298 push_constants: &relax_push,
1299 workgroups,
1300 indirect: None,
1301 });
1302 }
1303 let attributes = [
1304 float("threshold", threshold),
1305 enumeration("connectivity", connectivity.token()),
1306 unsigned("propagation_passes", propagation_passes),
1307 ];
1308 input.runtime().record_image_split_semantic(
1309 &dispatches,
1310 ImageSemanticDispatch {
1311 contract,
1312 inputs: &[ImageSemanticInput::Image(input)],
1313 outputs: &[ImageSemanticOutput::Matrix(&labels)],
1314 attributes: &attributes,
1315 },
1316 )?;
1317 Ok(labels)
1318}
1319
1320#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1322pub enum DistanceType {
1323 L1,
1325 #[default]
1327 L2,
1328}
1329
1330impl DistanceType {
1331 pub(super) const fn token(self) -> &'static str {
1332 match self {
1333 Self::L1 => "l1",
1334 Self::L2 => "l2",
1335 }
1336 }
1337
1338 pub(super) const fn code(self) -> u32 {
1339 match self {
1340 Self::L1 => 1,
1341 Self::L2 => 2,
1342 }
1343 }
1344}
1345
1346pub fn distance_transform(
1362 input: &Image,
1363 threshold: f32,
1364 distance: DistanceType,
1365 propagation_passes: u32,
1366) -> Result<Matrix> {
1367 if !threshold.is_finite() {
1368 return Err(Error::invalid_argument(
1369 "image::distance_transform threshold must be finite",
1370 ));
1371 }
1372 let contract = crate::core::operation::image::DISTANCE_TRANSFORM;
1373 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1374 let plane_count = batch
1375 .checked_mul(channels)
1376 .ok_or_else(|| Error::out_of_range("image::distance_transform plane count exceeds u32"))?;
1377 let plane_elements = plane_count
1378 .checked_mul(image_height)
1379 .and_then(|count| count.checked_mul(image_width))
1380 .ok_or_else(|| Error::out_of_range("image::distance_transform element count exceeds u32"))?;
1381 let relax_passes = if propagation_passes == 0 {
1382 image_height.checked_add(image_width).ok_or_else(|| {
1383 Error::out_of_range("image::distance_transform propagation bound exceeds u32")
1384 })?
1385 } else {
1386 propagation_passes
1387 };
1388 let distances = Matrix::allocate(
1389 input.runtime(),
1390 vec![
1391 plane_count as usize,
1392 image_height as usize,
1393 image_width as usize,
1394 ],
1395 plane_elements as usize,
1396 DType::F32,
1397 )?;
1398 let mut workgroups =
1399 KernelId::ImageDistanceTransformInitF32.output_workgroups(image_width, image_height);
1400 workgroups[2] = plane_count;
1401 let init_buffers = [
1402 BufferBinding::read(input.storage()),
1403 BufferBinding::write(distances.storage()),
1404 ];
1405 let init_push = [
1406 PushConstant::U32(batch),
1407 PushConstant::U32(channels),
1408 PushConstant::U32(image_height),
1409 PushConstant::U32(image_width),
1410 PushConstant::F32(threshold),
1411 ];
1412 let relax_buffers = [BufferBinding::read_write(distances.storage())];
1413 let relax_push = [
1414 PushConstant::U32(batch),
1415 PushConstant::U32(channels),
1416 PushConstant::U32(image_height),
1417 PushConstant::U32(image_width),
1418 PushConstant::U32(distance.code()),
1419 ];
1420 let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
1421 dispatches.push(ComputeDispatch {
1422 kernel: KernelId::ImageDistanceTransformInitF32,
1423 buffers: &init_buffers,
1424 push_constants: &init_push,
1425 workgroups,
1426 indirect: None,
1427 });
1428 for _ in 0..relax_passes {
1429 dispatches.push(ComputeDispatch {
1430 kernel: KernelId::ImageDistanceTransformRelaxF32,
1431 buffers: &relax_buffers,
1432 push_constants: &relax_push,
1433 workgroups,
1434 indirect: None,
1435 });
1436 }
1437 let attributes = [
1438 float("threshold", threshold),
1439 enumeration("distance", distance.token()),
1440 unsigned("propagation_passes", propagation_passes),
1441 ];
1442 input.runtime().record_image_split_semantic(
1443 &dispatches,
1444 ImageSemanticDispatch {
1445 contract,
1446 inputs: &[ImageSemanticInput::Image(input)],
1447 outputs: &[ImageSemanticOutput::Matrix(&distances)],
1448 attributes: &attributes,
1449 },
1450 )?;
1451 Ok(distances)
1452}
1453
1454pub fn hough_lines(
1471 input: &Image,
1472 edge_threshold: f32,
1473 rho_step: f32,
1474 theta_step: f32,
1475 threshold: u32,
1476 max_lines: u32,
1477) -> Result<Matrix> {
1478 if !edge_threshold.is_finite()
1479 || !rho_step.is_finite()
1480 || !theta_step.is_finite()
1481 || rho_step <= 0.0
1482 || theta_step <= 0.0
1483 || theta_step > 180.0
1484 {
1485 return Err(Error::invalid_argument(
1486 "image::hough_lines steps must be finite, positive, and theta_step <= 180",
1487 ));
1488 }
1489 if max_lines == 0 {
1490 return Err(Error::invalid_argument(
1491 "image::hough_lines max_lines must be nonzero",
1492 ));
1493 }
1494 let contract = crate::core::operation::image::HOUGH_LINES;
1495 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1496 let plane_count = batch
1497 .checked_mul(channels)
1498 .ok_or_else(|| Error::out_of_range("image::hough_lines plane count exceeds u32"))?;
1499 let num_theta = (180.0f32 / theta_step).ceil() as u32;
1500 let span = (image_width as f64).hypot(image_height as f64).ceil();
1501 let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
1502 let bins = num_theta
1503 .checked_mul(num_rho)
1504 .ok_or_else(|| Error::out_of_range("image::hough_lines accumulator size exceeds u32"))?;
1505 let acc_stride = bins
1506 .checked_add(1)
1507 .ok_or_else(|| Error::out_of_range("image::hough_lines accumulator stride exceeds u32"))?;
1508 let acc_elements = plane_count
1509 .checked_mul(acc_stride)
1510 .ok_or_else(|| Error::out_of_range("image::hough_lines accumulator elements exceed u32"))?;
1511 let line_elements = plane_count
1512 .checked_mul(max_lines)
1513 .and_then(|count| count.checked_mul(3))
1514 .ok_or_else(|| Error::out_of_range("image::hough_lines output elements exceed u32"))?;
1515 let acc_cells = plane_count
1516 .checked_mul(bins)
1517 .ok_or_else(|| Error::out_of_range("image::hough_lines accumulator cells exceed u32"))?;
1518 let accumulator = Matrix::allocate(
1519 input.runtime(),
1520 vec![plane_count as usize, acc_stride as usize],
1521 acc_elements as usize,
1522 DType::U32,
1523 )?;
1524 let lines = Matrix::allocate(
1525 input.runtime(),
1526 vec![plane_count as usize, max_lines as usize, 3],
1527 line_elements as usize,
1528 DType::F32,
1529 )?;
1530 let mut workgroups =
1531 KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
1532 workgroups[2] = plane_count;
1533 let rho_span = span as f32;
1534 let clear_buffers = [
1535 BufferBinding::write(accumulator.storage()),
1536 BufferBinding::write(lines.storage()),
1537 ];
1538 let clear_push = [
1539 PushConstant::U32(acc_elements),
1540 PushConstant::U32(line_elements),
1541 ];
1542 let accumulate_buffers = [
1543 BufferBinding::read(input.storage()),
1544 BufferBinding::read_write(accumulator.storage()),
1545 ];
1546 let accumulate_push = [
1547 PushConstant::U32(batch),
1548 PushConstant::U32(channels),
1549 PushConstant::U32(image_height),
1550 PushConstant::U32(image_width),
1551 PushConstant::F32(edge_threshold),
1552 PushConstant::F32(rho_step),
1553 PushConstant::F32(theta_step),
1554 PushConstant::U32(num_theta),
1555 PushConstant::U32(num_rho),
1556 PushConstant::F32(rho_span),
1557 ];
1558 let extract_buffers = [
1559 BufferBinding::read_write(accumulator.storage()),
1560 BufferBinding::write(lines.storage()),
1561 ];
1562 let extract_push = [
1563 PushConstant::U32(num_theta),
1564 PushConstant::U32(num_rho),
1565 PushConstant::U32(plane_count),
1566 PushConstant::U32(threshold),
1567 PushConstant::U32(max_lines),
1568 PushConstant::F32(rho_step),
1569 PushConstant::F32(theta_step),
1570 PushConstant::F32(rho_span),
1571 ];
1572 let dispatches = [
1573 ComputeDispatch {
1574 kernel: KernelId::ImageHoughLinesClearU32,
1575 buffers: &clear_buffers,
1576 push_constants: &clear_push,
1577 workgroups: KernelId::ImageHoughLinesClearU32.linear_workgroups(acc_elements + line_elements),
1578 indirect: None,
1579 },
1580 ComputeDispatch {
1581 kernel: KernelId::ImageHoughLinesAccumulateF32,
1582 buffers: &accumulate_buffers,
1583 push_constants: &accumulate_push,
1584 workgroups,
1585 indirect: None,
1586 },
1587 ComputeDispatch {
1588 kernel: KernelId::ImageHoughLinesExtractU32,
1589 buffers: &extract_buffers,
1590 push_constants: &extract_push,
1591 workgroups: KernelId::ImageHoughLinesExtractU32.linear_workgroups(acc_cells),
1592 indirect: None,
1593 },
1594 ];
1595 let attributes = [
1596 float("edge_threshold", edge_threshold),
1597 float("rho_step", rho_step),
1598 float("theta_step", theta_step),
1599 unsigned("threshold", threshold),
1600 unsigned("max_lines", max_lines),
1601 ];
1602 input.runtime().record_image_split_semantic(
1603 &dispatches,
1604 ImageSemanticDispatch {
1605 contract,
1606 inputs: &[ImageSemanticInput::Image(input)],
1607 outputs: &[ImageSemanticOutput::Matrix(&lines)],
1608 attributes: &attributes,
1609 },
1610 )?;
1611 Ok(lines)
1612}
1613
1614#[allow(clippy::too_many_arguments)]
1632pub fn hough_lines_p(
1633 input: &Image,
1634 edge_threshold: f32,
1635 rho_step: f32,
1636 theta_step: f32,
1637 threshold: u32,
1638 max_lines: u32,
1639 min_line_length: f32,
1640 max_line_gap: u32,
1641) -> Result<Matrix> {
1642 if !edge_threshold.is_finite()
1643 || !rho_step.is_finite()
1644 || !theta_step.is_finite()
1645 || !min_line_length.is_finite()
1646 || rho_step <= 0.0
1647 || theta_step <= 0.0
1648 || theta_step > 180.0
1649 || min_line_length < 0.0
1650 {
1651 return Err(Error::invalid_argument(
1652 "image::hough_lines_p steps must be finite/positive, theta_step <= 180, min_line_length >= 0",
1653 ));
1654 }
1655 if max_lines == 0 {
1656 return Err(Error::invalid_argument(
1657 "image::hough_lines_p max_lines must be nonzero",
1658 ));
1659 }
1660 let contract = crate::core::operation::image::HOUGH_LINES_P;
1661 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1662 let plane_count = batch
1663 .checked_mul(channels)
1664 .ok_or_else(|| Error::out_of_range("image::hough_lines_p plane count exceeds u32"))?;
1665 let num_theta = (180.0f32 / theta_step).ceil() as u32;
1666 let span = (image_width as f64).hypot(image_height as f64).ceil();
1667 let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
1668 let bins = num_theta
1669 .checked_mul(num_rho)
1670 .ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator size exceeds u32"))?;
1671 let acc_stride = bins
1672 .checked_add(1)
1673 .ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator stride exceeds u32"))?;
1674 let acc_elements = plane_count
1675 .checked_mul(acc_stride)
1676 .ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator elements exceed u32"))?;
1677 let acc_cells = plane_count
1678 .checked_mul(bins)
1679 .ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator cells exceed u32"))?;
1680 let line_elements = plane_count
1681 .checked_mul(max_lines)
1682 .and_then(|count| count.checked_mul(3))
1683 .ok_or_else(|| Error::out_of_range("image::hough_lines_p line elements exceed u32"))?;
1684 let segment_elements = plane_count
1685 .checked_mul(max_lines)
1686 .and_then(|count| count.checked_mul(4))
1687 .ok_or_else(|| Error::out_of_range("image::hough_lines_p segment elements exceed u32"))?;
1688 let line_slots = plane_count
1689 .checked_mul(max_lines)
1690 .ok_or_else(|| Error::out_of_range("image::hough_lines_p line slots exceed u32"))?;
1691 let accumulator = Matrix::allocate(
1692 input.runtime(),
1693 vec![plane_count as usize, acc_stride as usize],
1694 acc_elements as usize,
1695 DType::U32,
1696 )?;
1697 let lines = Matrix::allocate(
1698 input.runtime(),
1699 vec![plane_count as usize, max_lines as usize, 3],
1700 line_elements as usize,
1701 DType::F32,
1702 )?;
1703 let segments = Matrix::allocate(
1704 input.runtime(),
1705 vec![plane_count as usize, max_lines as usize, 4],
1706 segment_elements as usize,
1707 DType::F32,
1708 )?;
1709 let mut workgroups =
1710 KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
1711 workgroups[2] = plane_count;
1712 let rho_span = span as f32;
1713 let clear_buffers = [
1714 BufferBinding::write(accumulator.storage()),
1715 BufferBinding::write(lines.storage()),
1716 ];
1717 let clear_push = [
1718 PushConstant::U32(acc_elements),
1719 PushConstant::U32(line_elements),
1720 ];
1721 let accumulate_buffers = [
1722 BufferBinding::read(input.storage()),
1723 BufferBinding::read_write(accumulator.storage()),
1724 ];
1725 let accumulate_push = [
1726 PushConstant::U32(batch),
1727 PushConstant::U32(channels),
1728 PushConstant::U32(image_height),
1729 PushConstant::U32(image_width),
1730 PushConstant::F32(edge_threshold),
1731 PushConstant::F32(rho_step),
1732 PushConstant::F32(theta_step),
1733 PushConstant::U32(num_theta),
1734 PushConstant::U32(num_rho),
1735 PushConstant::F32(rho_span),
1736 ];
1737 let extract_buffers = [
1738 BufferBinding::read_write(accumulator.storage()),
1739 BufferBinding::write(lines.storage()),
1740 ];
1741 let extract_push = [
1742 PushConstant::U32(num_theta),
1743 PushConstant::U32(num_rho),
1744 PushConstant::U32(plane_count),
1745 PushConstant::U32(threshold),
1746 PushConstant::U32(max_lines),
1747 PushConstant::F32(rho_step),
1748 PushConstant::F32(theta_step),
1749 PushConstant::F32(rho_span),
1750 ];
1751 let probe_buffers = [
1752 BufferBinding::read(input.storage()),
1753 BufferBinding::read(lines.storage()),
1754 BufferBinding::write(segments.storage()),
1755 ];
1756 let probe_push = [
1757 PushConstant::U32(plane_count),
1758 PushConstant::U32(max_lines),
1759 PushConstant::U32(image_height),
1760 PushConstant::U32(image_width),
1761 PushConstant::F32(edge_threshold),
1762 PushConstant::F32(min_line_length),
1763 PushConstant::U32(max_line_gap),
1764 ];
1765 let dispatches = [
1766 ComputeDispatch {
1767 kernel: KernelId::ImageHoughLinesPClearU32,
1768 buffers: &clear_buffers,
1769 push_constants: &clear_push,
1770 workgroups: KernelId::ImageHoughLinesPClearU32
1771 .linear_workgroups(acc_elements + line_elements),
1772 indirect: None,
1773 },
1774 ComputeDispatch {
1775 kernel: KernelId::ImageHoughLinesPAccumulateF32,
1776 buffers: &accumulate_buffers,
1777 push_constants: &accumulate_push,
1778 workgroups,
1779 indirect: None,
1780 },
1781 ComputeDispatch {
1782 kernel: KernelId::ImageHoughLinesPExtractU32,
1783 buffers: &extract_buffers,
1784 push_constants: &extract_push,
1785 workgroups: KernelId::ImageHoughLinesPExtractU32.linear_workgroups(acc_cells),
1786 indirect: None,
1787 },
1788 ComputeDispatch {
1789 kernel: KernelId::ImageHoughLinesProbeF32,
1790 buffers: &probe_buffers,
1791 push_constants: &probe_push,
1792 workgroups: KernelId::ImageHoughLinesProbeF32.linear_workgroups(line_slots),
1793 indirect: None,
1794 },
1795 ];
1796 let attributes = [
1797 float("edge_threshold", edge_threshold),
1798 float("rho_step", rho_step),
1799 float("theta_step", theta_step),
1800 unsigned("threshold", threshold),
1801 unsigned("max_lines", max_lines),
1802 float("min_line_length", min_line_length),
1803 unsigned("max_line_gap", max_line_gap),
1804 ];
1805 input.runtime().record_image_split_semantic(
1806 &dispatches,
1807 ImageSemanticDispatch {
1808 contract,
1809 inputs: &[ImageSemanticInput::Image(input)],
1810 outputs: &[ImageSemanticOutput::Matrix(&segments)],
1811 attributes: &attributes,
1812 },
1813 )?;
1814 Ok(segments)
1815}
1816
1817pub fn find_contours(
1838 input: &Image,
1839 threshold: f32,
1840 connectivity: Connectivity,
1841 max_contours: u32,
1842 max_points: u32,
1843 propagation_passes: u32,
1844) -> Result<(Matrix, Matrix)> {
1845 if !threshold.is_finite() {
1846 return Err(Error::invalid_argument(
1847 "image::find_contours threshold must be finite",
1848 ));
1849 }
1850 if max_contours == 0 {
1851 return Err(Error::invalid_argument(
1852 "image::find_contours max_contours must be nonzero",
1853 ));
1854 }
1855 let contract = crate::core::operation::image::FIND_CONTOURS;
1856 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
1857 let plane_count = batch
1858 .checked_mul(channels)
1859 .ok_or_else(|| Error::out_of_range("image::find_contours plane count exceeds u32"))?;
1860 let plane_elements = image_height
1861 .checked_mul(image_width)
1862 .ok_or_else(|| Error::out_of_range("image::find_contours plane size exceeds u32"))?;
1863 let label_elements = plane_count
1864 .checked_mul(plane_elements)
1865 .ok_or_else(|| Error::out_of_range("image::find_contours label count exceeds u32"))?;
1866 let relax_passes = if propagation_passes == 0 {
1867 image_height
1868 .checked_add(image_width)
1869 .ok_or_else(|| Error::out_of_range("image::find_contours propagation bound exceeds u32"))?
1870 } else {
1871 propagation_passes
1872 };
1873 let resolved_max_points = if max_points == 0 {
1874 image_height
1875 .checked_add(image_width)
1876 .and_then(|sum| sum.checked_mul(4))
1877 .ok_or_else(|| Error::out_of_range("image::find_contours point bound exceeds u32"))?
1878 } else {
1879 max_points
1880 };
1881 let labels = Matrix::allocate(
1882 input.runtime(),
1883 vec![
1884 plane_count as usize,
1885 image_height as usize,
1886 image_width as usize,
1887 ],
1888 label_elements as usize,
1889 DType::U32,
1890 )?;
1891 let seed_stride = max_contours
1892 .checked_add(1)
1893 .ok_or_else(|| Error::out_of_range("image::find_contours seed stride exceeds u32"))?;
1894 let seed_elements = plane_count
1895 .checked_mul(seed_stride)
1896 .ok_or_else(|| Error::out_of_range("image::find_contours seed count exceeds u32"))?;
1897 let point_elements = plane_count
1898 .checked_mul(max_contours)
1899 .and_then(|count| count.checked_mul(resolved_max_points))
1900 .and_then(|count| count.checked_mul(2))
1901 .ok_or_else(|| Error::out_of_range("image::find_contours point count exceeds u32"))?;
1902 let length_elements = plane_count
1903 .checked_mul(max_contours)
1904 .ok_or_else(|| Error::out_of_range("image::find_contours length count exceeds u32"))?;
1905 let seeds = Matrix::allocate(
1906 input.runtime(),
1907 vec![plane_count as usize, seed_stride as usize],
1908 seed_elements as usize,
1909 DType::U32,
1910 )?;
1911 let points = Matrix::allocate(
1912 input.runtime(),
1913 vec![
1914 plane_count as usize,
1915 max_contours as usize,
1916 resolved_max_points as usize,
1917 2,
1918 ],
1919 point_elements as usize,
1920 DType::F32,
1921 )?;
1922 let lengths = Matrix::allocate(
1923 input.runtime(),
1924 vec![plane_count as usize, max_contours as usize],
1925 length_elements as usize,
1926 DType::U32,
1927 )?;
1928 let clear_elements = seed_elements.max(point_elements).max(length_elements);
1929 let trace_slots = plane_count
1930 .checked_mul(max_contours)
1931 .ok_or_else(|| Error::out_of_range("image::find_contours slot count exceeds u32"))?;
1932 let mut workgroups =
1933 KernelId::ImageFindContoursInitU32.output_workgroups(image_width, image_height);
1934 workgroups[2] = plane_count;
1935 let clear_buffers = [
1936 BufferBinding::write(seeds.storage()),
1937 BufferBinding::write(points.storage()),
1938 BufferBinding::write(lengths.storage()),
1939 ];
1940 let clear_push = [
1941 PushConstant::U32(seed_elements),
1942 PushConstant::U32(point_elements),
1943 PushConstant::U32(length_elements),
1944 ];
1945 let init_buffers = [
1946 BufferBinding::read(input.storage()),
1947 BufferBinding::write(labels.storage()),
1948 ];
1949 let init_push = [
1950 PushConstant::U32(batch),
1951 PushConstant::U32(channels),
1952 PushConstant::U32(image_height),
1953 PushConstant::U32(image_width),
1954 PushConstant::F32(threshold),
1955 ];
1956 let relax_buffers = [BufferBinding::read_write(labels.storage())];
1957 let relax_push = [
1958 PushConstant::U32(batch),
1959 PushConstant::U32(channels),
1960 PushConstant::U32(image_height),
1961 PushConstant::U32(image_width),
1962 PushConstant::U32(connectivity.code()),
1963 ];
1964 let seeds_buffers = [
1965 BufferBinding::read(labels.storage()),
1966 BufferBinding::read_write(seeds.storage()),
1967 ];
1968 let seeds_push = [
1969 PushConstant::U32(batch),
1970 PushConstant::U32(channels),
1971 PushConstant::U32(image_height),
1972 PushConstant::U32(image_width),
1973 PushConstant::U32(max_contours),
1974 ];
1975 let trace_buffers = [
1976 BufferBinding::read(labels.storage()),
1977 BufferBinding::read(seeds.storage()),
1978 BufferBinding::write(points.storage()),
1979 BufferBinding::write(lengths.storage()),
1980 ];
1981 let trace_push = [
1982 PushConstant::U32(plane_count),
1983 PushConstant::U32(max_contours),
1984 PushConstant::U32(image_height),
1985 PushConstant::U32(image_width),
1986 PushConstant::U32(resolved_max_points),
1987 ];
1988 let mut dispatches = Vec::with_capacity(4 + relax_passes as usize);
1989 dispatches.push(ComputeDispatch {
1990 kernel: KernelId::ImageFindContoursClearU32,
1991 buffers: &clear_buffers,
1992 push_constants: &clear_push,
1993 workgroups: KernelId::ImageFindContoursClearU32.linear_workgroups(clear_elements),
1994 indirect: None,
1995 });
1996 dispatches.push(ComputeDispatch {
1997 kernel: KernelId::ImageFindContoursInitU32,
1998 buffers: &init_buffers,
1999 push_constants: &init_push,
2000 workgroups,
2001 indirect: None,
2002 });
2003 for _ in 0..relax_passes {
2004 dispatches.push(ComputeDispatch {
2005 kernel: KernelId::ImageFindContoursRelaxU32,
2006 buffers: &relax_buffers,
2007 push_constants: &relax_push,
2008 workgroups,
2009 indirect: None,
2010 });
2011 }
2012 dispatches.push(ComputeDispatch {
2013 kernel: KernelId::ImageFindContoursSeedsU32,
2014 buffers: &seeds_buffers,
2015 push_constants: &seeds_push,
2016 workgroups,
2017 indirect: None,
2018 });
2019 dispatches.push(ComputeDispatch {
2020 kernel: KernelId::ImageFindContoursTraceU32,
2021 buffers: &trace_buffers,
2022 push_constants: &trace_push,
2023 workgroups: KernelId::ImageFindContoursTraceU32.linear_workgroups(trace_slots),
2024 indirect: None,
2025 });
2026 let attributes = [
2027 float("threshold", threshold),
2028 enumeration("connectivity", connectivity.token()),
2029 unsigned("max_contours", max_contours),
2030 unsigned("max_points", resolved_max_points),
2031 unsigned("propagation_passes", propagation_passes),
2032 ];
2033 input.runtime().record_image_split_semantic(
2034 &dispatches,
2035 ImageSemanticDispatch {
2036 contract,
2037 inputs: &[ImageSemanticInput::Image(input)],
2038 outputs: &[
2039 ImageSemanticOutput::Matrix(&points),
2040 ImageSemanticOutput::Matrix(&lengths),
2041 ],
2042 attributes: &attributes,
2043 },
2044 )?;
2045 Ok((points, lengths))
2046}
2047
2048#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2050pub enum CornerScore {
2051 #[default]
2053 Harris,
2054 MinEigen,
2056}
2057
2058impl CornerScore {
2059 pub(super) const fn token(self) -> &'static str {
2060 match self {
2061 Self::Harris => "harris",
2062 Self::MinEigen => "min_eigen",
2063 }
2064 }
2065
2066 pub(super) const fn code(self) -> u32 {
2067 match self {
2068 Self::Harris => 0,
2069 Self::MinEigen => 1,
2070 }
2071 }
2072}
2073
2074pub fn corner_score(
2088 input: &Image,
2089 block_size: u32,
2090 k: f32,
2091 score_type: CornerScore,
2092) -> Result<Image> {
2093 if !k.is_finite() {
2094 return Err(Error::invalid_argument(
2095 "image::corner_score k must be finite",
2096 ));
2097 }
2098 if block_size < 3 || block_size.is_multiple_of(2) {
2099 return Err(Error::invalid_argument(
2100 "image::corner_score block_size must be odd and at least 3",
2101 ));
2102 }
2103 let contract = crate::core::operation::image::CORNER_SCORE;
2104 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
2105 let plane_count = batch
2106 .checked_mul(channels)
2107 .ok_or_else(|| Error::out_of_range("image::corner_score plane count exceeds u32"))?;
2108 let product_elements = plane_count
2109 .checked_mul(image_height)
2110 .and_then(|count| count.checked_mul(image_width))
2111 .and_then(|count| count.checked_mul(3))
2112 .ok_or_else(|| Error::out_of_range("image::corner_score scratch size exceeds u32"))?;
2113 let products = Matrix::allocate(
2114 input.runtime(),
2115 vec![product_elements as usize],
2116 product_elements as usize,
2117 DType::F32,
2118 )?;
2119 let output = allocate_like(input, contract.name())?;
2120 let gradient_buffers = [
2121 BufferBinding::read(input.storage()),
2122 BufferBinding::write(products.storage()),
2123 ];
2124 let gradient_push = [
2125 PushConstant::U32(batch),
2126 PushConstant::U32(channels),
2127 PushConstant::U32(image_height),
2128 PushConstant::U32(image_width),
2129 ];
2130 let score_buffers = [
2131 BufferBinding::read(products.storage()),
2132 BufferBinding::write(output.storage()),
2133 ];
2134 let score_push = [
2135 PushConstant::U32(batch),
2136 PushConstant::U32(channels),
2137 PushConstant::U32(image_height),
2138 PushConstant::U32(image_width),
2139 PushConstant::U32(block_size),
2140 PushConstant::F32(k),
2141 PushConstant::U32(score_type.code()),
2142 ];
2143 let dispatches = [
2144 ComputeDispatch {
2145 kernel: KernelId::ImageCornerScoreGradientF32,
2146 buffers: &gradient_buffers,
2147 push_constants: &gradient_push,
2148 workgroups: [
2149 image_width.div_ceil(16),
2150 image_height.div_ceil(16),
2151 batch * channels,
2152 ],
2153 indirect: None,
2154 },
2155 ComputeDispatch {
2156 kernel: KernelId::ImageCornerScoreF32,
2157 buffers: &score_buffers,
2158 push_constants: &score_push,
2159 workgroups: [
2160 image_width.div_ceil(16),
2161 image_height.div_ceil(16),
2162 batch * channels,
2163 ],
2164 indirect: None,
2165 },
2166 ];
2167 let attributes = [
2168 unsigned("block_size", block_size),
2169 float("k", k),
2170 enumeration("score_type", score_type.token()),
2171 ];
2172 input.runtime().record_image_split_semantic(
2173 &dispatches,
2174 ImageSemanticDispatch {
2175 contract,
2176 inputs: &[ImageSemanticInput::Image(input)],
2177 outputs: &[ImageSemanticOutput::Image(&output)],
2178 attributes: &attributes,
2179 },
2180 )?;
2181 Ok(output)
2182}
2183
2184pub fn corner_fast(input: &Image, arc_length: u32) -> Result<Image> {
2198 if !(9..=16).contains(&arc_length) {
2199 return Err(Error::invalid_argument(
2200 "image::corner_fast arc_length must be in 9..=16",
2201 ));
2202 }
2203 let contract = crate::core::operation::image::CORNER_FAST;
2204 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
2205 let output = allocate_like(input, contract.name())?;
2206 let attributes = [unsigned("arc_length", arc_length)];
2207 input.runtime().record_image_semantic(
2208 ComputeDispatch {
2209 kernel: KernelId::ImageCornerFastF32,
2210 buffers: &[
2211 BufferBinding::read(input.storage()),
2212 BufferBinding::write(output.storage()),
2213 ],
2214 push_constants: &[
2215 PushConstant::U32(batch),
2216 PushConstant::U32(channels),
2217 PushConstant::U32(image_height),
2218 PushConstant::U32(image_width),
2219 PushConstant::U32(arc_length),
2220 ],
2221 workgroups: [
2222 image_width.div_ceil(16),
2223 image_height.div_ceil(16),
2224 batch * channels,
2225 ],
2226 indirect: None,
2227 },
2228 ImageSemanticDispatch {
2229 contract,
2230 inputs: &[ImageSemanticInput::Image(input)],
2231 outputs: &[ImageSemanticOutput::Image(&output)],
2232 attributes: &attributes,
2233 },
2234 )?;
2235 Ok(output)
2236}
2237
2238pub fn bf_match(query: &Matrix, train: &Matrix) -> Result<Matrix> {
2252 if query.dtype() != DType::U8 || train.dtype() != DType::U8 {
2253 return Err(Error::invalid_argument(
2254 "image::bf_match requires U8 descriptor matrices",
2255 ));
2256 }
2257 if query.shape().len() != 2 || train.shape().len() != 2 {
2258 return Err(Error::invalid_argument(
2259 "image::bf_match requires [N, D] descriptor matrices",
2260 ));
2261 }
2262 let desc_len = query.shape()[1];
2263 if desc_len == 0 || train.shape()[1] != desc_len {
2264 return Err(Error::invalid_argument(
2265 "image::bf_match descriptor widths must match and be nonzero",
2266 ));
2267 }
2268 let query_count = query.shape()[0];
2269 let train_count = train.shape()[0];
2270 if query_count == 0 || train_count == 0 {
2271 return Err(Error::invalid_argument(
2272 "image::bf_match requires nonempty descriptor sets",
2273 ));
2274 }
2275 let query_count_u32 = u32::try_from(query_count)
2276 .map_err(|_| Error::out_of_range("image::bf_match query count exceeds u32"))?;
2277 let train_count_u32 = u32::try_from(train_count)
2278 .map_err(|_| Error::out_of_range("image::bf_match train count exceeds u32"))?;
2279 let desc_len_u32 = u32::try_from(desc_len)
2280 .map_err(|_| Error::out_of_range("image::bf_match descriptor width exceeds u32"))?;
2281 let output = Matrix::allocate(
2282 query.runtime(),
2283 vec![query_count, 4],
2284 query_count
2285 .checked_mul(4)
2286 .ok_or_else(|| Error::out_of_range("image::bf_match output size exceeds u32"))?,
2287 DType::F32,
2288 )?;
2289 let attributes = [];
2290 query.runtime().record_image_semantic(
2291 ComputeDispatch {
2292 kernel: KernelId::ImageBfMatchU8,
2293 buffers: &[
2294 BufferBinding::read(query.storage()),
2295 BufferBinding::read(train.storage()),
2296 BufferBinding::write(output.storage()),
2297 ],
2298 push_constants: &[
2299 PushConstant::U32(query_count_u32),
2300 PushConstant::U32(train_count_u32),
2301 PushConstant::U32(desc_len_u32),
2302 ],
2303 workgroups: KernelId::ImageBfMatchU8.linear_workgroups(query_count_u32),
2304 indirect: None,
2305 },
2306 ImageSemanticDispatch {
2307 contract: crate::core::operation::image::BF_MATCH,
2308 inputs: &[
2309 ImageSemanticInput::Matrix(query),
2310 ImageSemanticInput::Matrix(train),
2311 ],
2312 outputs: &[ImageSemanticOutput::Matrix(&output)],
2313 attributes: &attributes,
2314 },
2315 )?;
2316 Ok(output)
2317}
2318
2319pub fn good_features_to_track(
2338 input: &Image,
2339 max_corners: u32,
2340 quality: f32,
2341 min_distance: f32,
2342) -> Result<(Matrix, Matrix)> {
2343 if !quality.is_finite()
2344 || !(0.0..=1.0).contains(&quality)
2345 || !min_distance.is_finite()
2346 || min_distance < 0.0
2347 {
2348 return Err(Error::invalid_argument(
2349 "image::good_features_to_track requires quality in [0, 1] and finite min_distance >= 0",
2350 ));
2351 }
2352 let contract = crate::core::operation::image::GOOD_FEATURES_TO_TRACK;
2353 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
2354 let plane_count = batch
2355 .checked_mul(channels)
2356 .ok_or_else(|| Error::out_of_range("image::good_features_to_track plane count exceeds u32"))?;
2357 let corner_cap = if max_corners == 0 {
2358 image_height
2359 .checked_mul(image_width)
2360 .ok_or_else(|| Error::out_of_range("image::good_features_to_track plane size exceeds u32"))?
2361 } else {
2362 max_corners
2363 };
2364 let row_elements = plane_count
2365 .checked_mul(image_height)
2366 .ok_or_else(|| Error::out_of_range("image::good_features_to_track scratch size exceeds u32"))?;
2367 let row_max = Matrix::allocate(
2368 input.runtime(),
2369 vec![row_elements as usize],
2370 row_elements as usize,
2371 DType::F32,
2372 )?;
2373 let thresholds = Matrix::allocate(
2374 input.runtime(),
2375 vec![plane_count as usize],
2376 plane_count as usize,
2377 DType::F32,
2378 )?;
2379 let counts = Matrix::allocate(
2380 input.runtime(),
2381 vec![plane_count as usize],
2382 plane_count as usize,
2383 DType::U32,
2384 )?;
2385 let keypoints = Matrix::allocate(
2386 input.runtime(),
2387 vec![plane_count as usize, corner_cap as usize, 3],
2388 plane_count
2389 .checked_mul(corner_cap)
2390 .and_then(|count| count.checked_mul(3))
2391 .ok_or_else(|| {
2392 Error::out_of_range("image::good_features_to_track keypoint size exceeds u32")
2393 })? as usize,
2394 DType::F32,
2395 )?;
2396 let clear_buffers = [
2397 BufferBinding::write(keypoints.storage()),
2398 BufferBinding::write(counts.storage()),
2399 ];
2400 let clear_push = [
2401 PushConstant::U32(batch),
2402 PushConstant::U32(channels),
2403 PushConstant::U32(image_height),
2404 PushConstant::U32(image_width),
2405 PushConstant::U32(corner_cap),
2406 ];
2407 let row_buffers = [
2408 BufferBinding::read(input.storage()),
2409 BufferBinding::write(row_max.storage()),
2410 ];
2411 let row_push = [
2412 PushConstant::U32(batch),
2413 PushConstant::U32(channels),
2414 PushConstant::U32(image_height),
2415 PushConstant::U32(image_width),
2416 ];
2417 let threshold_buffers = [
2418 BufferBinding::read(row_max.storage()),
2419 BufferBinding::write(thresholds.storage()),
2420 ];
2421 let threshold_push = [
2422 PushConstant::U32(batch),
2423 PushConstant::U32(channels),
2424 PushConstant::U32(image_height),
2425 PushConstant::F32(quality),
2426 ];
2427 let select_buffers = [
2428 BufferBinding::read(input.storage()),
2429 BufferBinding::read(thresholds.storage()),
2430 BufferBinding::write(keypoints.storage()),
2431 BufferBinding::write(counts.storage()),
2432 ];
2433 let select_push = [
2434 PushConstant::U32(batch),
2435 PushConstant::U32(channels),
2436 PushConstant::U32(image_height),
2437 PushConstant::U32(image_width),
2438 PushConstant::U32(corner_cap),
2439 PushConstant::F32(min_distance),
2440 ];
2441 let attributes = [
2442 unsigned("max_corners", max_corners),
2443 float("quality", quality),
2444 float("min_distance", min_distance),
2445 ];
2446 input.runtime().record_image_split_semantic(
2447 &[
2448 ComputeDispatch {
2449 kernel: KernelId::ImageGoodFeaturesClearF32,
2450 buffers: &clear_buffers,
2451 push_constants: &clear_push,
2452 workgroups: KernelId::ImageGoodFeaturesClearF32
2453 .linear_workgroups(plane_count * corner_cap * 3),
2454 indirect: None,
2455 },
2456 ComputeDispatch {
2457 kernel: KernelId::ImageGoodFeaturesRowMaxF32,
2458 buffers: &row_buffers,
2459 push_constants: &row_push,
2460 workgroups: KernelId::ImageGoodFeaturesRowMaxF32
2461 .linear_workgroups(plane_count * image_height),
2462 indirect: None,
2463 },
2464 ComputeDispatch {
2465 kernel: KernelId::ImageGoodFeaturesThresholdF32,
2466 buffers: &threshold_buffers,
2467 push_constants: &threshold_push,
2468 workgroups: KernelId::ImageGoodFeaturesThresholdF32.linear_workgroups(plane_count),
2469 indirect: None,
2470 },
2471 ComputeDispatch {
2472 kernel: KernelId::ImageGoodFeaturesSelectF32,
2473 buffers: &select_buffers,
2474 push_constants: &select_push,
2475 workgroups: [
2476 image_width.div_ceil(16),
2477 image_height.div_ceil(16),
2478 batch * channels,
2479 ],
2480 indirect: None,
2481 },
2482 ],
2483 ImageSemanticDispatch {
2484 contract,
2485 inputs: &[ImageSemanticInput::Image(input)],
2486 outputs: &[
2487 ImageSemanticOutput::Matrix(&keypoints),
2488 ImageSemanticOutput::Matrix(&counts),
2489 ],
2490 attributes: &attributes,
2491 },
2492 )?;
2493 Ok((keypoints, counts))
2494}
2495
2496pub fn orb(
2519 input: &Image,
2520 max_features: u32,
2521 quality: f32,
2522 min_distance: f32,
2523 levels: u32,
2524 edge: u32,
2525) -> Result<(Matrix, Matrix, Matrix)> {
2526 if !quality.is_finite()
2527 || !(0.0..=1.0).contains(&quality)
2528 || !min_distance.is_finite()
2529 || min_distance < 0.0
2530 {
2531 return Err(Error::invalid_argument(
2532 "image::orb requires quality in [0, 1] and finite min_distance >= 0",
2533 ));
2534 }
2535 if levels == 0 || edge < 18 {
2536 return Err(Error::invalid_argument(
2537 "image::orb requires levels >= 1 and edge >= 18 for the rotated BRIEF support",
2538 ));
2539 }
2540 let contract = crate::core::operation::image::ORB;
2541 let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
2542 let plane_count = batch
2543 .checked_mul(channels)
2544 .ok_or_else(|| Error::out_of_range("image::orb plane count exceeds u32"))?;
2545 let feature_cap = if max_features == 0 {
2546 image_height
2547 .checked_mul(image_width)
2548 .ok_or_else(|| Error::out_of_range("image::orb plane size exceeds u32"))?
2549 } else {
2550 max_features
2551 };
2552 let level_cap = feature_cap;
2553 let keypoints = Matrix::allocate(
2554 input.runtime(),
2555 vec![plane_count as usize, feature_cap as usize, 6],
2556 plane_count
2557 .checked_mul(feature_cap)
2558 .and_then(|count| count.checked_mul(6))
2559 .ok_or_else(|| Error::out_of_range("image::orb keypoint size exceeds u32"))? as usize,
2560 DType::F32,
2561 )?;
2562 let descriptors = Matrix::allocate(
2563 input.runtime(),
2564 vec![plane_count as usize, feature_cap as usize, 8],
2565 plane_count
2566 .checked_mul(feature_cap)
2567 .and_then(|count| count.checked_mul(8))
2568 .ok_or_else(|| Error::out_of_range("image::orb descriptor size exceeds u32"))? as usize,
2569 DType::U32,
2570 )?;
2571 let counts = Matrix::allocate(
2572 input.runtime(),
2573 vec![plane_count as usize],
2574 plane_count as usize,
2575 DType::U32,
2576 )?;
2577 let clear_buffers = [
2578 BufferBinding::write(keypoints.storage()),
2579 BufferBinding::write(descriptors.storage()),
2580 BufferBinding::write(counts.storage()),
2581 ];
2582 let clear_push = [
2583 PushConstant::U32(batch),
2584 PushConstant::U32(channels),
2585 PushConstant::U32(feature_cap),
2586 ];
2587 let mut level_images = Vec::with_capacity(levels as usize);
2588 let mut level_dims = Vec::with_capacity(levels as usize);
2589 let mut level_states = Vec::with_capacity(levels as usize);
2590 level_images.push(input.clone());
2591 level_dims.push((image_width, image_height, 1.0f32));
2592 for _ in 1..levels {
2593 let next = crate::image::pyr_down(
2594 level_images
2595 .last()
2596 .ok_or_else(|| Error::internal("image::orb pyramid level missing"))?,
2597 )?;
2598 let (width, height, scale) = level_dims[level_dims.len() - 1];
2599 level_dims.push((width.div_ceil(2), height.div_ceil(2), scale * 2.0));
2600 level_images.push(next);
2601 }
2602 for level_image in &level_images {
2603 let score_map = crate::image::corner_fast(level_image, 9)?;
2604 let (level_keypoints, level_counts) =
2605 crate::image::good_features_to_track(&score_map, level_cap, quality, min_distance)?;
2606 level_states.push((level_keypoints, level_counts));
2607 }
2608 let mut describe_sets = Vec::with_capacity(levels as usize);
2609 let mut describe_pushes = Vec::with_capacity(levels as usize);
2610 for level in 0..levels {
2611 let level_image = &level_images[level as usize];
2612 let level_keypoints = &level_states[level as usize].0;
2613 let level_counts = &level_states[level as usize].1;
2614 let (level_width, level_height, level_scale) = level_dims[level as usize];
2615 let describe_buffers = [
2616 BufferBinding::read(level_image.storage()),
2617 BufferBinding::read(level_keypoints.storage()),
2618 BufferBinding::read(level_counts.storage()),
2619 BufferBinding::write(keypoints.storage()),
2620 BufferBinding::write(descriptors.storage()),
2621 BufferBinding::write(counts.storage()),
2622 ];
2623 let describe_push = [
2624 PushConstant::U32(batch),
2625 PushConstant::U32(channels),
2626 PushConstant::U32(level_height),
2627 PushConstant::U32(level_width),
2628 PushConstant::U32(level_cap),
2629 PushConstant::U32(edge),
2630 PushConstant::U32(feature_cap),
2631 PushConstant::U32(level),
2632 PushConstant::F32(level_scale),
2633 ];
2634 describe_sets.push(describe_buffers);
2635 describe_pushes.push(describe_push);
2636 }
2637 let attributes = [
2638 unsigned("max_features", max_features),
2639 float("quality", quality),
2640 float("min_distance", min_distance),
2641 unsigned("levels", levels),
2642 unsigned("edge", edge),
2643 ];
2644 let mut dispatches = Vec::with_capacity(describe_sets.len() + 1);
2645 dispatches.push(ComputeDispatch {
2646 kernel: KernelId::ImageOrbClearF32,
2647 buffers: &clear_buffers,
2648 push_constants: &clear_push,
2649 workgroups: KernelId::ImageOrbClearF32.linear_workgroups(plane_count * feature_cap * 8),
2650 indirect: None,
2651 });
2652 for (buffers, push_constants) in describe_sets.iter().zip(describe_pushes.iter()) {
2653 dispatches.push(ComputeDispatch {
2654 kernel: KernelId::ImageOrbDescribeF32,
2655 buffers: buffers.as_slice(),
2656 push_constants: push_constants.as_slice(),
2657 workgroups: KernelId::ImageOrbDescribeF32.linear_workgroups(plane_count * level_cap),
2658 indirect: None,
2659 });
2660 }
2661 input.runtime().record_image_split_semantic(
2662 &dispatches,
2663 ImageSemanticDispatch {
2664 contract,
2665 inputs: &[ImageSemanticInput::Image(input)],
2666 outputs: &[
2667 ImageSemanticOutput::Matrix(&keypoints),
2668 ImageSemanticOutput::Matrix(&descriptors),
2669 ImageSemanticOutput::Matrix(&counts),
2670 ],
2671 attributes: &attributes,
2672 },
2673 )?;
2674 Ok((keypoints, descriptors, counts))
2675}
2676
2677pub fn optical_flow_pyr_lk(
2702 previous: &Image,
2703 next: &Image,
2704 points: &Matrix,
2705 levels: u32,
2706 window: u32,
2707 iterations: u32,
2708 min_eigen: f32,
2709) -> Result<(Matrix, Matrix, Matrix)> {
2710 let (batch, channels, image_height, image_width) =
2711 validate_accumulation_pair(previous, next, "image::optical_flow_pyr_lk")?;
2712 if levels == 0 || window == 0 || iterations == 0 || !min_eigen.is_finite() || min_eigen <= 0.0 {
2713 return Err(Error::invalid_argument(
2714 "image::optical_flow_pyr_lk requires levels/window/iterations >= 1 and finite min_eigen > 0",
2715 ));
2716 }
2717 if points.dtype() != DType::F32
2718 || points.shape().len() != 2
2719 || points.shape()[0] == 0
2720 || points.shape()[1] != 2
2721 {
2722 return Err(Error::invalid_argument(
2723 "image::optical_flow_pyr_lk requires a nonempty F32 [N, 2] points matrix",
2724 ));
2725 }
2726 let point_count = u32::try_from(points.shape()[0])
2727 .map_err(|_| Error::out_of_range("image::optical_flow_pyr_lk point count exceeds u32"))?;
2728 let support = window
2729 .checked_mul(2)
2730 .and_then(|value| value.checked_add(1))
2731 .ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk window exceeds u32"))?;
2732 let plane_count = batch
2733 .checked_mul(channels)
2734 .ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk plane count exceeds u32"))?;
2735 let state_elements = plane_count
2736 .checked_mul(point_count)
2737 .and_then(|count| count.checked_mul(2))
2738 .ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk state size exceeds u32"))?;
2739 let map_elements = plane_count
2740 .checked_mul(point_count)
2741 .ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk map size exceeds u32"))?;
2742 let contract = crate::core::operation::image::OPTICAL_FLOW_PYR_LK;
2743 let mut previous_levels = Vec::with_capacity(levels as usize);
2744 let mut next_levels = Vec::with_capacity(levels as usize);
2745 let mut level_dims = Vec::with_capacity(levels as usize);
2746 previous_levels.push(previous.clone());
2747 next_levels.push(next.clone());
2748 level_dims.push((image_width, image_height));
2749 for _ in 1..levels {
2750 previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
2751 || Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
2752 )?)?);
2753 next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
2754 || Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
2755 )?)?);
2756 let (width, height) = level_dims[level_dims.len() - 1];
2757 level_dims.push((width.div_ceil(2), height.div_ceil(2)));
2758 }
2759 let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
2760 if coarsest_width < support || coarsest_height < support {
2761 return Err(Error::invalid_argument(
2762 "image::optical_flow_pyr_lk requires the coarsest level to fit the full window",
2763 ));
2764 }
2765 let next_points = Matrix::allocate(
2766 previous.runtime(),
2767 vec![plane_count as usize, point_count as usize, 2],
2768 state_elements as usize,
2769 DType::F32,
2770 )?;
2771 let status = Matrix::allocate(
2772 previous.runtime(),
2773 vec![plane_count as usize, point_count as usize],
2774 map_elements as usize,
2775 DType::F32,
2776 )?;
2777 let error = Matrix::allocate(
2778 previous.runtime(),
2779 vec![plane_count as usize, point_count as usize],
2780 map_elements as usize,
2781 DType::F32,
2782 )?;
2783 let mut stages = Vec::with_capacity(levels as usize);
2784 for level in (0..levels).rev() {
2785 let previous_level = &previous_levels[level as usize];
2786 let next_level = &next_levels[level as usize];
2787 let (level_width, level_height) = level_dims[level as usize];
2788 let level_scale = 0.5f32.powi(level as i32);
2789 let initialize = u32::from(level == levels - 1);
2790 let finalize = u32::from(level == 0);
2791 let refine_buffers = [
2792 BufferBinding::read(previous_level.storage()),
2793 BufferBinding::read(next_level.storage()),
2794 BufferBinding::read(points.storage()),
2795 BufferBinding::read_write(next_points.storage()),
2796 BufferBinding::write(status.storage()),
2797 BufferBinding::write(error.storage()),
2798 ];
2799 let refine_push = [
2800 PushConstant::U32(batch),
2801 PushConstant::U32(channels),
2802 PushConstant::U32(point_count),
2803 PushConstant::U32(level_height),
2804 PushConstant::U32(level_width),
2805 PushConstant::U32(window),
2806 PushConstant::U32(iterations),
2807 PushConstant::U32(initialize),
2808 PushConstant::U32(finalize),
2809 PushConstant::F32(level_scale),
2810 PushConstant::F32(min_eigen),
2811 ];
2812 stages.push((KernelId::ImageFlowLkRefineF32, refine_buffers, refine_push));
2813 }
2814 let attributes = [
2815 unsigned("levels", levels),
2816 unsigned("window", window),
2817 unsigned("iterations", iterations),
2818 float("min_eigen", min_eigen),
2819 ];
2820 let dispatches: Vec<ComputeDispatch> = stages
2821 .iter()
2822 .map(|(kernel, buffers, push_constants)| ComputeDispatch {
2823 kernel: *kernel,
2824 buffers: buffers.as_slice(),
2825 push_constants: push_constants.as_slice(),
2826 workgroups: KernelId::ImageFlowLkRefineF32.linear_workgroups(plane_count * point_count),
2827 indirect: None,
2828 })
2829 .collect();
2830 previous.runtime().record_image_split_semantic(
2831 &dispatches,
2832 ImageSemanticDispatch {
2833 contract,
2834 inputs: &[
2835 ImageSemanticInput::Image(previous),
2836 ImageSemanticInput::Image(next),
2837 ImageSemanticInput::Matrix(points),
2838 ],
2839 outputs: &[
2840 ImageSemanticOutput::Matrix(&next_points),
2841 ImageSemanticOutput::Matrix(&status),
2842 ImageSemanticOutput::Matrix(&error),
2843 ],
2844 attributes: &attributes,
2845 },
2846 )?;
2847 Ok((next_points, status, error))
2848}
2849
2850pub fn optical_flow_farneback(
2875 previous: &Image,
2876 next: &Image,
2877 levels: u32,
2878 window: u32,
2879 iterations: u32,
2880 poly_n: u32,
2881 poly_sigma: f32,
2882) -> Result<Matrix> {
2883 let (batch, channels, image_height, image_width) =
2884 validate_accumulation_pair(previous, next, "image::optical_flow_farneback")?;
2885 if levels == 0
2886 || window == 0
2887 || iterations == 0
2888 || poly_n == 0
2889 || !poly_sigma.is_finite()
2890 || poly_sigma <= 0.0
2891 {
2892 return Err(Error::invalid_argument(
2893 "image::optical_flow_farneback requires levels/window/iterations/poly_n >= 1 and finite poly_sigma > 0",
2894 ));
2895 }
2896 let poly_support = poly_n
2897 .checked_mul(2)
2898 .and_then(|value| value.checked_add(1))
2899 .ok_or_else(|| Error::out_of_range("image::optical_flow_farneback poly_n exceeds u32"))?;
2900 let plane_count = batch
2901 .checked_mul(channels)
2902 .ok_or_else(|| Error::out_of_range("image::optical_flow_farneback plane count exceeds u32"))?;
2903 let contract = crate::core::operation::image::OPTICAL_FLOW_FARNEBACK;
2904 let mut previous_levels = Vec::with_capacity(levels as usize);
2905 let mut next_levels = Vec::with_capacity(levels as usize);
2906 let mut level_dims = Vec::with_capacity(levels as usize);
2907 previous_levels.push(previous.clone());
2908 next_levels.push(next.clone());
2909 level_dims.push((image_width, image_height));
2910 for _ in 1..levels {
2911 previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
2912 || Error::internal("image::optical_flow_farneback pyramid level missing"),
2913 )?)?);
2914 next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
2915 || Error::internal("image::optical_flow_farneback pyramid level missing"),
2916 )?)?);
2917 let (width, height) = level_dims[level_dims.len() - 1];
2918 level_dims.push((width.div_ceil(2), height.div_ceil(2)));
2919 }
2920 let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
2921 if coarsest_width < poly_support || coarsest_height < poly_support {
2922 return Err(Error::invalid_argument(
2923 "image::optical_flow_farneback requires the coarsest level to fit the polynomial support",
2924 ));
2925 }
2926 let workspace_elements = |planes: u32| -> Result<usize> {
2927 Ok(
2928 planes
2929 .checked_mul(image_height)
2930 .and_then(|count| count.checked_mul(image_width))
2931 .ok_or_else(|| {
2932 Error::out_of_range("image::optical_flow_farneback workspace size exceeds u32")
2933 })? as usize,
2934 )
2935 };
2936 let moment_shape = vec![
2937 plane_count as usize,
2938 3,
2939 image_height as usize,
2940 image_width as usize,
2941 ];
2942 let poly_shape = vec![
2943 plane_count as usize,
2944 5,
2945 image_height as usize,
2946 image_width as usize,
2947 ];
2948 let flow_shape = vec![
2949 plane_count as usize,
2950 2,
2951 image_height as usize,
2952 image_width as usize,
2953 ];
2954 let three_planes = plane_count.checked_mul(3).ok_or_else(|| {
2955 Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2956 })?;
2957 let five_planes = plane_count.checked_mul(5).ok_or_else(|| {
2958 Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2959 })?;
2960 let two_planes = plane_count.checked_mul(2).ok_or_else(|| {
2961 Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2962 })?;
2963 let moments_a = Matrix::allocate(
2964 previous.runtime(),
2965 moment_shape.clone(),
2966 workspace_elements(three_planes)?,
2967 DType::F32,
2968 )?;
2969 let moments_b = Matrix::allocate(
2970 previous.runtime(),
2971 moment_shape,
2972 workspace_elements(three_planes)?,
2973 DType::F32,
2974 )?;
2975 let poly1 = Matrix::allocate(
2976 previous.runtime(),
2977 poly_shape.clone(),
2978 workspace_elements(five_planes)?,
2979 DType::F32,
2980 )?;
2981 let poly2 = Matrix::allocate(
2982 previous.runtime(),
2983 poly_shape,
2984 workspace_elements(five_planes)?,
2985 DType::F32,
2986 )?;
2987 let flow_a = Matrix::allocate(
2988 previous.runtime(),
2989 flow_shape.clone(),
2990 workspace_elements(two_planes)?,
2991 DType::F32,
2992 )?;
2993 let flow_b = Matrix::allocate(
2994 previous.runtime(),
2995 flow_shape.clone(),
2996 workspace_elements(two_planes)?,
2997 DType::F32,
2998 )?;
2999 let flow = Matrix::allocate(
3000 previous.runtime(),
3001 flow_shape,
3002 workspace_elements(two_planes)?,
3003 DType::F32,
3004 )?;
3005 let mut stages = Vec::new();
3006 let mut parent: Option<(&Matrix, u32, u32, bool)> = None;
3007 for level in (0..levels).rev() {
3008 let (level_width, level_height) = level_dims[level as usize];
3009 {
3010 let expand_input = &previous_levels[level as usize];
3011 let expand_output = &moments_a;
3012 let expand_v_buffers = [
3013 BufferBinding::read(expand_input.storage()),
3014 BufferBinding::write(expand_output.storage()),
3015 ];
3016 let expand_v_push = [
3017 PushConstant::U32(batch),
3018 PushConstant::U32(channels),
3019 PushConstant::U32(level_height),
3020 PushConstant::U32(level_width),
3021 PushConstant::U32(poly_n),
3022 PushConstant::F32(poly_sigma),
3023 ];
3024 stages.push((
3025 KernelId::ImageFlowExpandVF32,
3026 expand_v_buffers.to_vec(),
3027 expand_v_push.to_vec(),
3028 [
3029 level_width.div_ceil(16),
3030 level_height.div_ceil(16),
3031 plane_count,
3032 ],
3033 ));
3034 }
3035 {
3036 let expand_input = &moments_a;
3037 let expand_output = &poly1;
3038 let expand_h_buffers = [
3039 BufferBinding::read(expand_input.storage()),
3040 BufferBinding::write(expand_output.storage()),
3041 ];
3042 let expand_h_push = [
3043 PushConstant::U32(batch),
3044 PushConstant::U32(channels),
3045 PushConstant::U32(level_height),
3046 PushConstant::U32(level_width),
3047 PushConstant::U32(poly_n),
3048 PushConstant::F32(poly_sigma),
3049 ];
3050 stages.push((
3051 KernelId::ImageFlowExpandHF32,
3052 expand_h_buffers.to_vec(),
3053 expand_h_push.to_vec(),
3054 [
3055 level_width.div_ceil(16),
3056 level_height.div_ceil(16),
3057 plane_count,
3058 ],
3059 ));
3060 }
3061 {
3062 let expand_input = &next_levels[level as usize];
3063 let expand_output = &moments_b;
3064 let expand_v_buffers = [
3065 BufferBinding::read(expand_input.storage()),
3066 BufferBinding::write(expand_output.storage()),
3067 ];
3068 let expand_v_push = [
3069 PushConstant::U32(batch),
3070 PushConstant::U32(channels),
3071 PushConstant::U32(level_height),
3072 PushConstant::U32(level_width),
3073 PushConstant::U32(poly_n),
3074 PushConstant::F32(poly_sigma),
3075 ];
3076 stages.push((
3077 KernelId::ImageFlowExpandVF32,
3078 expand_v_buffers.to_vec(),
3079 expand_v_push.to_vec(),
3080 [
3081 level_width.div_ceil(16),
3082 level_height.div_ceil(16),
3083 plane_count,
3084 ],
3085 ));
3086 }
3087 {
3088 let expand_input = &moments_b;
3089 let expand_output = &poly2;
3090 let expand_h_buffers = [
3091 BufferBinding::read(expand_input.storage()),
3092 BufferBinding::write(expand_output.storage()),
3093 ];
3094 let expand_h_push = [
3095 PushConstant::U32(batch),
3096 PushConstant::U32(channels),
3097 PushConstant::U32(level_height),
3098 PushConstant::U32(level_width),
3099 PushConstant::U32(poly_n),
3100 PushConstant::F32(poly_sigma),
3101 ];
3102 stages.push((
3103 KernelId::ImageFlowExpandHF32,
3104 expand_h_buffers.to_vec(),
3105 expand_h_push.to_vec(),
3106 [
3107 level_width.div_ceil(16),
3108 level_height.div_ceil(16),
3109 plane_count,
3110 ],
3111 ));
3112 }
3113 let mut estimate: &Matrix = &flow_a;
3114 let mut estimate_is_a = true;
3115 for iteration in 0..iterations {
3116 let (flow_in, init_mode, flow_in_width, flow_in_height, input_is_a) = if iteration == 0 {
3117 match parent {
3118 Some((buffer, width, height, is_a)) => (buffer, 1u32, width, height, is_a),
3119 None => (&flow_a, 0u32, level_width, level_height, true),
3120 }
3121 } else {
3122 (estimate, 2u32, level_width, level_height, estimate_is_a)
3123 };
3124 let output_is_flow = level == 0 && iteration + 1 == iterations;
3125 let flow_out: &Matrix = if output_is_flow {
3126 &flow
3127 } else if input_is_a {
3128 &flow_b
3129 } else {
3130 &flow_a
3131 };
3132 let update_buffers = [
3133 BufferBinding::read(poly1.storage()),
3134 BufferBinding::read(poly2.storage()),
3135 BufferBinding::read(flow_in.storage()),
3136 BufferBinding::write(flow_out.storage()),
3137 ];
3138 let update_push = [
3139 PushConstant::U32(batch),
3140 PushConstant::U32(channels),
3141 PushConstant::U32(level_height),
3142 PushConstant::U32(level_width),
3143 PushConstant::U32(flow_in_height),
3144 PushConstant::U32(flow_in_width),
3145 PushConstant::U32(window),
3146 PushConstant::U32(init_mode),
3147 ];
3148 stages.push((
3149 KernelId::ImageFlowUpdateF32,
3150 update_buffers.to_vec(),
3151 update_push.to_vec(),
3152 [
3153 level_width.div_ceil(16),
3154 level_height.div_ceil(16),
3155 plane_count,
3156 ],
3157 ));
3158 estimate = flow_out;
3159 estimate_is_a = !input_is_a;
3160 }
3161 parent = Some((estimate, level_width, level_height, estimate_is_a));
3162 }
3163 let attributes = [
3164 unsigned("levels", levels),
3165 unsigned("window", window),
3166 unsigned("iterations", iterations),
3167 unsigned("poly_n", poly_n),
3168 float("poly_sigma", poly_sigma),
3169 ];
3170 let dispatches: Vec<ComputeDispatch> = stages
3171 .iter()
3172 .map(
3173 |(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3174 kernel: *kernel,
3175 buffers: buffers.as_slice(),
3176 push_constants: push_constants.as_slice(),
3177 workgroups: *workgroups,
3178 indirect: None,
3179 },
3180 )
3181 .collect();
3182 previous.runtime().record_image_split_semantic(
3183 &dispatches,
3184 ImageSemanticDispatch {
3185 contract,
3186 inputs: &[
3187 ImageSemanticInput::Image(previous),
3188 ImageSemanticInput::Image(next),
3189 ],
3190 outputs: &[ImageSemanticOutput::Matrix(&flow)],
3191 attributes: &attributes,
3192 },
3193 )?;
3194 Ok(flow)
3195}
3196
3197pub fn stereo_bm(
3216 left: &Image,
3217 right: &Image,
3218 num_disparities: u32,
3219 block_size: u32,
3220 uniqueness: u32,
3221) -> Result<Matrix> {
3222 let (batch, channels, image_height, image_width) =
3223 validate_accumulation_pair(left, right, "image::stereo_bm")?;
3224 if num_disparities == 0 || block_size < 3 || block_size.is_multiple_of(2) {
3225 return Err(Error::invalid_argument(
3226 "image::stereo_bm requires num_disparities >= 1 and an odd block_size >= 3",
3227 ));
3228 }
3229 let support = block_size
3230 .checked_sub(1)
3231 .and_then(|value| value.checked_add(num_disparities))
3232 .ok_or_else(|| Error::out_of_range("image::stereo_bm support exceeds u32"))?;
3233 if image_width < support || image_height < block_size {
3234 return Err(Error::invalid_argument(
3235 "image::stereo_bm requires the image to fit the block and disparity support",
3236 ));
3237 }
3238 let plane_count = batch
3239 .checked_mul(channels)
3240 .ok_or_else(|| Error::out_of_range("image::stereo_bm plane count exceeds u32"))?;
3241 let disp_count = plane_count
3242 .checked_mul(num_disparities)
3243 .ok_or_else(|| Error::out_of_range("image::stereo_bm disparity slots exceed u32"))?;
3244 let block_radius = block_size / 2;
3245 let plane_elements = (image_height as usize)
3246 .checked_mul(image_width as usize)
3247 .ok_or_else(|| Error::out_of_range("image::stereo_bm plane size exceeds u32"))?;
3248 let cost_volume = Matrix::allocate(
3249 left.runtime(),
3250 vec![
3251 plane_count as usize,
3252 num_disparities as usize,
3253 image_height as usize,
3254 image_width as usize,
3255 ],
3256 plane_elements
3257 .checked_mul(disp_count as usize)
3258 .ok_or_else(|| Error::out_of_range("image::stereo_bm cost volume exceeds u32"))?,
3259 DType::F32,
3260 )?;
3261 let output = Matrix::allocate(
3262 left.runtime(),
3263 vec![
3264 plane_count as usize,
3265 1,
3266 image_height as usize,
3267 image_width as usize,
3268 ],
3269 plane_elements
3270 .checked_mul(plane_count as usize)
3271 .ok_or_else(|| Error::out_of_range("image::stereo_bm output size exceeds u32"))?,
3272 DType::F32,
3273 )?;
3274 let contract = crate::core::operation::image::STEREO_BM;
3275 let mut stages = Vec::new();
3276 {
3277 let sad_buffers = [
3278 BufferBinding::read(left.storage()),
3279 BufferBinding::read(right.storage()),
3280 BufferBinding::write(cost_volume.storage()),
3281 ];
3282 let sad_push = [
3283 PushConstant::U32(batch),
3284 PushConstant::U32(channels),
3285 PushConstant::U32(image_height),
3286 PushConstant::U32(image_width),
3287 PushConstant::U32(num_disparities),
3288 PushConstant::U32(block_radius),
3289 ];
3290 stages.push((
3291 KernelId::ImageStereoSadF32,
3292 sad_buffers.to_vec(),
3293 sad_push.to_vec(),
3294 [
3295 image_width.div_ceil(16),
3296 image_height.div_ceil(16),
3297 disp_count,
3298 ],
3299 ));
3300 }
3301 {
3302 let wta_buffers = [
3303 BufferBinding::read(cost_volume.storage()),
3304 BufferBinding::write(output.storage()),
3305 ];
3306 let wta_push = [
3307 PushConstant::U32(batch),
3308 PushConstant::U32(channels),
3309 PushConstant::U32(image_height),
3310 PushConstant::U32(image_width),
3311 PushConstant::U32(num_disparities),
3312 PushConstant::U32(block_radius),
3313 PushConstant::U32(uniqueness),
3314 ];
3315 stages.push((
3316 KernelId::ImageStereoWtaF32,
3317 wta_buffers.to_vec(),
3318 wta_push.to_vec(),
3319 [
3320 image_width.div_ceil(16),
3321 image_height.div_ceil(16),
3322 plane_count,
3323 ],
3324 ));
3325 }
3326 let attributes = [
3327 unsigned("num_disparities", num_disparities),
3328 unsigned("block_size", block_size),
3329 unsigned("uniqueness", uniqueness),
3330 ];
3331 let dispatches: Vec<ComputeDispatch> = stages
3332 .iter()
3333 .map(
3334 |(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3335 kernel: *kernel,
3336 buffers: buffers.as_slice(),
3337 push_constants: push_constants.as_slice(),
3338 workgroups: *workgroups,
3339 indirect: None,
3340 },
3341 )
3342 .collect();
3343 left.runtime().record_image_split_semantic(
3344 &dispatches,
3345 ImageSemanticDispatch {
3346 contract,
3347 inputs: &[
3348 ImageSemanticInput::Image(left),
3349 ImageSemanticInput::Image(right),
3350 ],
3351 outputs: &[ImageSemanticOutput::Matrix(&output)],
3352 attributes: &attributes,
3353 },
3354 )?;
3355 Ok(output)
3356}
3357
3358pub fn reproject_image_to_3d(disparity: &Matrix, q: &Matrix) -> Result<Matrix> {
3374 if disparity.dtype() != DType::F32 || q.dtype() != DType::F32 {
3375 return Err(Error::invalid_argument(
3376 "image::reproject_image_to_3d requires F32 disparity and q matrices",
3377 ));
3378 }
3379 if disparity.shape().len() != 4 || disparity.shape()[1] != 1 {
3380 return Err(Error::invalid_argument(
3381 "image::reproject_image_to_3d requires a [planes, 1, H, W] disparity matrix",
3382 ));
3383 }
3384 if q.shape() != [4, 4] {
3385 return Err(Error::invalid_argument(
3386 "image::reproject_image_to_3d requires a [4, 4] q matrix",
3387 ));
3388 }
3389 let plane_count = u32::try_from(disparity.shape()[0])
3390 .map_err(|_| Error::out_of_range("image::reproject_image_to_3d plane count exceeds u32"))?;
3391 let height = u32::try_from(disparity.shape()[2])
3392 .map_err(|_| Error::out_of_range("image::reproject_image_to_3d height exceeds u32"))?;
3393 let width = u32::try_from(disparity.shape()[3])
3394 .map_err(|_| Error::out_of_range("image::reproject_image_to_3d width exceeds u32"))?;
3395 if plane_count == 0 || height == 0 || width == 0 {
3396 return Err(Error::invalid_argument(
3397 "image::reproject_image_to_3d requires a nonempty disparity matrix",
3398 ));
3399 }
3400 let plane_elements = (height as usize)
3401 .checked_mul(width as usize)
3402 .ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d plane size exceeds u32"))?;
3403 let output = Matrix::allocate(
3404 disparity.runtime(),
3405 vec![plane_count as usize, 3, height as usize, width as usize],
3406 plane_elements
3407 .checked_mul(3)
3408 .and_then(|count| count.checked_mul(plane_count as usize))
3409 .ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d output size exceeds u32"))?,
3410 DType::F32,
3411 )?;
3412 let attributes = [];
3413 disparity.runtime().record_image_semantic(
3414 ComputeDispatch {
3415 kernel: KernelId::ImageReproject3dF32,
3416 buffers: &[
3417 BufferBinding::read(disparity.storage()),
3418 BufferBinding::read(q.storage()),
3419 BufferBinding::write(output.storage()),
3420 ],
3421 push_constants: &[
3422 PushConstant::U32(plane_count),
3423 PushConstant::U32(1),
3424 PushConstant::U32(height),
3425 PushConstant::U32(width),
3426 ],
3427 workgroups: [width.div_ceil(16), height.div_ceil(16), plane_count],
3428 indirect: None,
3429 },
3430 ImageSemanticDispatch {
3431 contract: crate::core::operation::image::REPROJECT_IMAGE_TO_3D,
3432 inputs: &[
3433 ImageSemanticInput::Matrix(disparity),
3434 ImageSemanticInput::Matrix(q),
3435 ],
3436 outputs: &[ImageSemanticOutput::Matrix(&output)],
3437 attributes: &attributes,
3438 },
3439 )?;
3440 Ok(output)
3441}
3442
3443pub fn fast_nl_means_denoising(
3458 input: &Image,
3459 h: f32,
3460 template_window: u32,
3461 search_window: u32,
3462) -> Result<Image> {
3463 let (batch, channels, image_height, image_width) =
3464 image_extent(input, "image::fast_nl_means_denoising")?;
3465 if !h.is_finite() || h <= 0.0 {
3466 return Err(Error::invalid_argument(
3467 "image::fast_nl_means_denoising requires a finite positive h",
3468 ));
3469 }
3470 if template_window < 3
3471 || template_window.is_multiple_of(2)
3472 || search_window < 3
3473 || search_window.is_multiple_of(2)
3474 {
3475 return Err(Error::invalid_argument(
3476 "image::fast_nl_means_denoising requires odd template_window/search_window >= 3",
3477 ));
3478 }
3479 let template_radius = template_window / 2;
3480 let search_radius = search_window / 2;
3481 let h_sqr = h * h;
3482 let output = allocate_like(input, "image::fast_nl_means_denoising")?;
3483 let attributes = [
3484 float("h", h),
3485 unsigned("template_window", template_window),
3486 unsigned("search_window", search_window),
3487 ];
3488 input.runtime().record_image_semantic(
3489 ComputeDispatch {
3490 kernel: KernelId::ImageNlMeansDenoiseF32,
3491 buffers: &[
3492 BufferBinding::read(input.storage()),
3493 BufferBinding::write(output.storage()),
3494 ],
3495 push_constants: &[
3496 PushConstant::U32(batch),
3497 PushConstant::U32(channels),
3498 PushConstant::U32(image_height),
3499 PushConstant::U32(image_width),
3500 PushConstant::U32(template_radius),
3501 PushConstant::U32(search_radius),
3502 PushConstant::F32(h_sqr),
3503 ],
3504 workgroups: [
3505 image_width.div_ceil(16),
3506 image_height.div_ceil(16),
3507 batch * channels,
3508 ],
3509 indirect: None,
3510 },
3511 ImageSemanticDispatch {
3512 contract: crate::core::operation::image::FAST_NL_MEANS_DENOISING,
3513 inputs: &[ImageSemanticInput::Image(input)],
3514 outputs: &[ImageSemanticOutput::Image(&output)],
3515 attributes: &attributes,
3516 },
3517 )?;
3518 Ok(output)
3519}
3520
3521pub fn pyr_mean_shift_filtering(input: &Image, sp: f32, sr: f32, max_level: u32) -> Result<Image> {
3541 let (batch, channels, image_height, image_width) =
3542 image_extent(input, "image::pyr_mean_shift_filtering")?;
3543 if !sp.is_finite() || sp <= 0.0 || !sr.is_finite() || sr <= 0.0 {
3544 return Err(Error::invalid_argument(
3545 "image::pyr_mean_shift_filtering requires finite positive sp and sr",
3546 ));
3547 }
3548 if channels > 4 {
3549 return Err(Error::invalid_argument(
3550 "image::pyr_mean_shift_filtering supports at most 4 channels",
3551 ));
3552 }
3553 if !(1..=4).contains(&max_level) {
3554 return Err(Error::invalid_argument(
3555 "image::pyr_mean_shift_filtering requires max_level in [1, 4]",
3556 ));
3557 }
3558 let levels = max_level
3559 .checked_add(1)
3560 .ok_or_else(|| Error::out_of_range("image::pyr_mean_shift_filtering max_level exceeds u32"))?;
3561 let spatial_radius = sp.ceil() as u32;
3562 let range_radius_sqr = sr * sr;
3563 let mut level_images = Vec::with_capacity(levels as usize);
3564 let mut level_dims = Vec::with_capacity(levels as usize);
3565 level_images.push(input.clone());
3566 level_dims.push((image_width, image_height));
3567 for _ in 1..levels {
3568 level_images.push(crate::image::pyr_down(level_images.last().ok_or_else(
3569 || Error::internal("image::pyr_mean_shift_filtering pyramid level missing"),
3570 )?)?);
3571 let (width, height) = level_dims[level_dims.len() - 1];
3572 level_dims.push((width.div_ceil(2), height.div_ceil(2)));
3573 }
3574 let runtime = input.runtime();
3575 let mut workspaces = Vec::with_capacity(levels as usize - 1);
3579 for level in 1..levels {
3580 let (level_width, level_height) = level_dims[level as usize];
3581 let count = (batch as usize)
3582 .checked_mul(channels as usize)
3583 .and_then(|value| value.checked_mul(level_height as usize))
3584 .and_then(|value| value.checked_mul(level_width as usize))
3585 .ok_or_else(|| {
3586 Error::out_of_range("image::pyr_mean_shift_filtering workspace exceeds usize")
3587 })?;
3588 workspaces.push(Matrix::allocate(
3589 runtime,
3590 vec![
3591 batch as usize,
3592 channels as usize,
3593 level_height as usize,
3594 level_width as usize,
3595 ],
3596 count,
3597 DType::F32,
3598 )?);
3599 }
3600 let output = allocate_like(input, "image::pyr_mean_shift_filtering")?;
3601 let mut stages = Vec::new();
3602 for level in (0..levels).rev() {
3603 let (level_width, level_height) = level_dims[level as usize];
3604 let shift_input = level_images[level as usize].as_matrix();
3605 let shift_output: &Matrix = if level == 0 {
3606 output.as_matrix()
3607 } else {
3608 &workspaces[level as usize - 1]
3609 };
3610 let (shift_seed, seed_width, seed_height, init_mode) = if level + 1 == levels {
3613 (shift_input, level_width, level_height, 0u32)
3614 } else {
3615 let (seed_width, seed_height) = level_dims[level as usize + 1];
3616 (&workspaces[level as usize], seed_width, seed_height, 1u32)
3617 };
3618 let pass_buffers = [
3619 BufferBinding::read(shift_input.storage()),
3620 BufferBinding::read(shift_seed.storage()),
3621 BufferBinding::write(shift_output.storage()),
3622 ];
3623 let pass_push = [
3624 PushConstant::U32(batch),
3625 PushConstant::U32(channels),
3626 PushConstant::U32(level_height),
3627 PushConstant::U32(level_width),
3628 PushConstant::U32(seed_width),
3629 PushConstant::U32(seed_height),
3630 PushConstant::U32(spatial_radius),
3631 PushConstant::U32(5),
3632 PushConstant::U32(init_mode),
3633 PushConstant::F32(range_radius_sqr),
3634 ];
3635 stages.push((
3636 KernelId::ImageMeanShiftPassF32,
3637 pass_buffers.to_vec(),
3638 pass_push.to_vec(),
3639 [level_width.div_ceil(16), level_height.div_ceil(16), batch],
3640 ));
3641 }
3642 let attributes = [
3643 float("sp", sp),
3644 float("sr", sr),
3645 unsigned("max_level", max_level),
3646 ];
3647 let dispatches: Vec<ComputeDispatch> = stages
3648 .iter()
3649 .map(
3650 |(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3651 kernel: *kernel,
3652 buffers: buffers.as_slice(),
3653 push_constants: push_constants.as_slice(),
3654 workgroups: *workgroups,
3655 indirect: None,
3656 },
3657 )
3658 .collect();
3659 runtime.record_image_split_semantic(
3660 &dispatches,
3661 ImageSemanticDispatch {
3662 contract: crate::core::operation::image::PYR_MEAN_SHIFT_FILTERING,
3663 inputs: &[ImageSemanticInput::Image(input)],
3664 outputs: &[ImageSemanticOutput::Image(&output)],
3665 attributes: &attributes,
3666 },
3667 )?;
3668 Ok(output)
3669}
3670
3671fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
3672 if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
3673 {
3674 return Err(Error::invalid_argument(format!(
3675 "{operation} requires an FP32 NCHW or CHW image"
3676 )));
3677 }
3678 let values = [
3679 input.batch_size(),
3680 input.channels(),
3681 input.height(),
3682 input.width(),
3683 ];
3684 if values.contains(&0) {
3685 return Err(Error::invalid_argument(format!(
3686 "{operation} requires a nonempty image"
3687 )));
3688 }
3689 Ok((
3690 u32::try_from(values[0]).map_err(|_| Error::out_of_range("image batch exceeds u32"))?,
3691 u32::try_from(values[1]).map_err(|_| Error::out_of_range("image channels exceed u32"))?,
3692 u32::try_from(values[2]).map_err(|_| Error::out_of_range("image height exceeds u32"))?,
3693 u32::try_from(values[3]).map_err(|_| Error::out_of_range("image width exceeds u32"))?,
3694 ))
3695}
3696
3697fn allocate_like(input: &Image, operation: &str) -> Result<Image> {
3698 let elements = input.as_matrix().num_elements();
3699 u32::try_from(elements)
3700 .map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
3701 let matrix = Matrix::allocate(
3702 input.runtime(),
3703 input.as_matrix().shape().to_vec(),
3704 elements,
3705 DType::F32,
3706 )?;
3707 Image::new(matrix, input.layout(), input.format())
3708}
3709
3710fn float(name: &str, value: f32) -> OpAttribute {
3711 OpAttribute::Float {
3712 name: name.into(),
3713 value: f64::from(value),
3714 }
3715}
3716fn unsigned(name: &str, value: u32) -> OpAttribute {
3717 OpAttribute::UnsignedInteger {
3718 name: name.into(),
3719 value: u64::from(value),
3720 }
3721}
3722fn enumeration(name: &str, value: &str) -> OpAttribute {
3723 OpAttribute::Enum {
3724 name: name.into(),
3725 value: value.into(),
3726 }
3727}
3728
3729fn validate_accumulation_pair(
3730 first: &Image,
3731 second: &Image,
3732 operation: &str,
3733) -> Result<(u32, u32, u32, u32)> {
3734 let extent = image_extent(first, operation)?;
3735 if second.as_matrix().shape() != first.as_matrix().shape()
3736 || second.layout() != first.layout()
3737 || second.format() != first.format()
3738 || second.dtype() != first.dtype()
3739 {
3740 return Err(Error::invalid_argument(format!(
3741 "{operation} requires identically shaped FP32 images"
3742 )));
3743 }
3744 Ok(extent)
3745}