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=850fff7da094fda90deb1885822908eb59de961a0e67423335fc6de4de68b058
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
2677/// Sparse Lucas-Kanade optical flow with image pyramids,
2678/// following `calcOpticalFlowPyrLK`. Each pyramid level runs
2679/// one `flow_lk_refine` dispatch from the coarsest level to
2680/// level 0 over `2 * window + 1` windows with the same point
2681/// set applied to every image plane; the tracked estimate
2682/// carries between levels in a `[planes, N, 2]` state buffer
2683/// and the last level writes status and error maps.
2684///
2685/// `points` is an F32 `[N, 2]` matrix of `(x, y)` source
2686/// positions in level-0 pixel coordinates. `window` is the
2687/// half-window radius. Returns `(next_points, status, error)`:
2688/// the tracked F32 `[planes, N, 2]` positions, an F32
2689/// `[planes, N]` found/lost mask, and an F32 `[planes, N]`
2690/// RMS patch-residual error; status 0 rows carry the final
2691/// unconverged estimate.
2692///
2693/// # Errors
2694///
2695/// Returns an error unless both images are nonempty FP32
2696/// NCHW/CHW images with identical shape, layout, and format,
2697/// `points` is a nonempty F32 `[N, 2]` matrix, `levels`,
2698/// `window`, and `iterations` are >= 1, `min_eigen` is finite
2699/// and positive, and the coarsest level still fits the full
2700/// window.
2701pub fn optical_flow_pyr_lk(
2702	previous: &Image,
2703	next: &Image,
2704	points: &Matrix,
2705	levels: u32,
2706	window: u32,
2707	iterations: u32,
2708	min_eigen: f32,
2709) -> Result<(Matrix, Matrix, Matrix)> {
2710	let (batch, channels, image_height, image_width) =
2711		validate_accumulation_pair(previous, next, "image::optical_flow_pyr_lk")?;
2712	if levels == 0 || window == 0 || iterations == 0 || !min_eigen.is_finite() || min_eigen <= 0.0 {
2713		return Err(Error::invalid_argument(
2714			"image::optical_flow_pyr_lk requires levels/window/iterations >= 1 and finite min_eigen > 0",
2715		));
2716	}
2717	if points.dtype() != DType::F32
2718		|| points.shape().len() != 2
2719		|| points.shape()[0] == 0
2720		|| points.shape()[1] != 2
2721	{
2722		return Err(Error::invalid_argument(
2723			"image::optical_flow_pyr_lk requires a nonempty F32 [N, 2] points matrix",
2724		));
2725	}
2726	let point_count = u32::try_from(points.shape()[0])
2727		.map_err(|_| Error::out_of_range("image::optical_flow_pyr_lk point count exceeds u32"))?;
2728	let support = window
2729		.checked_mul(2)
2730		.and_then(|value| value.checked_add(1))
2731		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk window exceeds u32"))?;
2732	let plane_count = batch
2733		.checked_mul(channels)
2734		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk plane count exceeds u32"))?;
2735	let state_elements = plane_count
2736		.checked_mul(point_count)
2737		.and_then(|count| count.checked_mul(2))
2738		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk state size exceeds u32"))?;
2739	let map_elements = plane_count
2740		.checked_mul(point_count)
2741		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk map size exceeds u32"))?;
2742	let contract = crate::core::operation::image::OPTICAL_FLOW_PYR_LK;
2743	let mut previous_levels = Vec::with_capacity(levels as usize);
2744	let mut next_levels = Vec::with_capacity(levels as usize);
2745	let mut level_dims = Vec::with_capacity(levels as usize);
2746	previous_levels.push(previous.clone());
2747	next_levels.push(next.clone());
2748	level_dims.push((image_width, image_height));
2749	for _ in 1..levels {
2750		previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
2751			|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
2752		)?)?);
2753		next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
2754			|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
2755		)?)?);
2756		let (width, height) = level_dims[level_dims.len() - 1];
2757		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
2758	}
2759	let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
2760	if coarsest_width < support || coarsest_height < support {
2761		return Err(Error::invalid_argument(
2762			"image::optical_flow_pyr_lk requires the coarsest level to fit the full window",
2763		));
2764	}
2765	let next_points = Matrix::allocate(
2766		previous.runtime(),
2767		vec![plane_count as usize, point_count as usize, 2],
2768		state_elements as usize,
2769		DType::F32,
2770	)?;
2771	let status = Matrix::allocate(
2772		previous.runtime(),
2773		vec![plane_count as usize, point_count as usize],
2774		map_elements as usize,
2775		DType::F32,
2776	)?;
2777	let error = Matrix::allocate(
2778		previous.runtime(),
2779		vec![plane_count as usize, point_count as usize],
2780		map_elements as usize,
2781		DType::F32,
2782	)?;
2783	let mut stages = Vec::with_capacity(levels as usize);
2784	for level in (0..levels).rev() {
2785		let previous_level = &previous_levels[level as usize];
2786		let next_level = &next_levels[level as usize];
2787		let (level_width, level_height) = level_dims[level as usize];
2788		let level_scale = 0.5f32.powi(level as i32);
2789		let initialize = u32::from(level == levels - 1);
2790		let finalize = u32::from(level == 0);
2791		let refine_buffers = [
2792			BufferBinding::read(previous_level.storage()),
2793			BufferBinding::read(next_level.storage()),
2794			BufferBinding::read(points.storage()),
2795			BufferBinding::read_write(next_points.storage()),
2796			BufferBinding::write(status.storage()),
2797			BufferBinding::write(error.storage()),
2798		];
2799		let refine_push = [
2800			PushConstant::U32(batch),
2801			PushConstant::U32(channels),
2802			PushConstant::U32(point_count),
2803			PushConstant::U32(level_height),
2804			PushConstant::U32(level_width),
2805			PushConstant::U32(window),
2806			PushConstant::U32(iterations),
2807			PushConstant::U32(initialize),
2808			PushConstant::U32(finalize),
2809			PushConstant::F32(level_scale),
2810			PushConstant::F32(min_eigen),
2811		];
2812		stages.push((KernelId::ImageFlowLkRefineF32, refine_buffers, refine_push));
2813	}
2814	let attributes = [
2815		unsigned("levels", levels),
2816		unsigned("window", window),
2817		unsigned("iterations", iterations),
2818		float("min_eigen", min_eigen),
2819	];
2820	let dispatches: Vec<ComputeDispatch> = stages
2821		.iter()
2822		.map(|(kernel, buffers, push_constants)| ComputeDispatch {
2823			kernel: *kernel,
2824			buffers: buffers.as_slice(),
2825			push_constants: push_constants.as_slice(),
2826			workgroups: KernelId::ImageFlowLkRefineF32.linear_workgroups(plane_count * point_count),
2827			indirect: None,
2828		})
2829		.collect();
2830	previous.runtime().record_image_split_semantic(
2831		&dispatches,
2832		ImageSemanticDispatch {
2833			contract,
2834			inputs: &[
2835				ImageSemanticInput::Image(previous),
2836				ImageSemanticInput::Image(next),
2837				ImageSemanticInput::Matrix(points),
2838			],
2839			outputs: &[
2840				ImageSemanticOutput::Matrix(&next_points),
2841				ImageSemanticOutput::Matrix(&status),
2842				ImageSemanticOutput::Matrix(&error),
2843			],
2844			attributes: &attributes,
2845		},
2846	)?;
2847	Ok((next_points, status, error))
2848}
2849
2850/// Dense Farneback optical flow over a 2x image pyramid,
2851/// following `calcOpticalFlowFarneback`. Each level expands
2852/// both frames into polynomial coefficient maps through two
2853/// separable weighted-least-squares passes (`flow_expand_v`
2854/// then `flow_expand_h`), then relaxes the flow field with
2855/// `iterations` Jacobi `flow_update` dispatches over a
2856/// `2 * window + 1` averaging neighbourhood. The coarsest
2857/// level starts from a zero field; finer levels initialize
2858/// from the 2x-upsampled coarser solution.
2859///
2860/// `window` is the half-window radius of the update
2861/// averaging neighbourhood and `poly_n` the half-support of
2862/// the gaussian-weighted polynomial fit. Returns the F32
2863/// `[planes, 2, H, W]` flow field at level-0 resolution with
2864/// x displacement in channel 0 and y displacement in
2865/// channel 1.
2866///
2867/// # Errors
2868///
2869/// Returns an error unless both images are nonempty FP32
2870/// NCHW/CHW images with identical shape, layout, and format,
2871/// `levels`, `window`, `iterations`, and `poly_n` are >= 1,
2872/// `poly_sigma` is finite and positive, and the coarsest
2873/// level still fits the polynomial support.
2874pub fn optical_flow_farneback(
2875	previous: &Image,
2876	next: &Image,
2877	levels: u32,
2878	window: u32,
2879	iterations: u32,
2880	poly_n: u32,
2881	poly_sigma: f32,
2882) -> Result<Matrix> {
2883	let (batch, channels, image_height, image_width) =
2884		validate_accumulation_pair(previous, next, "image::optical_flow_farneback")?;
2885	if levels == 0
2886		|| window == 0
2887		|| iterations == 0
2888		|| poly_n == 0
2889		|| !poly_sigma.is_finite()
2890		|| poly_sigma <= 0.0
2891	{
2892		return Err(Error::invalid_argument(
2893			"image::optical_flow_farneback requires levels/window/iterations/poly_n >= 1 and finite poly_sigma > 0",
2894		));
2895	}
2896	let poly_support = poly_n
2897		.checked_mul(2)
2898		.and_then(|value| value.checked_add(1))
2899		.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback poly_n exceeds u32"))?;
2900	let plane_count = batch
2901		.checked_mul(channels)
2902		.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback plane count exceeds u32"))?;
2903	let contract = crate::core::operation::image::OPTICAL_FLOW_FARNEBACK;
2904	let mut previous_levels = Vec::with_capacity(levels as usize);
2905	let mut next_levels = Vec::with_capacity(levels as usize);
2906	let mut level_dims = Vec::with_capacity(levels as usize);
2907	previous_levels.push(previous.clone());
2908	next_levels.push(next.clone());
2909	level_dims.push((image_width, image_height));
2910	for _ in 1..levels {
2911		previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
2912			|| Error::internal("image::optical_flow_farneback pyramid level missing"),
2913		)?)?);
2914		next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
2915			|| Error::internal("image::optical_flow_farneback pyramid level missing"),
2916		)?)?);
2917		let (width, height) = level_dims[level_dims.len() - 1];
2918		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
2919	}
2920	let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
2921	if coarsest_width < poly_support || coarsest_height < poly_support {
2922		return Err(Error::invalid_argument(
2923			"image::optical_flow_farneback requires the coarsest level to fit the polynomial support",
2924		));
2925	}
2926	let workspace_elements = |planes: u32| -> Result<usize> {
2927		Ok(
2928			planes
2929				.checked_mul(image_height)
2930				.and_then(|count| count.checked_mul(image_width))
2931				.ok_or_else(|| {
2932					Error::out_of_range("image::optical_flow_farneback workspace size exceeds u32")
2933				})? as usize,
2934		)
2935	};
2936	let moment_shape = vec![
2937		plane_count as usize,
2938		3,
2939		image_height as usize,
2940		image_width as usize,
2941	];
2942	let poly_shape = vec![
2943		plane_count as usize,
2944		5,
2945		image_height as usize,
2946		image_width as usize,
2947	];
2948	let flow_shape = vec![
2949		plane_count as usize,
2950		2,
2951		image_height as usize,
2952		image_width as usize,
2953	];
2954	let three_planes = plane_count.checked_mul(3).ok_or_else(|| {
2955		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2956	})?;
2957	let five_planes = plane_count.checked_mul(5).ok_or_else(|| {
2958		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2959	})?;
2960	let two_planes = plane_count.checked_mul(2).ok_or_else(|| {
2961		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
2962	})?;
2963	let moments_a = Matrix::allocate(
2964		previous.runtime(),
2965		moment_shape.clone(),
2966		workspace_elements(three_planes)?,
2967		DType::F32,
2968	)?;
2969	let moments_b = Matrix::allocate(
2970		previous.runtime(),
2971		moment_shape,
2972		workspace_elements(three_planes)?,
2973		DType::F32,
2974	)?;
2975	let poly1 = Matrix::allocate(
2976		previous.runtime(),
2977		poly_shape.clone(),
2978		workspace_elements(five_planes)?,
2979		DType::F32,
2980	)?;
2981	let poly2 = Matrix::allocate(
2982		previous.runtime(),
2983		poly_shape,
2984		workspace_elements(five_planes)?,
2985		DType::F32,
2986	)?;
2987	let flow_a = Matrix::allocate(
2988		previous.runtime(),
2989		flow_shape.clone(),
2990		workspace_elements(two_planes)?,
2991		DType::F32,
2992	)?;
2993	let flow_b = Matrix::allocate(
2994		previous.runtime(),
2995		flow_shape.clone(),
2996		workspace_elements(two_planes)?,
2997		DType::F32,
2998	)?;
2999	let flow = Matrix::allocate(
3000		previous.runtime(),
3001		flow_shape,
3002		workspace_elements(two_planes)?,
3003		DType::F32,
3004	)?;
3005	let mut stages = Vec::new();
3006	let mut parent: Option<(&Matrix, u32, u32, bool)> = None;
3007	for level in (0..levels).rev() {
3008		let (level_width, level_height) = level_dims[level as usize];
3009		{
3010			let expand_input = &previous_levels[level as usize];
3011			let expand_output = &moments_a;
3012			let expand_v_buffers = [
3013				BufferBinding::read(expand_input.storage()),
3014				BufferBinding::write(expand_output.storage()),
3015			];
3016			let expand_v_push = [
3017				PushConstant::U32(batch),
3018				PushConstant::U32(channels),
3019				PushConstant::U32(level_height),
3020				PushConstant::U32(level_width),
3021				PushConstant::U32(poly_n),
3022				PushConstant::F32(poly_sigma),
3023			];
3024			stages.push((
3025				KernelId::ImageFlowExpandVF32,
3026				expand_v_buffers.to_vec(),
3027				expand_v_push.to_vec(),
3028				[
3029					level_width.div_ceil(16),
3030					level_height.div_ceil(16),
3031					plane_count,
3032				],
3033			));
3034		}
3035		{
3036			let expand_input = &moments_a;
3037			let expand_output = &poly1;
3038			let expand_h_buffers = [
3039				BufferBinding::read(expand_input.storage()),
3040				BufferBinding::write(expand_output.storage()),
3041			];
3042			let expand_h_push = [
3043				PushConstant::U32(batch),
3044				PushConstant::U32(channels),
3045				PushConstant::U32(level_height),
3046				PushConstant::U32(level_width),
3047				PushConstant::U32(poly_n),
3048				PushConstant::F32(poly_sigma),
3049			];
3050			stages.push((
3051				KernelId::ImageFlowExpandHF32,
3052				expand_h_buffers.to_vec(),
3053				expand_h_push.to_vec(),
3054				[
3055					level_width.div_ceil(16),
3056					level_height.div_ceil(16),
3057					plane_count,
3058				],
3059			));
3060		}
3061		{
3062			let expand_input = &next_levels[level as usize];
3063			let expand_output = &moments_b;
3064			let expand_v_buffers = [
3065				BufferBinding::read(expand_input.storage()),
3066				BufferBinding::write(expand_output.storage()),
3067			];
3068			let expand_v_push = [
3069				PushConstant::U32(batch),
3070				PushConstant::U32(channels),
3071				PushConstant::U32(level_height),
3072				PushConstant::U32(level_width),
3073				PushConstant::U32(poly_n),
3074				PushConstant::F32(poly_sigma),
3075			];
3076			stages.push((
3077				KernelId::ImageFlowExpandVF32,
3078				expand_v_buffers.to_vec(),
3079				expand_v_push.to_vec(),
3080				[
3081					level_width.div_ceil(16),
3082					level_height.div_ceil(16),
3083					plane_count,
3084				],
3085			));
3086		}
3087		{
3088			let expand_input = &moments_b;
3089			let expand_output = &poly2;
3090			let expand_h_buffers = [
3091				BufferBinding::read(expand_input.storage()),
3092				BufferBinding::write(expand_output.storage()),
3093			];
3094			let expand_h_push = [
3095				PushConstant::U32(batch),
3096				PushConstant::U32(channels),
3097				PushConstant::U32(level_height),
3098				PushConstant::U32(level_width),
3099				PushConstant::U32(poly_n),
3100				PushConstant::F32(poly_sigma),
3101			];
3102			stages.push((
3103				KernelId::ImageFlowExpandHF32,
3104				expand_h_buffers.to_vec(),
3105				expand_h_push.to_vec(),
3106				[
3107					level_width.div_ceil(16),
3108					level_height.div_ceil(16),
3109					plane_count,
3110				],
3111			));
3112		}
3113		let mut estimate: &Matrix = &flow_a;
3114		let mut estimate_is_a = true;
3115		for iteration in 0..iterations {
3116			let (flow_in, init_mode, flow_in_width, flow_in_height, input_is_a) = if iteration == 0 {
3117				match parent {
3118					Some((buffer, width, height, is_a)) => (buffer, 1u32, width, height, is_a),
3119					None => (&flow_a, 0u32, level_width, level_height, true),
3120				}
3121			} else {
3122				(estimate, 2u32, level_width, level_height, estimate_is_a)
3123			};
3124			let output_is_flow = level == 0 && iteration + 1 == iterations;
3125			let flow_out: &Matrix = if output_is_flow {
3126				&flow
3127			} else if input_is_a {
3128				&flow_b
3129			} else {
3130				&flow_a
3131			};
3132			let update_buffers = [
3133				BufferBinding::read(poly1.storage()),
3134				BufferBinding::read(poly2.storage()),
3135				BufferBinding::read(flow_in.storage()),
3136				BufferBinding::write(flow_out.storage()),
3137			];
3138			let update_push = [
3139				PushConstant::U32(batch),
3140				PushConstant::U32(channels),
3141				PushConstant::U32(level_height),
3142				PushConstant::U32(level_width),
3143				PushConstant::U32(flow_in_height),
3144				PushConstant::U32(flow_in_width),
3145				PushConstant::U32(window),
3146				PushConstant::U32(init_mode),
3147			];
3148			stages.push((
3149				KernelId::ImageFlowUpdateF32,
3150				update_buffers.to_vec(),
3151				update_push.to_vec(),
3152				[
3153					level_width.div_ceil(16),
3154					level_height.div_ceil(16),
3155					plane_count,
3156				],
3157			));
3158			estimate = flow_out;
3159			estimate_is_a = !input_is_a;
3160		}
3161		parent = Some((estimate, level_width, level_height, estimate_is_a));
3162	}
3163	let attributes = [
3164		unsigned("levels", levels),
3165		unsigned("window", window),
3166		unsigned("iterations", iterations),
3167		unsigned("poly_n", poly_n),
3168		float("poly_sigma", poly_sigma),
3169	];
3170	let dispatches: Vec<ComputeDispatch> = stages
3171		.iter()
3172		.map(
3173			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3174				kernel: *kernel,
3175				buffers: buffers.as_slice(),
3176				push_constants: push_constants.as_slice(),
3177				workgroups: *workgroups,
3178				indirect: None,
3179			},
3180		)
3181		.collect();
3182	previous.runtime().record_image_split_semantic(
3183		&dispatches,
3184		ImageSemanticDispatch {
3185			contract,
3186			inputs: &[
3187				ImageSemanticInput::Image(previous),
3188				ImageSemanticInput::Image(next),
3189			],
3190			outputs: &[ImageSemanticOutput::Matrix(&flow)],
3191			attributes: &attributes,
3192		},
3193	)?;
3194	Ok(flow)
3195}
3196
3197/// Block-matching stereo disparity over the horizontal search
3198/// range [0, num_disparities), following cv::StereoBM. The
3199/// `stereo_sad` pass builds a [planes, num_disparities, H, W]
3200/// sum-of-absolute-differences volume over an odd block_size
3201/// window; `stereo_wta` then keeps the per-pixel argmin, applies
3202/// the `uniqueness` percent runner-up margin test (0 disables),
3203/// and refines the winner with a symmetric parabola on the
3204/// neighbouring costs. Pixels outside the border region where
3205/// the matching window fits for every disparity, and uniqueness
3206/// losers, are marked -1; the valid range otherwise starts at 0.
3207/// Returns the F32 [planes, 1, H, W] disparity map.
3208///
3209/// # Errors
3210///
3211/// Returns an error unless both images are nonempty FP32
3212/// NCHW/CHW images with identical shape, layout, and format,
3213/// num_disparities >= 1, block_size is odd and >= 3, and the
3214/// image fits the combined block and disparity support.
3215pub fn stereo_bm(
3216	left: &Image,
3217	right: &Image,
3218	num_disparities: u32,
3219	block_size: u32,
3220	uniqueness: u32,
3221) -> Result<Matrix> {
3222	let (batch, channels, image_height, image_width) =
3223		validate_accumulation_pair(left, right, "image::stereo_bm")?;
3224	if num_disparities == 0 || block_size < 3 || block_size.is_multiple_of(2) {
3225		return Err(Error::invalid_argument(
3226			"image::stereo_bm requires num_disparities >= 1 and an odd block_size >= 3",
3227		));
3228	}
3229	let support = block_size
3230		.checked_sub(1)
3231		.and_then(|value| value.checked_add(num_disparities))
3232		.ok_or_else(|| Error::out_of_range("image::stereo_bm support exceeds u32"))?;
3233	if image_width < support || image_height < block_size {
3234		return Err(Error::invalid_argument(
3235			"image::stereo_bm requires the image to fit the block and disparity support",
3236		));
3237	}
3238	let plane_count = batch
3239		.checked_mul(channels)
3240		.ok_or_else(|| Error::out_of_range("image::stereo_bm plane count exceeds u32"))?;
3241	let disp_count = plane_count
3242		.checked_mul(num_disparities)
3243		.ok_or_else(|| Error::out_of_range("image::stereo_bm disparity slots exceed u32"))?;
3244	let block_radius = block_size / 2;
3245	let plane_elements = (image_height as usize)
3246		.checked_mul(image_width as usize)
3247		.ok_or_else(|| Error::out_of_range("image::stereo_bm plane size exceeds u32"))?;
3248	let cost_volume = Matrix::allocate(
3249		left.runtime(),
3250		vec![
3251			plane_count as usize,
3252			num_disparities as usize,
3253			image_height as usize,
3254			image_width as usize,
3255		],
3256		plane_elements
3257			.checked_mul(disp_count as usize)
3258			.ok_or_else(|| Error::out_of_range("image::stereo_bm cost volume exceeds u32"))?,
3259		DType::F32,
3260	)?;
3261	let output = Matrix::allocate(
3262		left.runtime(),
3263		vec![
3264			plane_count as usize,
3265			1,
3266			image_height as usize,
3267			image_width as usize,
3268		],
3269		plane_elements
3270			.checked_mul(plane_count as usize)
3271			.ok_or_else(|| Error::out_of_range("image::stereo_bm output size exceeds u32"))?,
3272		DType::F32,
3273	)?;
3274	let contract = crate::core::operation::image::STEREO_BM;
3275	let mut stages = Vec::new();
3276	{
3277		let sad_buffers = [
3278			BufferBinding::read(left.storage()),
3279			BufferBinding::read(right.storage()),
3280			BufferBinding::write(cost_volume.storage()),
3281		];
3282		let sad_push = [
3283			PushConstant::U32(batch),
3284			PushConstant::U32(channels),
3285			PushConstant::U32(image_height),
3286			PushConstant::U32(image_width),
3287			PushConstant::U32(num_disparities),
3288			PushConstant::U32(block_radius),
3289		];
3290		stages.push((
3291			KernelId::ImageStereoSadF32,
3292			sad_buffers.to_vec(),
3293			sad_push.to_vec(),
3294			[
3295				image_width.div_ceil(16),
3296				image_height.div_ceil(16),
3297				disp_count,
3298			],
3299		));
3300	}
3301	{
3302		let wta_buffers = [
3303			BufferBinding::read(cost_volume.storage()),
3304			BufferBinding::write(output.storage()),
3305		];
3306		let wta_push = [
3307			PushConstant::U32(batch),
3308			PushConstant::U32(channels),
3309			PushConstant::U32(image_height),
3310			PushConstant::U32(image_width),
3311			PushConstant::U32(num_disparities),
3312			PushConstant::U32(block_radius),
3313			PushConstant::U32(uniqueness),
3314		];
3315		stages.push((
3316			KernelId::ImageStereoWtaF32,
3317			wta_buffers.to_vec(),
3318			wta_push.to_vec(),
3319			[
3320				image_width.div_ceil(16),
3321				image_height.div_ceil(16),
3322				plane_count,
3323			],
3324		));
3325	}
3326	let attributes = [
3327		unsigned("num_disparities", num_disparities),
3328		unsigned("block_size", block_size),
3329		unsigned("uniqueness", uniqueness),
3330	];
3331	let dispatches: Vec<ComputeDispatch> = stages
3332		.iter()
3333		.map(
3334			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3335				kernel: *kernel,
3336				buffers: buffers.as_slice(),
3337				push_constants: push_constants.as_slice(),
3338				workgroups: *workgroups,
3339				indirect: None,
3340			},
3341		)
3342		.collect();
3343	left.runtime().record_image_split_semantic(
3344		&dispatches,
3345		ImageSemanticDispatch {
3346			contract,
3347			inputs: &[
3348				ImageSemanticInput::Image(left),
3349				ImageSemanticInput::Image(right),
3350			],
3351			outputs: &[ImageSemanticOutput::Matrix(&output)],
3352			attributes: &attributes,
3353		},
3354	)?;
3355	Ok(output)
3356}
3357
3358/// Per-pixel reprojection of a disparity map into 3D
3359/// coordinates, following cv::reprojectImageTo3D. For each
3360/// pixel it evaluates (X, Y, Z, W) = Q * [x, y, disparity, 1]
3361/// with the row-major 4x4 F32 matrix `q`, then writes the
3362/// normalized coordinates X/W, Y/W, Z/W. `disparity` must be
3363/// F32 [planes, 1, H, W] (the stereo_bm output layout) and
3364/// `q` F32 [4, 4]; the homogeneous divide is unguarded, so a
3365/// degenerate last row surfaces as inf/NaN. Returns the F32
3366/// [planes, 3, H, W] coordinate map.
3367///
3368/// # Errors
3369///
3370/// Returns an error unless `disparity` is F32 with shape
3371/// [planes, 1, H, W] and `q` is F32 [4, 4] on the same
3372/// runtime.
3373pub fn reproject_image_to_3d(disparity: &Matrix, q: &Matrix) -> Result<Matrix> {
3374	if disparity.dtype() != DType::F32 || q.dtype() != DType::F32 {
3375		return Err(Error::invalid_argument(
3376			"image::reproject_image_to_3d requires F32 disparity and q matrices",
3377		));
3378	}
3379	if disparity.shape().len() != 4 || disparity.shape()[1] != 1 {
3380		return Err(Error::invalid_argument(
3381			"image::reproject_image_to_3d requires a [planes, 1, H, W] disparity matrix",
3382		));
3383	}
3384	if q.shape() != [4, 4] {
3385		return Err(Error::invalid_argument(
3386			"image::reproject_image_to_3d requires a [4, 4] q matrix",
3387		));
3388	}
3389	let plane_count = u32::try_from(disparity.shape()[0])
3390		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d plane count exceeds u32"))?;
3391	let height = u32::try_from(disparity.shape()[2])
3392		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d height exceeds u32"))?;
3393	let width = u32::try_from(disparity.shape()[3])
3394		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d width exceeds u32"))?;
3395	if plane_count == 0 || height == 0 || width == 0 {
3396		return Err(Error::invalid_argument(
3397			"image::reproject_image_to_3d requires a nonempty disparity matrix",
3398		));
3399	}
3400	let plane_elements = (height as usize)
3401		.checked_mul(width as usize)
3402		.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d plane size exceeds u32"))?;
3403	let output = Matrix::allocate(
3404		disparity.runtime(),
3405		vec![plane_count as usize, 3, height as usize, width as usize],
3406		plane_elements
3407			.checked_mul(3)
3408			.and_then(|count| count.checked_mul(plane_count as usize))
3409			.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d output size exceeds u32"))?,
3410		DType::F32,
3411	)?;
3412	let attributes = [];
3413	disparity.runtime().record_image_semantic(
3414		ComputeDispatch {
3415			kernel: KernelId::ImageReproject3dF32,
3416			buffers: &[
3417				BufferBinding::read(disparity.storage()),
3418				BufferBinding::read(q.storage()),
3419				BufferBinding::write(output.storage()),
3420			],
3421			push_constants: &[
3422				PushConstant::U32(plane_count),
3423				PushConstant::U32(1),
3424				PushConstant::U32(height),
3425				PushConstant::U32(width),
3426			],
3427			workgroups: [width.div_ceil(16), height.div_ceil(16), plane_count],
3428			indirect: None,
3429		},
3430		ImageSemanticDispatch {
3431			contract: crate::core::operation::image::REPROJECT_IMAGE_TO_3D,
3432			inputs: &[
3433				ImageSemanticInput::Matrix(disparity),
3434				ImageSemanticInput::Matrix(q),
3435			],
3436			outputs: &[ImageSemanticOutput::Matrix(&output)],
3437			attributes: &attributes,
3438		},
3439	)?;
3440	Ok(output)
3441}
3442
3443/// Non-local means denoising over a search window,
3444/// following cv::fastNlMeansDenoising. Each output pixel is
3445/// the weighted mean of samples in the (search_window)^2
3446/// neighbourhood with weights exp(-d / h^2), where d is the
3447/// patch SSD over an odd template_window normalized by its
3448/// area; the center weight equals the largest neighbour
3449/// weight so a uniform region stays untouched. Returns an
3450/// image with identical shape, layout, and format.
3451///
3452/// # Errors
3453///
3454/// Returns an error unless `input` is a nonempty FP32
3455/// NCHW/CHW image, `h` is finite and positive, and both
3456/// windows are odd and at least 3.
3457pub fn fast_nl_means_denoising(
3458	input: &Image,
3459	h: f32,
3460	template_window: u32,
3461	search_window: u32,
3462) -> Result<Image> {
3463	let (batch, channels, image_height, image_width) =
3464		image_extent(input, "image::fast_nl_means_denoising")?;
3465	if !h.is_finite() || h <= 0.0 {
3466		return Err(Error::invalid_argument(
3467			"image::fast_nl_means_denoising requires a finite positive h",
3468		));
3469	}
3470	if template_window < 3
3471		|| template_window.is_multiple_of(2)
3472		|| search_window < 3
3473		|| search_window.is_multiple_of(2)
3474	{
3475		return Err(Error::invalid_argument(
3476			"image::fast_nl_means_denoising requires odd template_window/search_window >= 3",
3477		));
3478	}
3479	let template_radius = template_window / 2;
3480	let search_radius = search_window / 2;
3481	let h_sqr = h * h;
3482	let output = allocate_like(input, "image::fast_nl_means_denoising")?;
3483	let attributes = [
3484		float("h", h),
3485		unsigned("template_window", template_window),
3486		unsigned("search_window", search_window),
3487	];
3488	input.runtime().record_image_semantic(
3489		ComputeDispatch {
3490			kernel: KernelId::ImageNlMeansDenoiseF32,
3491			buffers: &[
3492				BufferBinding::read(input.storage()),
3493				BufferBinding::write(output.storage()),
3494			],
3495			push_constants: &[
3496				PushConstant::U32(batch),
3497				PushConstant::U32(channels),
3498				PushConstant::U32(image_height),
3499				PushConstant::U32(image_width),
3500				PushConstant::U32(template_radius),
3501				PushConstant::U32(search_radius),
3502				PushConstant::F32(h_sqr),
3503			],
3504			workgroups: [
3505				image_width.div_ceil(16),
3506				image_height.div_ceil(16),
3507				batch * channels,
3508			],
3509			indirect: None,
3510		},
3511		ImageSemanticDispatch {
3512			contract: crate::core::operation::image::FAST_NL_MEANS_DENOISING,
3513			inputs: &[ImageSemanticInput::Image(input)],
3514			outputs: &[ImageSemanticOutput::Image(&output)],
3515			attributes: &attributes,
3516		},
3517	)?;
3518	Ok(output)
3519}
3520
3521/// Pyramid mean-shift edge-preserving smoothing, following
3522/// cv::pyrMeanShiftFiltering. The image is downsampled
3523/// max_level times with pyr_down; each level then runs a
3524/// per-pixel mean-shift pass that, for up to five
3525/// iterations, averages the (2*sp+1)^2 window samples whose
3526/// channel-vector distance stays below sr and adopts that
3527/// mean position and color, converging when the spatial
3528/// shift drops under one pixel. Coarse-to-fine levels seed
3529/// their starting color from the parent's converged result.
3530/// Channels participate as one color vector per plane
3531/// pixel; returns an image with identical shape, layout,
3532/// and format.
3533///
3534/// # Errors
3535///
3536/// Returns an error unless `input` is a nonempty FP32
3537/// NCHW/CHW image with at most 4 channels, sp/sr are finite
3538/// and positive, max_level is in [1, 4], and the coarsest
3539/// level still fits the spatial window support.
3540pub fn pyr_mean_shift_filtering(input: &Image, sp: f32, sr: f32, max_level: u32) -> Result<Image> {
3541	let (batch, channels, image_height, image_width) =
3542		image_extent(input, "image::pyr_mean_shift_filtering")?;
3543	if !sp.is_finite() || sp <= 0.0 || !sr.is_finite() || sr <= 0.0 {
3544		return Err(Error::invalid_argument(
3545			"image::pyr_mean_shift_filtering requires finite positive sp and sr",
3546		));
3547	}
3548	if channels > 4 {
3549		return Err(Error::invalid_argument(
3550			"image::pyr_mean_shift_filtering supports at most 4 channels",
3551		));
3552	}
3553	if !(1..=4).contains(&max_level) {
3554		return Err(Error::invalid_argument(
3555			"image::pyr_mean_shift_filtering requires max_level in [1, 4]",
3556		));
3557	}
3558	let levels = max_level
3559		.checked_add(1)
3560		.ok_or_else(|| Error::out_of_range("image::pyr_mean_shift_filtering max_level exceeds u32"))?;
3561	let spatial_radius = sp.ceil() as u32;
3562	let range_radius_sqr = sr * sr;
3563	let mut level_images = Vec::with_capacity(levels as usize);
3564	let mut level_dims = Vec::with_capacity(levels as usize);
3565	level_images.push(input.clone());
3566	level_dims.push((image_width, image_height));
3567	for _ in 1..levels {
3568		level_images.push(crate::image::pyr_down(level_images.last().ok_or_else(
3569			|| Error::internal("image::pyr_mean_shift_filtering pyramid level missing"),
3570		)?)?);
3571		let (width, height) = level_dims[level_dims.len() - 1];
3572		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
3573	}
3574	let runtime = input.runtime();
3575	// `converged[level]` storage: the returned Image for level 0,
3576	// workspaces[level - 1] for coarser levels. Workspaces are allocated
3577	// up front because dispatch bindings hold stable `&Storage` borrows.
3578	let mut workspaces = Vec::with_capacity(levels as usize - 1);
3579	for level in 1..levels {
3580		let (level_width, level_height) = level_dims[level as usize];
3581		let count = (batch as usize)
3582			.checked_mul(channels as usize)
3583			.and_then(|value| value.checked_mul(level_height as usize))
3584			.and_then(|value| value.checked_mul(level_width as usize))
3585			.ok_or_else(|| {
3586				Error::out_of_range("image::pyr_mean_shift_filtering workspace exceeds usize")
3587			})?;
3588		workspaces.push(Matrix::allocate(
3589			runtime,
3590			vec![
3591				batch as usize,
3592				channels as usize,
3593				level_height as usize,
3594				level_width as usize,
3595			],
3596			count,
3597			DType::F32,
3598		)?);
3599	}
3600	let output = allocate_like(input, "image::pyr_mean_shift_filtering")?;
3601	let mut stages = Vec::new();
3602	for level in (0..levels).rev() {
3603		let (level_width, level_height) = level_dims[level as usize];
3604		let shift_input = level_images[level as usize].as_matrix();
3605		let shift_output: &Matrix = if level == 0 {
3606			output.as_matrix()
3607		} else {
3608			&workspaces[level as usize - 1]
3609		};
3610		// Levels below the coarsest seed their starting color from the
3611		// parent's converged result (level + 1, stored at workspaces[level]).
3612		let (shift_seed, seed_width, seed_height, init_mode) = if level + 1 == levels {
3613			(shift_input, level_width, level_height, 0u32)
3614		} else {
3615			let (seed_width, seed_height) = level_dims[level as usize + 1];
3616			(&workspaces[level as usize], seed_width, seed_height, 1u32)
3617		};
3618		let pass_buffers = [
3619			BufferBinding::read(shift_input.storage()),
3620			BufferBinding::read(shift_seed.storage()),
3621			BufferBinding::write(shift_output.storage()),
3622		];
3623		let pass_push = [
3624			PushConstant::U32(batch),
3625			PushConstant::U32(channels),
3626			PushConstant::U32(level_height),
3627			PushConstant::U32(level_width),
3628			PushConstant::U32(seed_width),
3629			PushConstant::U32(seed_height),
3630			PushConstant::U32(spatial_radius),
3631			PushConstant::U32(5),
3632			PushConstant::U32(init_mode),
3633			PushConstant::F32(range_radius_sqr),
3634		];
3635		stages.push((
3636			KernelId::ImageMeanShiftPassF32,
3637			pass_buffers.to_vec(),
3638			pass_push.to_vec(),
3639			[level_width.div_ceil(16), level_height.div_ceil(16), batch],
3640		));
3641	}
3642	let attributes = [
3643		float("sp", sp),
3644		float("sr", sr),
3645		unsigned("max_level", max_level),
3646	];
3647	let dispatches: Vec<ComputeDispatch> = stages
3648		.iter()
3649		.map(
3650			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
3651				kernel: *kernel,
3652				buffers: buffers.as_slice(),
3653				push_constants: push_constants.as_slice(),
3654				workgroups: *workgroups,
3655				indirect: None,
3656			},
3657		)
3658		.collect();
3659	runtime.record_image_split_semantic(
3660		&dispatches,
3661		ImageSemanticDispatch {
3662			contract: crate::core::operation::image::PYR_MEAN_SHIFT_FILTERING,
3663			inputs: &[ImageSemanticInput::Image(input)],
3664			outputs: &[ImageSemanticOutput::Image(&output)],
3665			attributes: &attributes,
3666		},
3667	)?;
3668	Ok(output)
3669}
3670
3671fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
3672	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
3673	{
3674		return Err(Error::invalid_argument(format!(
3675			"{operation} requires an FP32 NCHW or CHW image"
3676		)));
3677	}
3678	let values = [
3679		input.batch_size(),
3680		input.channels(),
3681		input.height(),
3682		input.width(),
3683	];
3684	if values.contains(&0) {
3685		return Err(Error::invalid_argument(format!(
3686			"{operation} requires a nonempty image"
3687		)));
3688	}
3689	Ok((
3690		u32::try_from(values[0]).map_err(|_| Error::out_of_range("image batch exceeds u32"))?,
3691		u32::try_from(values[1]).map_err(|_| Error::out_of_range("image channels exceed u32"))?,
3692		u32::try_from(values[2]).map_err(|_| Error::out_of_range("image height exceeds u32"))?,
3693		u32::try_from(values[3]).map_err(|_| Error::out_of_range("image width exceeds u32"))?,
3694	))
3695}
3696
3697fn allocate_like(input: &Image, operation: &str) -> Result<Image> {
3698	let elements = input.as_matrix().num_elements();
3699	u32::try_from(elements)
3700		.map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
3701	let matrix = Matrix::allocate(
3702		input.runtime(),
3703		input.as_matrix().shape().to_vec(),
3704		elements,
3705		DType::F32,
3706	)?;
3707	Image::new(matrix, input.layout(), input.format())
3708}
3709
3710fn float(name: &str, value: f32) -> OpAttribute {
3711	OpAttribute::Float {
3712		name: name.into(),
3713		value: f64::from(value),
3714	}
3715}
3716fn unsigned(name: &str, value: u32) -> OpAttribute {
3717	OpAttribute::UnsignedInteger {
3718		name: name.into(),
3719		value: u64::from(value),
3720	}
3721}
3722fn enumeration(name: &str, value: &str) -> OpAttribute {
3723	OpAttribute::Enum {
3724		name: name.into(),
3725		value: value.into(),
3726	}
3727}
3728
3729fn validate_accumulation_pair(
3730	first: &Image,
3731	second: &Image,
3732	operation: &str,
3733) -> Result<(u32, u32, u32, u32)> {
3734	let extent = image_extent(first, operation)?;
3735	if second.as_matrix().shape() != first.as_matrix().shape()
3736		|| second.layout() != first.layout()
3737		|| second.format() != first.format()
3738		|| second.dtype() != first.dtype()
3739	{
3740		return Err(Error::invalid_argument(format!(
3741			"{operation} requires identically shaped FP32 images"
3742		)));
3743	}
3744	Ok(extent)
3745}