Skip to main content

oa/image/
statistics.gen.rs

1// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
2// schema=image.json schema_version=1 generator_version=64
3// schema_sha256=b49cf13c5c000ebf985020b5b9eb0a98ddc2d64d8757d5cc3b5cb39d7aecbf00
4//! Per-plane image statistics and histogram metrics.
5
6use crate::{
7	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
8	runtime::{
9		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10		KernelId, PushConstant,
11	},
12};
13
14/// Accumulate a per-plane histogram over an FP32 NCHW or CHW image.
15///
16/// Each `(batch, channel)` plane contributes one row of `bins` buckets to the
17/// U32 result whose leading dimensions mirror the image; `[B,C,H,W]` and
18/// `[C,H,W]` inputs produce `[B,C,bins]` and `[C,bins]` results. Values below
19/// `lower` or at or above `upper` are ignored; in-range values map uniformly
20/// onto `[0, bins)`. The accumulator is cleared inside the operation, so a
21/// captured plan replays the same counts.
22///
23/// # Errors
24///
25/// Returns an error unless `bins` is in `1..=256`, `lower` and `upper` are
26/// finite with `lower < upper`, the image is nonempty FP32 NCHW/CHW, and all
27/// sizes fit the shader ABI.
28pub 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
107/// Equalize a normalized FP32 image histogram per `(batch, channel)` plane.
108///
109/// Pixel values are quantized into 256 uniform buckets over `[0, 1]`, the
110/// per-plane cumulative distribution is spread back over `[0, 1]` following
111/// the `equalizeHist` contract, and the result keeps the input layout and
112/// format. Values outside `[0, 1]` clamp into the edge buckets.
113///
114/// # Errors
115///
116/// Returns an error unless the image is nonempty FP32 NCHW/CHW and all
117/// sizes fit the shader ABI.
118pub 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/// Row-wise histogram comparison metric used by [`compare_hist`].
222#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub enum HistogramComparison {
224	/// Pearson correlation between centered rows; `1.0` is a perfect match.
225	#[default]
226	Correlation,
227	/// Chi-square distance over paired buckets; `0.0` is a perfect match.
228	ChiSquare,
229	/// Normalized per-bucket minimum sum; `1.0` is a perfect match.
230	Intersection,
231	/// Bhattacharyya distance between normalized rows; `0.0` is a perfect match.
232	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
255/// Compare two same-shape U32 histogram matrices row by row.
256///
257/// The last dimension is the bucket axis; every leading index is an
258/// independent row, so `[B,C,bins]` histograms produce a `[B,C]` FP32 score
259/// matrix. Correlation, chi-square, intersection, and Bhattacharyya follow
260/// the OpenCV `compareHist` formulas; degenerate rows return `0.0` rather
261/// than propagating a zero denominator.
262///
263/// # Errors
264///
265/// Returns an error unless both inputs are same-shape nonempty U32 matrices
266/// of rank at least two on one runtime, and all sizes fit the shader ABI.
267pub 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/// Histogram-driven threshold selection used by [`threshold_auto`].
331#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
332pub enum AutoThreshold {
333	/// Maximize between-class variance following `THRESH_OTSU`.
334	#[default]
335	Otsu,
336	/// Maximum-distance triangle construction following `THRESH_TRIANGLE`.
337	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
356/// Binary-threshold an FP32 image with a histogram-selected level.
357///
358/// Each `(batch, channel)` plane is quantized into 256 uniform buckets
359/// over `[0, 1]`; the Otsu or Triangle method selects one threshold per
360/// plane following the OpenCV `THRESH_OTSU`/`THRESH_TRIANGLE` contracts,
361/// and pixels strictly above it produce `max_value` while all others
362/// produce `0.0`. Returns the thresholded image together with the
363/// per-plane threshold Matrix shaped like the leading dimensions.
364///
365/// # Errors
366///
367/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
368/// `max_value` is finite, and all sizes fit the shader ABI.
369pub 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
488/// Compute the per-plane summed-area table of an FP32 image.
489///
490/// Following the `integral` contract, the result is a `(height + 1)`
491/// x `(width + 1)` FP32 Matrix per `(batch, channel)` plane whose
492/// zero row and column border the inclusive prefix sums: element
493/// `(y, x)` holds the sum over source pixels `[0, y) x [0, x)`. The
494/// leading dimensions are preserved ahead of the enlarged spatial
495/// extents.
496///
497/// # Errors
498///
499/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
500/// enlarged extents stay nonzero, and all sizes fit the shader ABI.
501pub 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
562/// Back-project a per-plane U32 histogram onto an FP32 image.
563///
564/// Each pixel is quantized with the `calc_hist` rule over
565/// `[lower, upper)` into `bins` buckets taken from the histogram's
566/// last dimension; the output pixel carries the histogram count as
567/// an FP32 value, or `0.0` when the source falls outside the range.
568/// Histogram leading dimensions must equal the image's leading
569/// plane dimensions, following `calcBackProject`.
570///
571/// # Errors
572///
573/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
574/// the histogram is a nonempty U32 Matrix of matching leading
575/// shape, `lower`/`upper` are finite with `lower < upper`, and all
576/// sizes fit the shader ABI.
577pub 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
650/// Contrast-limited adaptive histogram equalization per plane.
651///
652/// Each plane is split into `tile_width` x `tile_height` tiles,
653/// quantized into 256 uniform buckets over `[0, 1]`, clipped at
654/// `clip_limit` times the per-bin average with the excess spread
655/// uniformly, and remapped through bilinear-interpolated tile
656/// lookup tables following the `CLAHE` contract.
657///
658/// # Errors
659///
660/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
661/// `clip_limit` is finite and positive, both tile extents are
662/// nonzero, and all sizes fit the shader ABI.
663pub 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
796/// Add one image to a running accumulation image elementwise,
797/// following `accumulate`. Both images must share shape, layout,
798/// and format; the result is a fresh F32 image, not an in-place
799/// update.
800///
801/// # Errors
802///
803/// Returns an error unless both images are nonempty FP32
804/// NCHW/CHW images with identical shape, layout, and format.
805pub 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
843/// Blend an image into a running average as
844/// `input * alpha + accumulator * (1 - alpha)` per element,
845/// following `accumulateWeighted`.
846///
847/// # Errors
848///
849/// Returns an error unless both images are nonempty FP32
850/// NCHW/CHW images with identical shape, layout, and format and
851/// `alpha` is finite.
852pub 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
897/// Compute the ten spatial moments `m00, m10, m01, m20, m11, m02,
898/// m30, m21, m12, m03` per image plane through a serial per-plane
899/// reduction, following `cv::moments`. The result Matrix carries
900/// the image's leading plane dimensions plus a final extent-10
901/// moment dimension.
902///
903/// # Errors
904///
905/// Returns an error unless the image is a nonempty FP32
906/// NCHW/CHW image and all sizes fit the shader ABI.
907pub 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
949/// Peak signal-to-noise ratio per image plane in decibels,
950/// following `cv::PSNR`: `10 * log10(peak^2 / mse)` through a
951/// serial per-plane reduction, `+inf` when the planes match
952/// exactly. The result Matrix carries the image's leading plane
953/// dimensions.
954///
955/// # Errors
956///
957/// Returns an error unless both images are nonempty FP32
958/// NCHW/CHW images with identical shape, layout, and format and
959/// `peak_value` is finite and positive.
960pub 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
1006/// Global structural similarity per image plane through a serial
1007/// per-plane reduction of means, variances, and covariance with
1008/// the standard `K1=0.01, K2=0.03` constants over a `[0, 1]`
1009/// dynamic range, following the SSIM index of Wang et al. rather
1010/// than OpenCV's windowed map. The result Matrix carries the
1011/// image's leading plane dimensions.
1012///
1013/// # Errors
1014///
1015/// Returns an error unless both images are nonempty FP32
1016/// NCHW/CHW images with identical shape, layout, and format.
1017pub 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/// Template-match score metric used by [`match_template`].
1057#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1058pub enum MatchTemplate {
1059	/// `TM_SQDIFF` squared difference.
1060	#[default]
1061	Sqdiff,
1062	/// `TM_SQDIFF_NORMED` normalized squared difference.
1063	SqdiffNormed,
1064	/// `TM_CCORR` cross-correlation.
1065	Ccorr,
1066	/// `TM_CCORR_NORMED` normalized cross-correlation.
1067	CcorrNormed,
1068	/// `TM_CCOEFF` correlation coefficient.
1069	Ccoeff,
1070	/// `TM_CCOEFF_NORMED` normalized correlation coefficient.
1071	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
1098/// Slide a single-plane template over each image plane and write the
1099/// per-position match score to a Matrix, following `matchTemplate`.
1100/// The template's channel count must equal the input's; the output
1101/// carries the input's leading plane dimensions plus
1102/// `(height - th + 1) x (width - tw + 1)` score elements computed by
1103/// a serial per-position reduction over the template window.
1104///
1105/// # Errors
1106///
1107/// Returns an error unless both images are nonempty FP32 NCHW/CHW
1108/// images with matching channel counts, a single-plane template no
1109/// larger than the image planes, and sizes that fit the shader ABI.
1110pub 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/// Neighborhood connectivity used by [`connected_components`].
1188#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1189pub enum Connectivity {
1190	/// 4-connected cross neighborhood.
1191	Four,
1192	/// 8-connected full neighborhood.
1193	#[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
1213/// Connected-component labeling per plane, following
1214/// `connectedComponents`: every pixel above `threshold` is a
1215/// foreground candidate and receives a unique initial label;
1216/// bounded min-label propagation merges neighbors under the
1217/// selected connectivity (4 or 8). The U32 output carries
1218/// plane x height x width labels with `u32::MAX` on background
1219/// pixels. `propagation_passes` bounds label propagation (zero
1220/// selects `height + width` per plane); components with
1221/// diameters beyond the bound resolve to sub-components.
1222///
1223/// # Errors
1224///
1225/// Returns an error unless the image is a nonempty FP32
1226/// NCHW/CHW image and `threshold` is finite.
1227pub 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/// Distance metric used by [`distance_transform`].
1321#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1322pub enum DistanceType {
1323	/// 4-neighborhood unit-weight chamfer (exact Manhattan).
1324	L1,
1325	/// 8-neighborhood 1/sqrt(2) chamfer approximation.
1326	#[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
1346/// Distance transform per plane, following `distanceTransform`:
1347/// every pixel above `threshold` measures the chamfer distance
1348/// to the nearest background pixel. `DistanceType::L1` uses a
1349/// 4-neighborhood with unit weights (exact Manhattan distance);
1350/// `DistanceType::L2` uses an 8-neighborhood with weights
1351/// 1 / sqrt(2), the classic 3x3 chamfer approximation. The F32
1352/// output carries plane x height x width distances, zero on
1353/// background. `propagation_passes` bounds the relaxation
1354/// (zero selects `height + width` per plane, the worst-case
1355/// propagation distance).
1356///
1357/// # Errors
1358///
1359/// Returns an error unless the image is a nonempty FP32
1360/// NCHW/CHW image and `threshold` is finite.
1361pub 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
1454/// Standard Hough line transform per plane, following
1455/// `HoughLines`: pixels above `edge_threshold` vote into a
1456/// (theta x rho) accumulator quantized by `theta_step`
1457/// (degrees over [0, 180)) and `rho_step`. Accumulator cells
1458/// reaching `threshold` votes that are strict local maxima in
1459/// their 3x3 theta-rho neighborhood emit lines. The F32 output
1460/// carries plane x `max_lines` x 3 rows of (rho, theta degrees,
1461/// votes) in compacted unsorted order; unused rows are zero.
1462///
1463/// # Errors
1464///
1465/// Returns an error unless the image is a nonempty FP32
1466/// NCHW/CHW image, `edge_threshold`/`rho_step`/`theta_step`
1467/// are finite, `rho_step`/`theta_step` are positive,
1468/// `theta_step` does not exceed 180, and `max_lines` is
1469/// nonzero.
1470pub 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/// Probabilistic Hough segment transform per plane, following
1615/// `HoughLinesP`: votes accumulate as in `hough_lines`, strict
1616/// local-maxima cells above `threshold` emit candidate lines,
1617/// and each candidate is walked along its direction to find
1618/// the dominant contiguous edge run that tolerates gaps of up
1619/// to `max_line_gap` pixels and reaches `min_line_length`.
1620/// The F32 output carries plane x `max_lines` x 4 rows of
1621/// (x1, y1, x2, y2) endpoints; line slots without a qualifying
1622/// run are zero.
1623///
1624/// # Errors
1625///
1626/// Returns an error unless the image is a nonempty FP32
1627/// NCHW/CHW image, `edge_threshold`/`rho_step`/`theta_step`
1628/// are finite, `rho_step`/`theta_step` are positive,
1629/// `theta_step` does not exceed 180, `min_line_length` is
1630/// nonnegative, and `max_lines` is nonzero.
1631#[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
1817/// External contour extraction per plane, following `findContours`
1818/// with `RETR_EXTERNAL` semantics: foreground pixels above
1819/// `threshold` are labeled as connected components under the
1820/// selected connectivity, each component's minimum-index
1821/// boundary pixel seeds a Moore-neighbor trace that emits an
1822/// ordered `(x, y)` point list. Returns an F32
1823/// `[planes, max_contours, max_points, 2]` point matrix and a U32
1824/// `[planes, max_contours]` length matrix; unused slots stay zero.
1825/// `max_points` bounds each contour (zero selects
1826/// `4 * (height + width)`; longer contours truncate), and
1827/// `max_contours` bounds the per-plane contour count.
1828/// `propagation_passes` bounds component labeling (zero selects
1829/// `height + width`). Contour order and slot assignment are
1830/// unspecified across planes.
1831///
1832/// # Errors
1833///
1834/// Returns an error unless the image is a nonempty FP32
1835/// NCHW/CHW image, `threshold` is finite, and `max_contours` is
1836/// nonzero.
1837pub 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/// Corner response function used by [`corner_score`].
2049#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2050pub enum CornerScore {
2051	/// Harris response `det(M) - k * trace(M)^2` over the windowed second moments.
2052	#[default]
2053	Harris,
2054	/// Shi-Tomasi smallest-eigenvalue response `lambda_min(M)`.
2055	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
2074/// Per-pixel corner response over each plane: 3x3 Sobel gradients feed
2075/// windowed second moments `M = [sum Ix^2, sum IxIy; sum IxIy, sum Iy^2]`
2076/// inside a `block_size` x `block_size` box. `Harris` emits
2077/// `det(M) - k * trace(M)^2`; `MinEigen` emits the smaller eigenvalue
2078/// of `M` (Shi-Tomasi). Borders reflect101 like `cornerHarris`.
2079///
2080/// The response map shares the input geometry; combine with a local
2081/// max pass for candidate keypoints.
2082///
2083/// # Errors
2084///
2085/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
2086/// image, `k` is finite, and `block_size` is odd and at least 3.
2087pub 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
2184/// FAST corner response per plane on the radius-3 circle of 16
2185/// samples: for each pixel the score is the largest deviation `t`
2186/// such that `arc_length` contiguous circle samples are all brighter
2187/// than `center + t` or all darker than `center - t`, zero when no
2188/// such arc exists. Pixels within 3 of the border score 0.0.
2189///
2190/// The response map shares the input geometry; non-maximum
2191/// suppression and thresholding select candidate keypoints.
2192///
2193/// # Errors
2194///
2195/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
2196/// image and `arc_length` is in `9..=16`.
2197pub 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
2238/// Brute-force Hamming descriptor matching: for each row of `query`,
2239/// scan every row of `train` and record the two smallest XOR popcount
2240/// distances. Both inputs are U8 `[N, D]` matrices sharing `D`.
2241///
2242/// Returns an F32 `[N_query, 4]` matrix whose rows are
2243/// `(best_index, best_distance, second_index, second_distance)`,
2244/// mirroring `BFMatcher.knnMatch(k=2)` on `NORM_HAMMING`. Rows with
2245/// fewer than two candidates fill unused columns with `-1`.
2246///
2247/// # Errors
2248///
2249/// Returns an error unless both inputs are nonempty U8 matrices with
2250/// identical trailing descriptor width and at least one row each.
2251pub 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
2319/// Bounded `goodFeaturesToTrack` selection over a per-plane corner
2320/// response map: pixels scoring above `quality * plane_max` survive
2321/// radius suppression when no strictly stronger candidate lies within
2322/// `min_distance` (ties break by lower linear index). Survivors claim
2323/// atomic slots per plane up to `max_corners`; slot order is
2324/// unsorted unlike OpenCV's score-descending emission.
2325///
2326/// Returns `(keypoints, counts)`: an F32 `[planes, max_corners, 3]`
2327/// matrix of `(x, y, score)` rows holding `min(count, max_corners)`
2328/// valid entries followed by zeros, and a U32 `[planes]` survivor
2329/// count matrix (may exceed `max_corners` when slots truncate).
2330/// A `max_corners` of zero selects `height * width` per plane.
2331///
2332/// # Errors
2333///
2334/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
2335/// image and both `quality` and `min_distance` are finite with
2336/// quality in [0, 1] and min_distance >= 0.
2337pub 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
2496/// Bounded ORB keypoint + steered rBRIEF descriptor pipeline,
2497/// following `ORB::detectAndCompute`. Each pyramid level runs the
2498/// existing corner_fast + good_features_to_track stages (FAST-9
2499/// response, quality-thresholded radius suppression), then a
2500/// describe stage computes the intensity-centroid orientation over
2501/// a 31x31 patch and a 256-bit steered BRIEF descriptor using the
2502/// OpenCV bit_pattern_31_ test pairs. Scale factor is 2x per level
2503/// via pyr_down.
2504///
2505/// Returns `(keypoints, descriptors, counts)`: an F32
2506/// `[planes, max_features, 6]` matrix of `(x, y, angle_radians,
2507/// score, level, size)` rows in level-0 coordinates, a U32
2508/// `[planes, max_features, 8]` matrix of descriptor words, and a
2509/// U32 `[planes]` claimed-slot count (may exceed `max_features`).
2510/// Slot order is unordered across a level's survivors. A
2511/// `max_features` of zero selects `height * width` per plane.
2512///
2513/// # Errors
2514///
2515/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
2516/// image, `levels` >= 1, `edge` >= 18 (rotated test-pair support),
2517/// quality is in [0, 1], and min_distance is finite and >= 0.
2518pub 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
2677fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
2678	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
2679	{
2680		return Err(Error::invalid_argument(format!(
2681			"{operation} requires an FP32 NCHW or CHW image"
2682		)));
2683	}
2684	let values = [
2685		input.batch_size(),
2686		input.channels(),
2687		input.height(),
2688		input.width(),
2689	];
2690	if values.contains(&0) {
2691		return Err(Error::invalid_argument(format!(
2692			"{operation} requires a nonempty image"
2693		)));
2694	}
2695	Ok((
2696		u32::try_from(values[0]).map_err(|_| Error::out_of_range("image batch exceeds u32"))?,
2697		u32::try_from(values[1]).map_err(|_| Error::out_of_range("image channels exceed u32"))?,
2698		u32::try_from(values[2]).map_err(|_| Error::out_of_range("image height exceeds u32"))?,
2699		u32::try_from(values[3]).map_err(|_| Error::out_of_range("image width exceeds u32"))?,
2700	))
2701}
2702
2703fn allocate_like(input: &Image, operation: &str) -> Result<Image> {
2704	let elements = input.as_matrix().num_elements();
2705	u32::try_from(elements)
2706		.map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
2707	let matrix = Matrix::allocate(
2708		input.runtime(),
2709		input.as_matrix().shape().to_vec(),
2710		elements,
2711		DType::F32,
2712	)?;
2713	Image::new(matrix, input.layout(), input.format())
2714}
2715
2716fn float(name: &str, value: f32) -> OpAttribute {
2717	OpAttribute::Float {
2718		name: name.into(),
2719		value: f64::from(value),
2720	}
2721}
2722fn unsigned(name: &str, value: u32) -> OpAttribute {
2723	OpAttribute::UnsignedInteger {
2724		name: name.into(),
2725		value: u64::from(value),
2726	}
2727}
2728fn enumeration(name: &str, value: &str) -> OpAttribute {
2729	OpAttribute::Enum {
2730		name: name.into(),
2731		value: value.into(),
2732	}
2733}
2734
2735fn validate_accumulation_pair(
2736	first: &Image,
2737	second: &Image,
2738	operation: &str,
2739) -> Result<(u32, u32, u32, u32)> {
2740	let extent = image_extent(first, operation)?;
2741	if second.as_matrix().shape() != first.as_matrix().shape()
2742		|| second.layout() != first.layout()
2743		|| second.format() != first.format()
2744		|| second.dtype() != first.dtype()
2745	{
2746		return Err(Error::invalid_argument(format!(
2747			"{operation} requires identically shaped FP32 images"
2748		)));
2749	}
2750	Ok(extent)
2751}