oarust 0.16.0

GPU-first semantic computing engine written in Rust
Documentation
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=image.json schema_version=1 generator_version=64
// schema_sha256=4c3af0f4b2504702bcaaa32134afcbd07ca92d06660d4847a5eeb5a0691dde61
//! Per-plane image statistics and histogram metrics.

use crate::{
	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
	runtime::{
		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
		KernelId, PushConstant,
	},
};

/// Accumulate a per-plane histogram over an FP32 NCHW or CHW image.
///
/// Each `(batch, channel)` plane contributes one row of `bins` buckets to the
/// U32 result whose leading dimensions mirror the image; `[B,C,H,W]` and
/// `[C,H,W]` inputs produce `[B,C,bins]` and `[C,bins]` results. Values below
/// `lower` or at or above `upper` are ignored; in-range values map uniformly
/// onto `[0, bins)`. The accumulator is cleared inside the operation, so a
/// captured plan replays the same counts.
///
/// # Errors
///
/// Returns an error unless `bins` is in `1..=256`, `lower` and `upper` are
/// finite with `lower < upper`, the image is nonempty FP32 NCHW/CHW, and all
/// sizes fit the shader ABI.
pub fn calc_hist(input: &Image, bins: u32, lower: f32, upper: f32) -> Result<Matrix> {
	if bins == 0 || bins > 256 {
		return Err(Error::invalid_argument(
			"image::calc_hist bins must be in 1..=256",
		));
	}
	if !lower.is_finite() || !upper.is_finite() || lower >= upper {
		return Err(Error::invalid_argument(
			"image::calc_hist requires finite bounds with lower < upper",
		));
	}
	let (batch, channels, image_height, image_width) = image_extent(input, "image::calc_hist")?;
	let mut shape = input.as_matrix().shape().to_vec();
	shape.truncate(shape.len() - 2);
	shape.push(bins as usize);
	let histogram_elements = shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::calc_hist output size exceeds u32"))?;
	let histogram = Matrix::allocate(
		input.engine_handle(),
		shape,
		histogram_elements as usize,
		DType::U32,
	)?;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(bins),
		PushConstant::F32(lower),
		PushConstant::F32(upper),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageCalcHistClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageCalcHistClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageCalcHistF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	let attributes = [
		unsigned("bins", bins),
		float("lower", lower),
		float("upper", upper),
	];
	input.engine_handle().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CALC_HIST,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&histogram)],
			attributes: &attributes,
		},
	)?;
	Ok(histogram)
}

/// Equalize a normalized FP32 image histogram per `(batch, channel)` plane.
///
/// Pixel values are quantized into 256 uniform buckets over `[0, 1]`, the
/// per-plane cumulative distribution is spread back over `[0, 1]` following
/// the `equalizeHist` contract, and the result keeps the input layout and
/// format. Values outside `[0, 1]` clamp into the edge buckets.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW and all
/// sizes fit the shader ABI.
pub fn equalize_hist(input: &Image) -> Result<Image> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::equalize_hist")?;
	let mut histogram_shape = input.as_matrix().shape().to_vec();
	histogram_shape.truncate(histogram_shape.len() - 2);
	histogram_shape.push(256);
	let histogram_elements = histogram_shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::equalize_hist workspace exceeds u32"))?;
	let engine = input.engine_handle();
	let histogram = Matrix::allocate(
		engine,
		histogram_shape.clone(),
		histogram_elements as usize,
		DType::U32,
	)?;
	let lut = Matrix::allocate(
		engine,
		histogram_shape,
		histogram_elements as usize,
		DType::F32,
	)?;
	let output = allocate_like(input, "image::equalize_hist")?;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let lut_buffers = [
		BufferBinding::read(histogram.storage()),
		BufferBinding::write(lut.storage()),
	];
	let lut_push = [PushConstant::U32(histogram_elements)];
	let remap_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(lut.storage()),
		BufferBinding::write(output.storage()),
	];
	let remap_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageEqualizeHistClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistLutF32,
			buffers: &lut_buffers,
			push_constants: &lut_push,
			workgroups: KernelId::ImageEqualizeHistLutF32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistRemapF32,
			buffers: &remap_buffers,
			push_constants: &remap_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	input.engine_handle().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::EQUALIZE_HIST,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Row-wise histogram comparison metric used by [`compare_hist`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HistogramComparison {
	/// Pearson correlation between centered rows; `1.0` is a perfect match.
	#[default]
	Correlation,
	/// Chi-square distance over paired buckets; `0.0` is a perfect match.
	ChiSquare,
	/// Normalized per-bucket minimum sum; `1.0` is a perfect match.
	Intersection,
	/// Bhattacharyya distance between normalized rows; `0.0` is a perfect match.
	Bhattacharyya,
}

impl HistogramComparison {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Correlation => "correlation",
			Self::ChiSquare => "chi_square",
			Self::Intersection => "intersection",
			Self::Bhattacharyya => "bhattacharyya",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Correlation => 0,
			Self::ChiSquare => 1,
			Self::Intersection => 2,
			Self::Bhattacharyya => 3,
		}
	}
}

/// Compare two same-shape U32 histogram matrices row by row.
///
/// The last dimension is the bucket axis; every leading index is an
/// independent row, so `[B,C,bins]` histograms produce a `[B,C]` FP32 score
/// matrix. Correlation, chi-square, intersection, and Bhattacharyya follow
/// the OpenCV `compareHist` formulas; degenerate rows return `0.0` rather
/// than propagating a zero denominator.
///
/// # Errors
///
/// Returns an error unless both inputs are same-shape nonempty U32 matrices
/// of rank at least two on one engine, and all sizes fit the shader ABI.
pub fn compare_hist(
	first: &Matrix,
	second: &Matrix,
	method: HistogramComparison,
) -> Result<Matrix> {
	if first.dtype() != DType::U32
		|| second.dtype() != DType::U32
		|| first.shape() != second.shape()
		|| !first.engine_handle().same_as(second.engine_handle())
	{
		return Err(Error::invalid_argument(
			"image::compare_hist requires same-shape same-engine U32 histograms",
		));
	}
	let shape = first.shape();
	if shape.len() < 2 || shape.contains(&0) {
		return Err(Error::invalid_argument(
			"image::compare_hist requires nonempty matrices of rank at least two",
		));
	}
	let bin_count = u32::try_from(shape[shape.len() - 1])
		.map_err(|_| Error::out_of_range("image::compare_hist bin count exceeds u32"))?;
	let row_count = shape[..shape.len() - 1]
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::compare_hist row count exceeds u32"))?;
	let output = Matrix::allocate(
		first.engine_handle(),
		shape[..shape.len() - 1].to_vec(),
		row_count as usize,
		DType::F32,
	)?;
	first.engine_handle().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageCompareHistU32,
			buffers: &[
				BufferBinding::read(first.storage()),
				BufferBinding::read(second.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(row_count),
				PushConstant::U32(bin_count),
				PushConstant::U32(method.code()),
			],
			workgroups: KernelId::ImageCompareHistU32.linear_workgroups(row_count),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::COMPARE_HIST,
			inputs: &[
				ImageSemanticInput::Matrix(first),
				ImageSemanticInput::Matrix(second),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &[enumeration("method", method.token())],
		},
	)?;
	Ok(output)
}

fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(format!(
			"{operation} requires an FP32 NCHW or CHW image"
		)));
	}
	let values = [
		input.batch_size(),
		input.channels(),
		input.height(),
		input.width(),
	];
	if values.contains(&0) {
		return Err(Error::invalid_argument(format!(
			"{operation} requires a nonempty image"
		)));
	}
	Ok((
		u32::try_from(values[0]).map_err(|_| Error::out_of_range("image batch exceeds u32"))?,
		u32::try_from(values[1]).map_err(|_| Error::out_of_range("image channels exceed u32"))?,
		u32::try_from(values[2]).map_err(|_| Error::out_of_range("image height exceeds u32"))?,
		u32::try_from(values[3]).map_err(|_| Error::out_of_range("image width exceeds u32"))?,
	))
}

fn allocate_like(input: &Image, operation: &str) -> Result<Image> {
	let elements = input.as_matrix().num_elements();
	u32::try_from(elements)
		.map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
	let matrix = Matrix::allocate(
		input.engine_handle(),
		input.as_matrix().shape().to_vec(),
		elements,
		DType::F32,
	)?;
	Image::new(matrix, input.layout(), input.format())
}

fn float(name: &str, value: f32) -> OpAttribute {
	OpAttribute::Float {
		name: name.into(),
		value: f64::from(value),
	}
}
fn unsigned(name: &str, value: u32) -> OpAttribute {
	OpAttribute::UnsignedInteger {
		name: name.into(),
		value: u64::from(value),
	}
}
fn enumeration(name: &str, value: &str) -> OpAttribute {
	OpAttribute::Enum {
		name: name.into(),
		value: value.into(),
	}
}