use crate::{
DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
runtime::{
BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
KernelId, PushConstant,
},
};
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.runtime(),
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.runtime().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)
}
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 runtime = input.runtime();
let histogram = Matrix::allocate(
runtime,
histogram_shape.clone(),
histogram_elements as usize,
DType::U32,
)?;
let lut = Matrix::allocate(
runtime,
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.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract: crate::core::operation::image::EQUALIZE_HIST,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &[],
},
)?;
Ok(output)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HistogramComparison {
#[default]
Correlation,
ChiSquare,
Intersection,
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,
}
}
}
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.runtime().same_as(second.runtime())
{
return Err(Error::invalid_argument(
"image::compare_hist requires same-shape same-runtime 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.runtime(),
shape[..shape.len() - 1].to_vec(),
row_count as usize,
DType::F32,
)?;
first.runtime().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)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AutoThreshold {
#[default]
Otsu,
Triangle,
}
impl AutoThreshold {
pub(super) const fn token(self) -> &'static str {
match self {
Self::Otsu => "otsu",
Self::Triangle => "triangle",
}
}
pub(super) const fn code(self) -> u32 {
match self {
Self::Otsu => 0,
Self::Triangle => 1,
}
}
}
pub fn threshold_auto(
input: &Image,
method: AutoThreshold,
max_value: f32,
) -> Result<(Image, Matrix)> {
if !max_value.is_finite() {
return Err(Error::invalid_argument(
"image::threshold_auto requires a finite max_value",
));
}
let (batch, channels, image_height, image_width) = image_extent(input, "image::threshold_auto")?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::threshold_auto plane count exceeds u32"))?;
let histogram_elements = plane_count
.checked_mul(256)
.ok_or_else(|| Error::out_of_range("image::threshold_auto workspace exceeds u32"))?;
let runtime = input.runtime();
let mut histogram_shape = input.as_matrix().shape().to_vec();
histogram_shape.truncate(histogram_shape.len() - 2);
histogram_shape.push(256);
let histogram = Matrix::allocate(
runtime,
histogram_shape,
histogram_elements as usize,
DType::U32,
)?;
let thresholds_shape = input.as_matrix().shape()[..input.as_matrix().shape().len() - 2].to_vec();
let thresholds = Matrix::allocate(runtime, thresholds_shape, plane_count as usize, DType::F32)?;
let output = allocate_like(input, "image::threshold_auto")?;
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 select_buffers = [
BufferBinding::read(histogram.storage()),
BufferBinding::write(thresholds.storage()),
];
let select_push = [
PushConstant::U32(plane_count),
PushConstant::U32(method.code()),
];
let apply_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(thresholds.storage()),
BufferBinding::write(output.storage()),
];
let apply_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(max_value),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageThresholdAutoClearU32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageThresholdAutoClearU32.linear_workgroups(histogram_elements),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageThresholdAutoF32,
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::ImageThresholdAutoSelectU32,
buffers: &select_buffers,
push_constants: &select_push,
workgroups: KernelId::ImageThresholdAutoSelectU32.linear_workgroups(plane_count),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageThresholdAutoApplyF32,
buffers: &apply_buffers,
push_constants: &apply_push,
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
];
let attributes = [
enumeration("method", method.token()),
float("max_value", max_value),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract: crate::core::operation::image::THRESHOLD_AUTO,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[
ImageSemanticOutput::Image(&output),
ImageSemanticOutput::Matrix(&thresholds),
],
attributes: &attributes,
},
)?;
Ok((output, thresholds))
}
pub fn integral(input: &Image) -> Result<Matrix> {
let (batch, channels, image_height, image_width) = image_extent(input, "image::integral")?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::integral plane count exceeds u32"))?;
let mut shape = input.as_matrix().shape().to_vec();
let rank = shape.len();
shape[rank - 2] += 1;
shape[rank - 1] += 1;
let elements = shape
.iter()
.try_fold(1u32, |count, value| {
count.checked_mul(u32::try_from(*value).ok()?)
})
.ok_or_else(|| Error::out_of_range("image::integral output size exceeds u32"))?;
let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
let row_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(output.storage()),
];
let row_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
];
let col_buffers = [BufferBinding::read_write(output.storage())];
let col_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageIntegralRowsF32,
buffers: &row_buffers,
push_constants: &row_push,
workgroups: KernelId::ImageIntegralRowsF32.linear_workgroups(plane_count * image_height),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageIntegralColsF32,
buffers: &col_buffers,
push_constants: &col_push,
workgroups: KernelId::ImageIntegralColsF32.linear_workgroups(plane_count * (image_width + 1)),
indirect: None,
},
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract: crate::core::operation::image::INTEGRAL,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &[],
},
)?;
Ok(output)
}
pub fn calc_back_project(
input: &Image,
histogram: &Matrix,
lower: f32,
upper: f32,
) -> Result<Image> {
let (batch, channels, image_height, image_width) =
image_extent(input, "image::calc_back_project")?;
if histogram.dtype() != DType::U32 || histogram.shape().is_empty() {
return Err(Error::invalid_argument(
"image::calc_back_project requires a nonempty U32 histogram",
));
}
let image_shape = input.as_matrix().shape();
let histogram_shape = histogram.shape();
if histogram_shape.len() != image_shape.len() - 1
|| histogram_shape[..histogram_shape.len() - 1] != image_shape[..image_shape.len() - 2]
{
return Err(Error::invalid_argument(
"image::calc_back_project histogram leading shape must match the image planes",
));
}
let bins = u32::try_from(histogram_shape[histogram_shape.len() - 1])
.map_err(|_| Error::out_of_range("image::calc_back_project bins exceed u32"))?;
if bins == 0 || bins > 256 {
return Err(Error::invalid_argument(
"image::calc_back_project histogram bins must be in 1..=256",
));
}
if !lower.is_finite() || !upper.is_finite() || lower >= upper {
return Err(Error::invalid_argument(
"image::calc_back_project requires finite bounds with lower < upper",
));
}
let output = allocate_like(input, "image::calc_back_project")?;
let attributes = [float("lower", lower), float("upper", upper)];
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageCalcBackProjectF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::read(histogram.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(bins),
PushConstant::F32(lower),
PushConstant::F32(upper),
],
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::CALC_BACK_PROJECT,
inputs: &[
ImageSemanticInput::Image(input),
ImageSemanticInput::Matrix(histogram),
],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn clahe(input: &Image, clip_limit: f32, tile_width: u32, tile_height: u32) -> Result<Image> {
let (batch, channels, image_height, image_width) = image_extent(input, "image::clahe")?;
if !clip_limit.is_finite() || clip_limit <= 0.0 {
return Err(Error::invalid_argument(
"image::clahe requires a finite positive clip_limit",
));
}
if tile_width == 0 || tile_height == 0 {
return Err(Error::invalid_argument(
"image::clahe requires nonzero tile extents",
));
}
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::clahe plane count exceeds u32"))?;
let tiles_x = image_width.div_ceil(tile_width);
let tiles_y = image_height.div_ceil(tile_height);
let tile_count = plane_count
.checked_mul(tiles_x)
.and_then(|count| count.checked_mul(tiles_y))
.ok_or_else(|| Error::out_of_range("image::clahe tile count exceeds u32"))?;
let histogram_elements = tile_count
.checked_mul(256)
.ok_or_else(|| Error::out_of_range("image::clahe histogram size exceeds u32"))?;
let runtime = input.runtime();
let histogram = Matrix::allocate(
runtime,
vec![histogram_elements as usize],
histogram_elements as usize,
DType::U32,
)?;
let lut = Matrix::allocate(
runtime,
vec![histogram_elements as usize],
histogram_elements as usize,
DType::F32,
)?;
let output = allocate_like(input, "image::clahe")?;
let tile_area = tile_width as f32 * tile_height as f32;
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(tile_width),
PushConstant::U32(tile_height),
PushConstant::U32(tiles_x),
];
let lut_buffers = [
BufferBinding::read(histogram.storage()),
BufferBinding::write(lut.storage()),
];
let lut_push = [
PushConstant::U32(tile_count),
PushConstant::F32(clip_limit),
PushConstant::F32(tile_area),
];
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),
PushConstant::U32(tile_width),
PushConstant::U32(tile_height),
PushConstant::U32(tiles_x),
PushConstant::U32(tiles_y),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageClaheClearU32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageClaheClearU32.linear_workgroups(histogram_elements),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageClaheF32,
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::ImageClaheLutU32,
buffers: &lut_buffers,
push_constants: &lut_push,
workgroups: KernelId::ImageClaheLutU32.linear_workgroups(tile_count),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageClaheRemapF32,
buffers: &remap_buffers,
push_constants: &remap_push,
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
];
let attributes = [
float("clip_limit", clip_limit),
unsigned("tile_width", tile_width),
unsigned("tile_height", tile_height),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract: crate::core::operation::image::CLAHE,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn accumulate(input: &Image, accumulator: &Image) -> Result<Image> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(input, accumulator, "image::accumulate")?;
let output = allocate_like(input, "image::accumulate")?;
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageAccumulateF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::read(accumulator.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
],
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::ACCUMULATE,
inputs: &[
ImageSemanticInput::Image(input),
ImageSemanticInput::Image(accumulator),
],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &[],
},
)?;
Ok(output)
}
pub fn accumulate_weighted(input: &Image, accumulator: &Image, alpha: f32) -> Result<Image> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(input, accumulator, "image::accumulate_weighted")?;
if !alpha.is_finite() {
return Err(Error::invalid_argument(
"image::accumulate_weighted requires a finite alpha",
));
}
let output = allocate_like(input, "image::accumulate_weighted")?;
let attributes = [float("alpha", alpha)];
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageAccumulateWeightedF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::read(accumulator.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(alpha),
],
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::ACCUMULATE_WEIGHTED,
inputs: &[
ImageSemanticInput::Image(input),
ImageSemanticInput::Image(accumulator),
],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn moments(input: &Image) -> Result<Matrix> {
let (batch, channels, image_height, image_width) = image_extent(input, "image::moments")?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::moments plane count exceeds u32"))?;
let mut shape = input.as_matrix().shape().to_vec();
shape.truncate(shape.len() - 2);
shape.push(10);
let output = Matrix::allocate(
input.runtime(),
shape,
plane_count
.checked_mul(10)
.ok_or_else(|| Error::out_of_range("image::moments output size exceeds u32"))? as usize,
DType::F32,
)?;
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageMomentsF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
],
workgroups: KernelId::ImageMomentsF32.linear_workgroups(plane_count),
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::MOMENTS,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &[],
},
)?;
Ok(output)
}
pub fn psnr(first: &Image, second: &Image, peak_value: f32) -> Result<Matrix> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(first, second, "image::psnr")?;
if !peak_value.is_finite() || peak_value <= 0.0 {
return Err(Error::invalid_argument(
"image::psnr requires a finite positive peak_value",
));
}
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::psnr plane count exceeds u32"))?;
let mut shape = first.as_matrix().shape().to_vec();
shape.truncate(shape.len() - 2);
let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
let attributes = [float("peak_value", peak_value)];
first.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImagePsnrF32,
buffers: &[
BufferBinding::read(first.storage()),
BufferBinding::read(second.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(peak_value),
],
workgroups: KernelId::ImagePsnrF32.linear_workgroups(plane_count),
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::PSNR,
inputs: &[
ImageSemanticInput::Image(first),
ImageSemanticInput::Image(second),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn ssim(first: &Image, second: &Image) -> Result<Matrix> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(first, second, "image::ssim")?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::ssim plane count exceeds u32"))?;
let mut shape = first.as_matrix().shape().to_vec();
shape.truncate(shape.len() - 2);
let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
first.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageSsimF32,
buffers: &[
BufferBinding::read(first.storage()),
BufferBinding::read(second.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
],
workgroups: KernelId::ImageSsimF32.linear_workgroups(plane_count),
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::SSIM,
inputs: &[
ImageSemanticInput::Image(first),
ImageSemanticInput::Image(second),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &[],
},
)?;
Ok(output)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MatchTemplate {
#[default]
Sqdiff,
SqdiffNormed,
Ccorr,
CcorrNormed,
Ccoeff,
CcoeffNormed,
}
impl MatchTemplate {
pub(super) const fn token(self) -> &'static str {
match self {
Self::Sqdiff => "sqdiff",
Self::SqdiffNormed => "sqdiff_normed",
Self::Ccorr => "ccorr",
Self::CcorrNormed => "ccorr_normed",
Self::Ccoeff => "ccoeff",
Self::CcoeffNormed => "ccoeff_normed",
}
}
pub(super) const fn code(self) -> u32 {
match self {
Self::Sqdiff => 0,
Self::SqdiffNormed => 1,
Self::Ccorr => 2,
Self::CcorrNormed => 3,
Self::Ccoeff => 4,
Self::CcoeffNormed => 5,
}
}
}
pub fn match_template(input: &Image, template: &Image, method: MatchTemplate) -> Result<Matrix> {
let (batch, channels, image_height, image_width) = image_extent(input, "image::match_template")?;
if template.dtype() != DType::F32
|| !matches!(template.layout(), ImageLayout::Nchw | ImageLayout::Chw)
|| template.batch_size() != 1
|| template.channels() != input.channels()
{
return Err(Error::invalid_argument(
"image::match_template requires a single-plane FP32 template with matching channels",
));
}
let template_height = u32::try_from(template.height())
.map_err(|_| Error::out_of_range("image::match_template template height exceeds u32"))?;
let template_width = u32::try_from(template.width())
.map_err(|_| Error::out_of_range("image::match_template template width exceeds u32"))?;
if template_height == 0
|| template_width == 0
|| template_height > image_height
|| template_width > image_width
{
return Err(Error::invalid_argument(
"image::match_template requires a nonempty template no larger than the image planes",
));
}
let output_height = image_height - template_height + 1;
let output_width = image_width - template_width + 1;
let mut shape = input.as_matrix().shape().to_vec();
let rank = shape.len();
shape[rank - 2] = output_height as usize;
shape[rank - 1] = output_width as usize;
let elements = shape
.iter()
.try_fold(1u32, |count, value| {
count.checked_mul(u32::try_from(*value).ok()?)
})
.ok_or_else(|| Error::out_of_range("image::match_template output size exceeds u32"))?;
let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
let attributes = [enumeration("method", method.token())];
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageMatchTemplateF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::read(template.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(template_height),
PushConstant::U32(template_width),
PushConstant::U32(output_height),
PushConstant::U32(output_width),
PushConstant::U32(method.code()),
],
workgroups: [
output_width.div_ceil(16),
output_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::MATCH_TEMPLATE,
inputs: &[
ImageSemanticInput::Image(input),
ImageSemanticInput::Image(template),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Connectivity {
Four,
#[default]
Eight,
}
impl Connectivity {
pub(super) const fn token(self) -> &'static str {
match self {
Self::Four => "four",
Self::Eight => "eight",
}
}
pub(super) const fn code(self) -> u32 {
match self {
Self::Four => 4,
Self::Eight => 8,
}
}
}
pub fn connected_components(
input: &Image,
threshold: f32,
connectivity: Connectivity,
propagation_passes: u32,
) -> Result<Matrix> {
if !threshold.is_finite() {
return Err(Error::invalid_argument(
"image::connected_components threshold must be finite",
));
}
let contract = crate::core::operation::image::CONNECTED_COMPONENTS;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::connected_components plane count exceeds u32"))?;
let plane_elements = plane_count
.checked_mul(image_height)
.and_then(|count| count.checked_mul(image_width))
.ok_or_else(|| Error::out_of_range("image::connected_components label count exceeds u32"))?;
let relax_passes = if propagation_passes == 0 {
image_height.checked_add(image_width).ok_or_else(|| {
Error::out_of_range("image::connected_components propagation bound exceeds u32")
})?
} else {
propagation_passes
};
let labels = Matrix::allocate(
input.runtime(),
vec![
plane_count as usize,
image_height as usize,
image_width as usize,
],
plane_elements as usize,
DType::U32,
)?;
let mut workgroups =
KernelId::ImageConnectedComponentsInitU32.output_workgroups(image_width, image_height);
workgroups[2] = plane_count;
let init_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(labels.storage()),
];
let init_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(threshold),
];
let relax_buffers = [BufferBinding::read_write(labels.storage())];
let relax_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(connectivity.code()),
];
let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageConnectedComponentsInitU32,
buffers: &init_buffers,
push_constants: &init_push,
workgroups,
indirect: None,
});
for _ in 0..relax_passes {
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageConnectedComponentsRelaxU32,
buffers: &relax_buffers,
push_constants: &relax_push,
workgroups,
indirect: None,
});
}
let attributes = [
float("threshold", threshold),
enumeration("connectivity", connectivity.token()),
unsigned("propagation_passes", propagation_passes),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&labels)],
attributes: &attributes,
},
)?;
Ok(labels)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DistanceType {
L1,
#[default]
L2,
}
impl DistanceType {
pub(super) const fn token(self) -> &'static str {
match self {
Self::L1 => "l1",
Self::L2 => "l2",
}
}
pub(super) const fn code(self) -> u32 {
match self {
Self::L1 => 1,
Self::L2 => 2,
}
}
}
pub fn distance_transform(
input: &Image,
threshold: f32,
distance: DistanceType,
propagation_passes: u32,
) -> Result<Matrix> {
if !threshold.is_finite() {
return Err(Error::invalid_argument(
"image::distance_transform threshold must be finite",
));
}
let contract = crate::core::operation::image::DISTANCE_TRANSFORM;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::distance_transform plane count exceeds u32"))?;
let plane_elements = plane_count
.checked_mul(image_height)
.and_then(|count| count.checked_mul(image_width))
.ok_or_else(|| Error::out_of_range("image::distance_transform element count exceeds u32"))?;
let relax_passes = if propagation_passes == 0 {
image_height.checked_add(image_width).ok_or_else(|| {
Error::out_of_range("image::distance_transform propagation bound exceeds u32")
})?
} else {
propagation_passes
};
let distances = Matrix::allocate(
input.runtime(),
vec![
plane_count as usize,
image_height as usize,
image_width as usize,
],
plane_elements as usize,
DType::F32,
)?;
let mut workgroups =
KernelId::ImageDistanceTransformInitF32.output_workgroups(image_width, image_height);
workgroups[2] = plane_count;
let init_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(distances.storage()),
];
let init_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(threshold),
];
let relax_buffers = [BufferBinding::read_write(distances.storage())];
let relax_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(distance.code()),
];
let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageDistanceTransformInitF32,
buffers: &init_buffers,
push_constants: &init_push,
workgroups,
indirect: None,
});
for _ in 0..relax_passes {
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageDistanceTransformRelaxF32,
buffers: &relax_buffers,
push_constants: &relax_push,
workgroups,
indirect: None,
});
}
let attributes = [
float("threshold", threshold),
enumeration("distance", distance.token()),
unsigned("propagation_passes", propagation_passes),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&distances)],
attributes: &attributes,
},
)?;
Ok(distances)
}
pub fn hough_lines(
input: &Image,
edge_threshold: f32,
rho_step: f32,
theta_step: f32,
threshold: u32,
max_lines: u32,
) -> Result<Matrix> {
if !edge_threshold.is_finite()
|| !rho_step.is_finite()
|| !theta_step.is_finite()
|| rho_step <= 0.0
|| theta_step <= 0.0
|| theta_step > 180.0
{
return Err(Error::invalid_argument(
"image::hough_lines steps must be finite, positive, and theta_step <= 180",
));
}
if max_lines == 0 {
return Err(Error::invalid_argument(
"image::hough_lines max_lines must be nonzero",
));
}
let contract = crate::core::operation::image::HOUGH_LINES;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::hough_lines plane count exceeds u32"))?;
let num_theta = (180.0f32 / theta_step).ceil() as u32;
let span = (image_width as f64).hypot(image_height as f64).ceil();
let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
let bins = num_theta
.checked_mul(num_rho)
.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator size exceeds u32"))?;
let acc_stride = bins
.checked_add(1)
.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator stride exceeds u32"))?;
let acc_elements = plane_count
.checked_mul(acc_stride)
.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator elements exceed u32"))?;
let line_elements = plane_count
.checked_mul(max_lines)
.and_then(|count| count.checked_mul(3))
.ok_or_else(|| Error::out_of_range("image::hough_lines output elements exceed u32"))?;
let acc_cells = plane_count
.checked_mul(bins)
.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator cells exceed u32"))?;
let accumulator = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, acc_stride as usize],
acc_elements as usize,
DType::U32,
)?;
let lines = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, max_lines as usize, 3],
line_elements as usize,
DType::F32,
)?;
let mut workgroups =
KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
workgroups[2] = plane_count;
let rho_span = span as f32;
let clear_buffers = [
BufferBinding::write(accumulator.storage()),
BufferBinding::write(lines.storage()),
];
let clear_push = [
PushConstant::U32(acc_elements),
PushConstant::U32(line_elements),
];
let accumulate_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read_write(accumulator.storage()),
];
let accumulate_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(edge_threshold),
PushConstant::F32(rho_step),
PushConstant::F32(theta_step),
PushConstant::U32(num_theta),
PushConstant::U32(num_rho),
PushConstant::F32(rho_span),
];
let extract_buffers = [
BufferBinding::read_write(accumulator.storage()),
BufferBinding::write(lines.storage()),
];
let extract_push = [
PushConstant::U32(num_theta),
PushConstant::U32(num_rho),
PushConstant::U32(plane_count),
PushConstant::U32(threshold),
PushConstant::U32(max_lines),
PushConstant::F32(rho_step),
PushConstant::F32(theta_step),
PushConstant::F32(rho_span),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageHoughLinesClearU32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageHoughLinesClearU32.linear_workgroups(acc_elements + line_elements),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageHoughLinesAccumulateF32,
buffers: &accumulate_buffers,
push_constants: &accumulate_push,
workgroups,
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageHoughLinesExtractU32,
buffers: &extract_buffers,
push_constants: &extract_push,
workgroups: KernelId::ImageHoughLinesExtractU32.linear_workgroups(acc_cells),
indirect: None,
},
];
let attributes = [
float("edge_threshold", edge_threshold),
float("rho_step", rho_step),
float("theta_step", theta_step),
unsigned("threshold", threshold),
unsigned("max_lines", max_lines),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&lines)],
attributes: &attributes,
},
)?;
Ok(lines)
}
#[allow(clippy::too_many_arguments)]
pub fn hough_lines_p(
input: &Image,
edge_threshold: f32,
rho_step: f32,
theta_step: f32,
threshold: u32,
max_lines: u32,
min_line_length: f32,
max_line_gap: u32,
) -> Result<Matrix> {
if !edge_threshold.is_finite()
|| !rho_step.is_finite()
|| !theta_step.is_finite()
|| !min_line_length.is_finite()
|| rho_step <= 0.0
|| theta_step <= 0.0
|| theta_step > 180.0
|| min_line_length < 0.0
{
return Err(Error::invalid_argument(
"image::hough_lines_p steps must be finite/positive, theta_step <= 180, min_line_length >= 0",
));
}
if max_lines == 0 {
return Err(Error::invalid_argument(
"image::hough_lines_p max_lines must be nonzero",
));
}
let contract = crate::core::operation::image::HOUGH_LINES_P;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p plane count exceeds u32"))?;
let num_theta = (180.0f32 / theta_step).ceil() as u32;
let span = (image_width as f64).hypot(image_height as f64).ceil();
let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
let bins = num_theta
.checked_mul(num_rho)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator size exceeds u32"))?;
let acc_stride = bins
.checked_add(1)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator stride exceeds u32"))?;
let acc_elements = plane_count
.checked_mul(acc_stride)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator elements exceed u32"))?;
let acc_cells = plane_count
.checked_mul(bins)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator cells exceed u32"))?;
let line_elements = plane_count
.checked_mul(max_lines)
.and_then(|count| count.checked_mul(3))
.ok_or_else(|| Error::out_of_range("image::hough_lines_p line elements exceed u32"))?;
let segment_elements = plane_count
.checked_mul(max_lines)
.and_then(|count| count.checked_mul(4))
.ok_or_else(|| Error::out_of_range("image::hough_lines_p segment elements exceed u32"))?;
let line_slots = plane_count
.checked_mul(max_lines)
.ok_or_else(|| Error::out_of_range("image::hough_lines_p line slots exceed u32"))?;
let accumulator = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, acc_stride as usize],
acc_elements as usize,
DType::U32,
)?;
let lines = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, max_lines as usize, 3],
line_elements as usize,
DType::F32,
)?;
let segments = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, max_lines as usize, 4],
segment_elements as usize,
DType::F32,
)?;
let mut workgroups =
KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
workgroups[2] = plane_count;
let rho_span = span as f32;
let clear_buffers = [
BufferBinding::write(accumulator.storage()),
BufferBinding::write(lines.storage()),
];
let clear_push = [
PushConstant::U32(acc_elements),
PushConstant::U32(line_elements),
];
let accumulate_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read_write(accumulator.storage()),
];
let accumulate_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(edge_threshold),
PushConstant::F32(rho_step),
PushConstant::F32(theta_step),
PushConstant::U32(num_theta),
PushConstant::U32(num_rho),
PushConstant::F32(rho_span),
];
let extract_buffers = [
BufferBinding::read_write(accumulator.storage()),
BufferBinding::write(lines.storage()),
];
let extract_push = [
PushConstant::U32(num_theta),
PushConstant::U32(num_rho),
PushConstant::U32(plane_count),
PushConstant::U32(threshold),
PushConstant::U32(max_lines),
PushConstant::F32(rho_step),
PushConstant::F32(theta_step),
PushConstant::F32(rho_span),
];
let probe_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(lines.storage()),
BufferBinding::write(segments.storage()),
];
let probe_push = [
PushConstant::U32(plane_count),
PushConstant::U32(max_lines),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(edge_threshold),
PushConstant::F32(min_line_length),
PushConstant::U32(max_line_gap),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageHoughLinesPClearU32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageHoughLinesPClearU32
.linear_workgroups(acc_elements + line_elements),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageHoughLinesPAccumulateF32,
buffers: &accumulate_buffers,
push_constants: &accumulate_push,
workgroups,
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageHoughLinesPExtractU32,
buffers: &extract_buffers,
push_constants: &extract_push,
workgroups: KernelId::ImageHoughLinesPExtractU32.linear_workgroups(acc_cells),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageHoughLinesProbeF32,
buffers: &probe_buffers,
push_constants: &probe_push,
workgroups: KernelId::ImageHoughLinesProbeF32.linear_workgroups(line_slots),
indirect: None,
},
];
let attributes = [
float("edge_threshold", edge_threshold),
float("rho_step", rho_step),
float("theta_step", theta_step),
unsigned("threshold", threshold),
unsigned("max_lines", max_lines),
float("min_line_length", min_line_length),
unsigned("max_line_gap", max_line_gap),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Matrix(&segments)],
attributes: &attributes,
},
)?;
Ok(segments)
}
pub fn find_contours(
input: &Image,
threshold: f32,
connectivity: Connectivity,
max_contours: u32,
max_points: u32,
propagation_passes: u32,
) -> Result<(Matrix, Matrix)> {
if !threshold.is_finite() {
return Err(Error::invalid_argument(
"image::find_contours threshold must be finite",
));
}
if max_contours == 0 {
return Err(Error::invalid_argument(
"image::find_contours max_contours must be nonzero",
));
}
let contract = crate::core::operation::image::FIND_CONTOURS;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::find_contours plane count exceeds u32"))?;
let plane_elements = image_height
.checked_mul(image_width)
.ok_or_else(|| Error::out_of_range("image::find_contours plane size exceeds u32"))?;
let label_elements = plane_count
.checked_mul(plane_elements)
.ok_or_else(|| Error::out_of_range("image::find_contours label count exceeds u32"))?;
let relax_passes = if propagation_passes == 0 {
image_height
.checked_add(image_width)
.ok_or_else(|| Error::out_of_range("image::find_contours propagation bound exceeds u32"))?
} else {
propagation_passes
};
let resolved_max_points = if max_points == 0 {
image_height
.checked_add(image_width)
.and_then(|sum| sum.checked_mul(4))
.ok_or_else(|| Error::out_of_range("image::find_contours point bound exceeds u32"))?
} else {
max_points
};
let labels = Matrix::allocate(
input.runtime(),
vec![
plane_count as usize,
image_height as usize,
image_width as usize,
],
label_elements as usize,
DType::U32,
)?;
let seed_stride = max_contours
.checked_add(1)
.ok_or_else(|| Error::out_of_range("image::find_contours seed stride exceeds u32"))?;
let seed_elements = plane_count
.checked_mul(seed_stride)
.ok_or_else(|| Error::out_of_range("image::find_contours seed count exceeds u32"))?;
let point_elements = plane_count
.checked_mul(max_contours)
.and_then(|count| count.checked_mul(resolved_max_points))
.and_then(|count| count.checked_mul(2))
.ok_or_else(|| Error::out_of_range("image::find_contours point count exceeds u32"))?;
let length_elements = plane_count
.checked_mul(max_contours)
.ok_or_else(|| Error::out_of_range("image::find_contours length count exceeds u32"))?;
let seeds = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, seed_stride as usize],
seed_elements as usize,
DType::U32,
)?;
let points = Matrix::allocate(
input.runtime(),
vec![
plane_count as usize,
max_contours as usize,
resolved_max_points as usize,
2,
],
point_elements as usize,
DType::F32,
)?;
let lengths = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, max_contours as usize],
length_elements as usize,
DType::U32,
)?;
let clear_elements = seed_elements.max(point_elements).max(length_elements);
let trace_slots = plane_count
.checked_mul(max_contours)
.ok_or_else(|| Error::out_of_range("image::find_contours slot count exceeds u32"))?;
let mut workgroups =
KernelId::ImageFindContoursInitU32.output_workgroups(image_width, image_height);
workgroups[2] = plane_count;
let clear_buffers = [
BufferBinding::write(seeds.storage()),
BufferBinding::write(points.storage()),
BufferBinding::write(lengths.storage()),
];
let clear_push = [
PushConstant::U32(seed_elements),
PushConstant::U32(point_elements),
PushConstant::U32(length_elements),
];
let init_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(labels.storage()),
];
let init_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::F32(threshold),
];
let relax_buffers = [BufferBinding::read_write(labels.storage())];
let relax_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(connectivity.code()),
];
let seeds_buffers = [
BufferBinding::read(labels.storage()),
BufferBinding::read_write(seeds.storage()),
];
let seeds_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(max_contours),
];
let trace_buffers = [
BufferBinding::read(labels.storage()),
BufferBinding::read(seeds.storage()),
BufferBinding::write(points.storage()),
BufferBinding::write(lengths.storage()),
];
let trace_push = [
PushConstant::U32(plane_count),
PushConstant::U32(max_contours),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(resolved_max_points),
];
let mut dispatches = Vec::with_capacity(4 + relax_passes as usize);
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageFindContoursClearU32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageFindContoursClearU32.linear_workgroups(clear_elements),
indirect: None,
});
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageFindContoursInitU32,
buffers: &init_buffers,
push_constants: &init_push,
workgroups,
indirect: None,
});
for _ in 0..relax_passes {
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageFindContoursRelaxU32,
buffers: &relax_buffers,
push_constants: &relax_push,
workgroups,
indirect: None,
});
}
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageFindContoursSeedsU32,
buffers: &seeds_buffers,
push_constants: &seeds_push,
workgroups,
indirect: None,
});
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageFindContoursTraceU32,
buffers: &trace_buffers,
push_constants: &trace_push,
workgroups: KernelId::ImageFindContoursTraceU32.linear_workgroups(trace_slots),
indirect: None,
});
let attributes = [
float("threshold", threshold),
enumeration("connectivity", connectivity.token()),
unsigned("max_contours", max_contours),
unsigned("max_points", resolved_max_points),
unsigned("propagation_passes", propagation_passes),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[
ImageSemanticOutput::Matrix(&points),
ImageSemanticOutput::Matrix(&lengths),
],
attributes: &attributes,
},
)?;
Ok((points, lengths))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CornerScore {
#[default]
Harris,
MinEigen,
}
impl CornerScore {
pub(super) const fn token(self) -> &'static str {
match self {
Self::Harris => "harris",
Self::MinEigen => "min_eigen",
}
}
pub(super) const fn code(self) -> u32 {
match self {
Self::Harris => 0,
Self::MinEigen => 1,
}
}
}
pub fn corner_score(
input: &Image,
block_size: u32,
k: f32,
score_type: CornerScore,
) -> Result<Image> {
if !k.is_finite() {
return Err(Error::invalid_argument(
"image::corner_score k must be finite",
));
}
if block_size < 3 || block_size.is_multiple_of(2) {
return Err(Error::invalid_argument(
"image::corner_score block_size must be odd and at least 3",
));
}
let contract = crate::core::operation::image::CORNER_SCORE;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::corner_score plane count exceeds u32"))?;
let product_elements = plane_count
.checked_mul(image_height)
.and_then(|count| count.checked_mul(image_width))
.and_then(|count| count.checked_mul(3))
.ok_or_else(|| Error::out_of_range("image::corner_score scratch size exceeds u32"))?;
let products = Matrix::allocate(
input.runtime(),
vec![product_elements as usize],
product_elements as usize,
DType::F32,
)?;
let output = allocate_like(input, contract.name())?;
let gradient_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(products.storage()),
];
let gradient_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
];
let score_buffers = [
BufferBinding::read(products.storage()),
BufferBinding::write(output.storage()),
];
let score_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(block_size),
PushConstant::F32(k),
PushConstant::U32(score_type.code()),
];
let dispatches = [
ComputeDispatch {
kernel: KernelId::ImageCornerScoreGradientF32,
buffers: &gradient_buffers,
push_constants: &gradient_push,
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageCornerScoreF32,
buffers: &score_buffers,
push_constants: &score_push,
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
];
let attributes = [
unsigned("block_size", block_size),
float("k", k),
enumeration("score_type", score_type.token()),
];
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn corner_fast(input: &Image, arc_length: u32) -> Result<Image> {
if !(9..=16).contains(&arc_length) {
return Err(Error::invalid_argument(
"image::corner_fast arc_length must be in 9..=16",
));
}
let contract = crate::core::operation::image::CORNER_FAST;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let output = allocate_like(input, contract.name())?;
let attributes = [unsigned("arc_length", arc_length)];
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageCornerFastF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(arc_length),
],
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn bf_match(query: &Matrix, train: &Matrix) -> Result<Matrix> {
if query.dtype() != DType::U8 || train.dtype() != DType::U8 {
return Err(Error::invalid_argument(
"image::bf_match requires U8 descriptor matrices",
));
}
if query.shape().len() != 2 || train.shape().len() != 2 {
return Err(Error::invalid_argument(
"image::bf_match requires [N, D] descriptor matrices",
));
}
let desc_len = query.shape()[1];
if desc_len == 0 || train.shape()[1] != desc_len {
return Err(Error::invalid_argument(
"image::bf_match descriptor widths must match and be nonzero",
));
}
let query_count = query.shape()[0];
let train_count = train.shape()[0];
if query_count == 0 || train_count == 0 {
return Err(Error::invalid_argument(
"image::bf_match requires nonempty descriptor sets",
));
}
let query_count_u32 = u32::try_from(query_count)
.map_err(|_| Error::out_of_range("image::bf_match query count exceeds u32"))?;
let train_count_u32 = u32::try_from(train_count)
.map_err(|_| Error::out_of_range("image::bf_match train count exceeds u32"))?;
let desc_len_u32 = u32::try_from(desc_len)
.map_err(|_| Error::out_of_range("image::bf_match descriptor width exceeds u32"))?;
let output = Matrix::allocate(
query.runtime(),
vec![query_count, 4],
query_count
.checked_mul(4)
.ok_or_else(|| Error::out_of_range("image::bf_match output size exceeds u32"))?,
DType::F32,
)?;
let attributes = [];
query.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageBfMatchU8,
buffers: &[
BufferBinding::read(query.storage()),
BufferBinding::read(train.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(query_count_u32),
PushConstant::U32(train_count_u32),
PushConstant::U32(desc_len_u32),
],
workgroups: KernelId::ImageBfMatchU8.linear_workgroups(query_count_u32),
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::BF_MATCH,
inputs: &[
ImageSemanticInput::Matrix(query),
ImageSemanticInput::Matrix(train),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn good_features_to_track(
input: &Image,
max_corners: u32,
quality: f32,
min_distance: f32,
) -> Result<(Matrix, Matrix)> {
if !quality.is_finite()
|| !(0.0..=1.0).contains(&quality)
|| !min_distance.is_finite()
|| min_distance < 0.0
{
return Err(Error::invalid_argument(
"image::good_features_to_track requires quality in [0, 1] and finite min_distance >= 0",
));
}
let contract = crate::core::operation::image::GOOD_FEATURES_TO_TRACK;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::good_features_to_track plane count exceeds u32"))?;
let corner_cap = if max_corners == 0 {
image_height
.checked_mul(image_width)
.ok_or_else(|| Error::out_of_range("image::good_features_to_track plane size exceeds u32"))?
} else {
max_corners
};
let row_elements = plane_count
.checked_mul(image_height)
.ok_or_else(|| Error::out_of_range("image::good_features_to_track scratch size exceeds u32"))?;
let row_max = Matrix::allocate(
input.runtime(),
vec![row_elements as usize],
row_elements as usize,
DType::F32,
)?;
let thresholds = Matrix::allocate(
input.runtime(),
vec![plane_count as usize],
plane_count as usize,
DType::F32,
)?;
let counts = Matrix::allocate(
input.runtime(),
vec![plane_count as usize],
plane_count as usize,
DType::U32,
)?;
let keypoints = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, corner_cap as usize, 3],
plane_count
.checked_mul(corner_cap)
.and_then(|count| count.checked_mul(3))
.ok_or_else(|| {
Error::out_of_range("image::good_features_to_track keypoint size exceeds u32")
})? as usize,
DType::F32,
)?;
let clear_buffers = [
BufferBinding::write(keypoints.storage()),
BufferBinding::write(counts.storage()),
];
let clear_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(corner_cap),
];
let row_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(row_max.storage()),
];
let row_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
];
let threshold_buffers = [
BufferBinding::read(row_max.storage()),
BufferBinding::write(thresholds.storage()),
];
let threshold_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::F32(quality),
];
let select_buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(thresholds.storage()),
BufferBinding::write(keypoints.storage()),
BufferBinding::write(counts.storage()),
];
let select_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(corner_cap),
PushConstant::F32(min_distance),
];
let attributes = [
unsigned("max_corners", max_corners),
float("quality", quality),
float("min_distance", min_distance),
];
input.runtime().record_image_split_semantic(
&[
ComputeDispatch {
kernel: KernelId::ImageGoodFeaturesClearF32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageGoodFeaturesClearF32
.linear_workgroups(plane_count * corner_cap * 3),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageGoodFeaturesRowMaxF32,
buffers: &row_buffers,
push_constants: &row_push,
workgroups: KernelId::ImageGoodFeaturesRowMaxF32
.linear_workgroups(plane_count * image_height),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageGoodFeaturesThresholdF32,
buffers: &threshold_buffers,
push_constants: &threshold_push,
workgroups: KernelId::ImageGoodFeaturesThresholdF32.linear_workgroups(plane_count),
indirect: None,
},
ComputeDispatch {
kernel: KernelId::ImageGoodFeaturesSelectF32,
buffers: &select_buffers,
push_constants: &select_push,
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
],
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[
ImageSemanticOutput::Matrix(&keypoints),
ImageSemanticOutput::Matrix(&counts),
],
attributes: &attributes,
},
)?;
Ok((keypoints, counts))
}
pub fn orb(
input: &Image,
max_features: u32,
quality: f32,
min_distance: f32,
levels: u32,
edge: u32,
) -> Result<(Matrix, Matrix, Matrix)> {
if !quality.is_finite()
|| !(0.0..=1.0).contains(&quality)
|| !min_distance.is_finite()
|| min_distance < 0.0
{
return Err(Error::invalid_argument(
"image::orb requires quality in [0, 1] and finite min_distance >= 0",
));
}
if levels == 0 || edge < 18 {
return Err(Error::invalid_argument(
"image::orb requires levels >= 1 and edge >= 18 for the rotated BRIEF support",
));
}
let contract = crate::core::operation::image::ORB;
let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::orb plane count exceeds u32"))?;
let feature_cap = if max_features == 0 {
image_height
.checked_mul(image_width)
.ok_or_else(|| Error::out_of_range("image::orb plane size exceeds u32"))?
} else {
max_features
};
let level_cap = feature_cap;
let keypoints = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, feature_cap as usize, 6],
plane_count
.checked_mul(feature_cap)
.and_then(|count| count.checked_mul(6))
.ok_or_else(|| Error::out_of_range("image::orb keypoint size exceeds u32"))? as usize,
DType::F32,
)?;
let descriptors = Matrix::allocate(
input.runtime(),
vec![plane_count as usize, feature_cap as usize, 8],
plane_count
.checked_mul(feature_cap)
.and_then(|count| count.checked_mul(8))
.ok_or_else(|| Error::out_of_range("image::orb descriptor size exceeds u32"))? as usize,
DType::U32,
)?;
let counts = Matrix::allocate(
input.runtime(),
vec![plane_count as usize],
plane_count as usize,
DType::U32,
)?;
let clear_buffers = [
BufferBinding::write(keypoints.storage()),
BufferBinding::write(descriptors.storage()),
BufferBinding::write(counts.storage()),
];
let clear_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(feature_cap),
];
let mut level_images = Vec::with_capacity(levels as usize);
let mut level_dims = Vec::with_capacity(levels as usize);
let mut level_states = Vec::with_capacity(levels as usize);
level_images.push(input.clone());
level_dims.push((image_width, image_height, 1.0f32));
for _ in 1..levels {
let next = crate::image::pyr_down(
level_images
.last()
.ok_or_else(|| Error::internal("image::orb pyramid level missing"))?,
)?;
let (width, height, scale) = level_dims[level_dims.len() - 1];
level_dims.push((width.div_ceil(2), height.div_ceil(2), scale * 2.0));
level_images.push(next);
}
for level_image in &level_images {
let score_map = crate::image::corner_fast(level_image, 9)?;
let (level_keypoints, level_counts) =
crate::image::good_features_to_track(&score_map, level_cap, quality, min_distance)?;
level_states.push((level_keypoints, level_counts));
}
let mut describe_sets = Vec::with_capacity(levels as usize);
let mut describe_pushes = Vec::with_capacity(levels as usize);
for level in 0..levels {
let level_image = &level_images[level as usize];
let level_keypoints = &level_states[level as usize].0;
let level_counts = &level_states[level as usize].1;
let (level_width, level_height, level_scale) = level_dims[level as usize];
let describe_buffers = [
BufferBinding::read(level_image.storage()),
BufferBinding::read(level_keypoints.storage()),
BufferBinding::read(level_counts.storage()),
BufferBinding::write(keypoints.storage()),
BufferBinding::write(descriptors.storage()),
BufferBinding::write(counts.storage()),
];
let describe_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(level_cap),
PushConstant::U32(edge),
PushConstant::U32(feature_cap),
PushConstant::U32(level),
PushConstant::F32(level_scale),
];
describe_sets.push(describe_buffers);
describe_pushes.push(describe_push);
}
let attributes = [
unsigned("max_features", max_features),
float("quality", quality),
float("min_distance", min_distance),
unsigned("levels", levels),
unsigned("edge", edge),
];
let mut dispatches = Vec::with_capacity(describe_sets.len() + 1);
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageOrbClearF32,
buffers: &clear_buffers,
push_constants: &clear_push,
workgroups: KernelId::ImageOrbClearF32.linear_workgroups(plane_count * feature_cap * 8),
indirect: None,
});
for (buffers, push_constants) in describe_sets.iter().zip(describe_pushes.iter()) {
dispatches.push(ComputeDispatch {
kernel: KernelId::ImageOrbDescribeF32,
buffers: buffers.as_slice(),
push_constants: push_constants.as_slice(),
workgroups: KernelId::ImageOrbDescribeF32.linear_workgroups(plane_count * level_cap),
indirect: None,
});
}
input.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[
ImageSemanticOutput::Matrix(&keypoints),
ImageSemanticOutput::Matrix(&descriptors),
ImageSemanticOutput::Matrix(&counts),
],
attributes: &attributes,
},
)?;
Ok((keypoints, descriptors, counts))
}
pub fn optical_flow_pyr_lk(
previous: &Image,
next: &Image,
points: &Matrix,
levels: u32,
window: u32,
iterations: u32,
min_eigen: f32,
) -> Result<(Matrix, Matrix, Matrix)> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(previous, next, "image::optical_flow_pyr_lk")?;
if levels == 0 || window == 0 || iterations == 0 || !min_eigen.is_finite() || min_eigen <= 0.0 {
return Err(Error::invalid_argument(
"image::optical_flow_pyr_lk requires levels/window/iterations >= 1 and finite min_eigen > 0",
));
}
if points.dtype() != DType::F32
|| points.shape().len() != 2
|| points.shape()[0] == 0
|| points.shape()[1] != 2
{
return Err(Error::invalid_argument(
"image::optical_flow_pyr_lk requires a nonempty F32 [N, 2] points matrix",
));
}
let point_count = u32::try_from(points.shape()[0])
.map_err(|_| Error::out_of_range("image::optical_flow_pyr_lk point count exceeds u32"))?;
let support = window
.checked_mul(2)
.and_then(|value| value.checked_add(1))
.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk window exceeds u32"))?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk plane count exceeds u32"))?;
let state_elements = plane_count
.checked_mul(point_count)
.and_then(|count| count.checked_mul(2))
.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk state size exceeds u32"))?;
let map_elements = plane_count
.checked_mul(point_count)
.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk map size exceeds u32"))?;
let contract = crate::core::operation::image::OPTICAL_FLOW_PYR_LK;
let mut previous_levels = Vec::with_capacity(levels as usize);
let mut next_levels = Vec::with_capacity(levels as usize);
let mut level_dims = Vec::with_capacity(levels as usize);
previous_levels.push(previous.clone());
next_levels.push(next.clone());
level_dims.push((image_width, image_height));
for _ in 1..levels {
previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
)?)?);
next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
)?)?);
let (width, height) = level_dims[level_dims.len() - 1];
level_dims.push((width.div_ceil(2), height.div_ceil(2)));
}
let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
if coarsest_width < support || coarsest_height < support {
return Err(Error::invalid_argument(
"image::optical_flow_pyr_lk requires the coarsest level to fit the full window",
));
}
let next_points = Matrix::allocate(
previous.runtime(),
vec![plane_count as usize, point_count as usize, 2],
state_elements as usize,
DType::F32,
)?;
let status = Matrix::allocate(
previous.runtime(),
vec![plane_count as usize, point_count as usize],
map_elements as usize,
DType::F32,
)?;
let error = Matrix::allocate(
previous.runtime(),
vec![plane_count as usize, point_count as usize],
map_elements as usize,
DType::F32,
)?;
let mut stages = Vec::with_capacity(levels as usize);
for level in (0..levels).rev() {
let previous_level = &previous_levels[level as usize];
let next_level = &next_levels[level as usize];
let (level_width, level_height) = level_dims[level as usize];
let level_scale = 0.5f32.powi(level as i32);
let initialize = u32::from(level == levels - 1);
let finalize = u32::from(level == 0);
let refine_buffers = [
BufferBinding::read(previous_level.storage()),
BufferBinding::read(next_level.storage()),
BufferBinding::read(points.storage()),
BufferBinding::read_write(next_points.storage()),
BufferBinding::write(status.storage()),
BufferBinding::write(error.storage()),
];
let refine_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(point_count),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(window),
PushConstant::U32(iterations),
PushConstant::U32(initialize),
PushConstant::U32(finalize),
PushConstant::F32(level_scale),
PushConstant::F32(min_eigen),
];
stages.push((KernelId::ImageFlowLkRefineF32, refine_buffers, refine_push));
}
let attributes = [
unsigned("levels", levels),
unsigned("window", window),
unsigned("iterations", iterations),
float("min_eigen", min_eigen),
];
let dispatches: Vec<ComputeDispatch> = stages
.iter()
.map(|(kernel, buffers, push_constants)| ComputeDispatch {
kernel: *kernel,
buffers: buffers.as_slice(),
push_constants: push_constants.as_slice(),
workgroups: KernelId::ImageFlowLkRefineF32.linear_workgroups(plane_count * point_count),
indirect: None,
})
.collect();
previous.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[
ImageSemanticInput::Image(previous),
ImageSemanticInput::Image(next),
ImageSemanticInput::Matrix(points),
],
outputs: &[
ImageSemanticOutput::Matrix(&next_points),
ImageSemanticOutput::Matrix(&status),
ImageSemanticOutput::Matrix(&error),
],
attributes: &attributes,
},
)?;
Ok((next_points, status, error))
}
pub fn optical_flow_farneback(
previous: &Image,
next: &Image,
levels: u32,
window: u32,
iterations: u32,
poly_n: u32,
poly_sigma: f32,
) -> Result<Matrix> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(previous, next, "image::optical_flow_farneback")?;
if levels == 0
|| window == 0
|| iterations == 0
|| poly_n == 0
|| !poly_sigma.is_finite()
|| poly_sigma <= 0.0
{
return Err(Error::invalid_argument(
"image::optical_flow_farneback requires levels/window/iterations/poly_n >= 1 and finite poly_sigma > 0",
));
}
let poly_support = poly_n
.checked_mul(2)
.and_then(|value| value.checked_add(1))
.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback poly_n exceeds u32"))?;
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback plane count exceeds u32"))?;
let contract = crate::core::operation::image::OPTICAL_FLOW_FARNEBACK;
let mut previous_levels = Vec::with_capacity(levels as usize);
let mut next_levels = Vec::with_capacity(levels as usize);
let mut level_dims = Vec::with_capacity(levels as usize);
previous_levels.push(previous.clone());
next_levels.push(next.clone());
level_dims.push((image_width, image_height));
for _ in 1..levels {
previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
|| Error::internal("image::optical_flow_farneback pyramid level missing"),
)?)?);
next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
|| Error::internal("image::optical_flow_farneback pyramid level missing"),
)?)?);
let (width, height) = level_dims[level_dims.len() - 1];
level_dims.push((width.div_ceil(2), height.div_ceil(2)));
}
let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
if coarsest_width < poly_support || coarsest_height < poly_support {
return Err(Error::invalid_argument(
"image::optical_flow_farneback requires the coarsest level to fit the polynomial support",
));
}
let workspace_elements = |planes: u32| -> Result<usize> {
Ok(
planes
.checked_mul(image_height)
.and_then(|count| count.checked_mul(image_width))
.ok_or_else(|| {
Error::out_of_range("image::optical_flow_farneback workspace size exceeds u32")
})? as usize,
)
};
let moment_shape = vec![
plane_count as usize,
3,
image_height as usize,
image_width as usize,
];
let poly_shape = vec![
plane_count as usize,
5,
image_height as usize,
image_width as usize,
];
let flow_shape = vec![
plane_count as usize,
2,
image_height as usize,
image_width as usize,
];
let three_planes = plane_count.checked_mul(3).ok_or_else(|| {
Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
})?;
let five_planes = plane_count.checked_mul(5).ok_or_else(|| {
Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
})?;
let two_planes = plane_count.checked_mul(2).ok_or_else(|| {
Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
})?;
let moments_a = Matrix::allocate(
previous.runtime(),
moment_shape.clone(),
workspace_elements(three_planes)?,
DType::F32,
)?;
let moments_b = Matrix::allocate(
previous.runtime(),
moment_shape,
workspace_elements(three_planes)?,
DType::F32,
)?;
let poly1 = Matrix::allocate(
previous.runtime(),
poly_shape.clone(),
workspace_elements(five_planes)?,
DType::F32,
)?;
let poly2 = Matrix::allocate(
previous.runtime(),
poly_shape,
workspace_elements(five_planes)?,
DType::F32,
)?;
let flow_a = Matrix::allocate(
previous.runtime(),
flow_shape.clone(),
workspace_elements(two_planes)?,
DType::F32,
)?;
let flow_b = Matrix::allocate(
previous.runtime(),
flow_shape.clone(),
workspace_elements(two_planes)?,
DType::F32,
)?;
let flow = Matrix::allocate(
previous.runtime(),
flow_shape,
workspace_elements(two_planes)?,
DType::F32,
)?;
let mut stages = Vec::new();
let mut parent: Option<(&Matrix, u32, u32, bool)> = None;
for level in (0..levels).rev() {
let (level_width, level_height) = level_dims[level as usize];
{
let expand_input = &previous_levels[level as usize];
let expand_output = &moments_a;
let expand_v_buffers = [
BufferBinding::read(expand_input.storage()),
BufferBinding::write(expand_output.storage()),
];
let expand_v_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(poly_n),
PushConstant::F32(poly_sigma),
];
stages.push((
KernelId::ImageFlowExpandVF32,
expand_v_buffers.to_vec(),
expand_v_push.to_vec(),
[
level_width.div_ceil(16),
level_height.div_ceil(16),
plane_count,
],
));
}
{
let expand_input = &moments_a;
let expand_output = &poly1;
let expand_h_buffers = [
BufferBinding::read(expand_input.storage()),
BufferBinding::write(expand_output.storage()),
];
let expand_h_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(poly_n),
PushConstant::F32(poly_sigma),
];
stages.push((
KernelId::ImageFlowExpandHF32,
expand_h_buffers.to_vec(),
expand_h_push.to_vec(),
[
level_width.div_ceil(16),
level_height.div_ceil(16),
plane_count,
],
));
}
{
let expand_input = &next_levels[level as usize];
let expand_output = &moments_b;
let expand_v_buffers = [
BufferBinding::read(expand_input.storage()),
BufferBinding::write(expand_output.storage()),
];
let expand_v_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(poly_n),
PushConstant::F32(poly_sigma),
];
stages.push((
KernelId::ImageFlowExpandVF32,
expand_v_buffers.to_vec(),
expand_v_push.to_vec(),
[
level_width.div_ceil(16),
level_height.div_ceil(16),
plane_count,
],
));
}
{
let expand_input = &moments_b;
let expand_output = &poly2;
let expand_h_buffers = [
BufferBinding::read(expand_input.storage()),
BufferBinding::write(expand_output.storage()),
];
let expand_h_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(poly_n),
PushConstant::F32(poly_sigma),
];
stages.push((
KernelId::ImageFlowExpandHF32,
expand_h_buffers.to_vec(),
expand_h_push.to_vec(),
[
level_width.div_ceil(16),
level_height.div_ceil(16),
plane_count,
],
));
}
let mut estimate: &Matrix = &flow_a;
let mut estimate_is_a = true;
for iteration in 0..iterations {
let (flow_in, init_mode, flow_in_width, flow_in_height, input_is_a) = if iteration == 0 {
match parent {
Some((buffer, width, height, is_a)) => (buffer, 1u32, width, height, is_a),
None => (&flow_a, 0u32, level_width, level_height, true),
}
} else {
(estimate, 2u32, level_width, level_height, estimate_is_a)
};
let output_is_flow = level == 0 && iteration + 1 == iterations;
let flow_out: &Matrix = if output_is_flow {
&flow
} else if input_is_a {
&flow_b
} else {
&flow_a
};
let update_buffers = [
BufferBinding::read(poly1.storage()),
BufferBinding::read(poly2.storage()),
BufferBinding::read(flow_in.storage()),
BufferBinding::write(flow_out.storage()),
];
let update_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(flow_in_height),
PushConstant::U32(flow_in_width),
PushConstant::U32(window),
PushConstant::U32(init_mode),
];
stages.push((
KernelId::ImageFlowUpdateF32,
update_buffers.to_vec(),
update_push.to_vec(),
[
level_width.div_ceil(16),
level_height.div_ceil(16),
plane_count,
],
));
estimate = flow_out;
estimate_is_a = !input_is_a;
}
parent = Some((estimate, level_width, level_height, estimate_is_a));
}
let attributes = [
unsigned("levels", levels),
unsigned("window", window),
unsigned("iterations", iterations),
unsigned("poly_n", poly_n),
float("poly_sigma", poly_sigma),
];
let dispatches: Vec<ComputeDispatch> = stages
.iter()
.map(
|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
kernel: *kernel,
buffers: buffers.as_slice(),
push_constants: push_constants.as_slice(),
workgroups: *workgroups,
indirect: None,
},
)
.collect();
previous.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[
ImageSemanticInput::Image(previous),
ImageSemanticInput::Image(next),
],
outputs: &[ImageSemanticOutput::Matrix(&flow)],
attributes: &attributes,
},
)?;
Ok(flow)
}
pub fn stereo_bm(
left: &Image,
right: &Image,
num_disparities: u32,
block_size: u32,
uniqueness: u32,
) -> Result<Matrix> {
let (batch, channels, image_height, image_width) =
validate_accumulation_pair(left, right, "image::stereo_bm")?;
if num_disparities == 0 || block_size < 3 || block_size.is_multiple_of(2) {
return Err(Error::invalid_argument(
"image::stereo_bm requires num_disparities >= 1 and an odd block_size >= 3",
));
}
let support = block_size
.checked_sub(1)
.and_then(|value| value.checked_add(num_disparities))
.ok_or_else(|| Error::out_of_range("image::stereo_bm support exceeds u32"))?;
if image_width < support || image_height < block_size {
return Err(Error::invalid_argument(
"image::stereo_bm requires the image to fit the block and disparity support",
));
}
let plane_count = batch
.checked_mul(channels)
.ok_or_else(|| Error::out_of_range("image::stereo_bm plane count exceeds u32"))?;
let disp_count = plane_count
.checked_mul(num_disparities)
.ok_or_else(|| Error::out_of_range("image::stereo_bm disparity slots exceed u32"))?;
let block_radius = block_size / 2;
let plane_elements = (image_height as usize)
.checked_mul(image_width as usize)
.ok_or_else(|| Error::out_of_range("image::stereo_bm plane size exceeds u32"))?;
let cost_volume = Matrix::allocate(
left.runtime(),
vec![
plane_count as usize,
num_disparities as usize,
image_height as usize,
image_width as usize,
],
plane_elements
.checked_mul(disp_count as usize)
.ok_or_else(|| Error::out_of_range("image::stereo_bm cost volume exceeds u32"))?,
DType::F32,
)?;
let output = Matrix::allocate(
left.runtime(),
vec![
plane_count as usize,
1,
image_height as usize,
image_width as usize,
],
plane_elements
.checked_mul(plane_count as usize)
.ok_or_else(|| Error::out_of_range("image::stereo_bm output size exceeds u32"))?,
DType::F32,
)?;
let contract = crate::core::operation::image::STEREO_BM;
let mut stages = Vec::new();
{
let sad_buffers = [
BufferBinding::read(left.storage()),
BufferBinding::read(right.storage()),
BufferBinding::write(cost_volume.storage()),
];
let sad_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(num_disparities),
PushConstant::U32(block_radius),
];
stages.push((
KernelId::ImageStereoSadF32,
sad_buffers.to_vec(),
sad_push.to_vec(),
[
image_width.div_ceil(16),
image_height.div_ceil(16),
disp_count,
],
));
}
{
let wta_buffers = [
BufferBinding::read(cost_volume.storage()),
BufferBinding::write(output.storage()),
];
let wta_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(num_disparities),
PushConstant::U32(block_radius),
PushConstant::U32(uniqueness),
];
stages.push((
KernelId::ImageStereoWtaF32,
wta_buffers.to_vec(),
wta_push.to_vec(),
[
image_width.div_ceil(16),
image_height.div_ceil(16),
plane_count,
],
));
}
let attributes = [
unsigned("num_disparities", num_disparities),
unsigned("block_size", block_size),
unsigned("uniqueness", uniqueness),
];
let dispatches: Vec<ComputeDispatch> = stages
.iter()
.map(
|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
kernel: *kernel,
buffers: buffers.as_slice(),
push_constants: push_constants.as_slice(),
workgroups: *workgroups,
indirect: None,
},
)
.collect();
left.runtime().record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract,
inputs: &[
ImageSemanticInput::Image(left),
ImageSemanticInput::Image(right),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn reproject_image_to_3d(disparity: &Matrix, q: &Matrix) -> Result<Matrix> {
if disparity.dtype() != DType::F32 || q.dtype() != DType::F32 {
return Err(Error::invalid_argument(
"image::reproject_image_to_3d requires F32 disparity and q matrices",
));
}
if disparity.shape().len() != 4 || disparity.shape()[1] != 1 {
return Err(Error::invalid_argument(
"image::reproject_image_to_3d requires a [planes, 1, H, W] disparity matrix",
));
}
if q.shape() != [4, 4] {
return Err(Error::invalid_argument(
"image::reproject_image_to_3d requires a [4, 4] q matrix",
));
}
let plane_count = u32::try_from(disparity.shape()[0])
.map_err(|_| Error::out_of_range("image::reproject_image_to_3d plane count exceeds u32"))?;
let height = u32::try_from(disparity.shape()[2])
.map_err(|_| Error::out_of_range("image::reproject_image_to_3d height exceeds u32"))?;
let width = u32::try_from(disparity.shape()[3])
.map_err(|_| Error::out_of_range("image::reproject_image_to_3d width exceeds u32"))?;
if plane_count == 0 || height == 0 || width == 0 {
return Err(Error::invalid_argument(
"image::reproject_image_to_3d requires a nonempty disparity matrix",
));
}
let plane_elements = (height as usize)
.checked_mul(width as usize)
.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d plane size exceeds u32"))?;
let output = Matrix::allocate(
disparity.runtime(),
vec![plane_count as usize, 3, height as usize, width as usize],
plane_elements
.checked_mul(3)
.and_then(|count| count.checked_mul(plane_count as usize))
.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d output size exceeds u32"))?,
DType::F32,
)?;
let attributes = [];
disparity.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageReproject3dF32,
buffers: &[
BufferBinding::read(disparity.storage()),
BufferBinding::read(q.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(plane_count),
PushConstant::U32(1),
PushConstant::U32(height),
PushConstant::U32(width),
],
workgroups: [width.div_ceil(16), height.div_ceil(16), plane_count],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::REPROJECT_IMAGE_TO_3D,
inputs: &[
ImageSemanticInput::Matrix(disparity),
ImageSemanticInput::Matrix(q),
],
outputs: &[ImageSemanticOutput::Matrix(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn fast_nl_means_denoising(
input: &Image,
h: f32,
template_window: u32,
search_window: u32,
) -> Result<Image> {
let (batch, channels, image_height, image_width) =
image_extent(input, "image::fast_nl_means_denoising")?;
if !h.is_finite() || h <= 0.0 {
return Err(Error::invalid_argument(
"image::fast_nl_means_denoising requires a finite positive h",
));
}
if template_window < 3
|| template_window.is_multiple_of(2)
|| search_window < 3
|| search_window.is_multiple_of(2)
{
return Err(Error::invalid_argument(
"image::fast_nl_means_denoising requires odd template_window/search_window >= 3",
));
}
let template_radius = template_window / 2;
let search_radius = search_window / 2;
let h_sqr = h * h;
let output = allocate_like(input, "image::fast_nl_means_denoising")?;
let attributes = [
float("h", h),
unsigned("template_window", template_window),
unsigned("search_window", search_window),
];
input.runtime().record_image_semantic(
ComputeDispatch {
kernel: KernelId::ImageNlMeansDenoiseF32,
buffers: &[
BufferBinding::read(input.storage()),
BufferBinding::write(output.storage()),
],
push_constants: &[
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(image_height),
PushConstant::U32(image_width),
PushConstant::U32(template_radius),
PushConstant::U32(search_radius),
PushConstant::F32(h_sqr),
],
workgroups: [
image_width.div_ceil(16),
image_height.div_ceil(16),
batch * channels,
],
indirect: None,
},
ImageSemanticDispatch {
contract: crate::core::operation::image::FAST_NL_MEANS_DENOISING,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
Ok(output)
}
pub fn pyr_mean_shift_filtering(input: &Image, sp: f32, sr: f32, max_level: u32) -> Result<Image> {
let (batch, channels, image_height, image_width) =
image_extent(input, "image::pyr_mean_shift_filtering")?;
if !sp.is_finite() || sp <= 0.0 || !sr.is_finite() || sr <= 0.0 {
return Err(Error::invalid_argument(
"image::pyr_mean_shift_filtering requires finite positive sp and sr",
));
}
if channels > 4 {
return Err(Error::invalid_argument(
"image::pyr_mean_shift_filtering supports at most 4 channels",
));
}
if !(1..=4).contains(&max_level) {
return Err(Error::invalid_argument(
"image::pyr_mean_shift_filtering requires max_level in [1, 4]",
));
}
let levels = max_level
.checked_add(1)
.ok_or_else(|| Error::out_of_range("image::pyr_mean_shift_filtering max_level exceeds u32"))?;
let spatial_radius = sp.ceil() as u32;
let range_radius_sqr = sr * sr;
let mut level_images = Vec::with_capacity(levels as usize);
let mut level_dims = Vec::with_capacity(levels as usize);
level_images.push(input.clone());
level_dims.push((image_width, image_height));
for _ in 1..levels {
level_images.push(crate::image::pyr_down(level_images.last().ok_or_else(
|| Error::internal("image::pyr_mean_shift_filtering pyramid level missing"),
)?)?);
let (width, height) = level_dims[level_dims.len() - 1];
level_dims.push((width.div_ceil(2), height.div_ceil(2)));
}
let runtime = input.runtime();
let mut workspaces = Vec::with_capacity(levels as usize - 1);
for level in 1..levels {
let (level_width, level_height) = level_dims[level as usize];
let count = (batch as usize)
.checked_mul(channels as usize)
.and_then(|value| value.checked_mul(level_height as usize))
.and_then(|value| value.checked_mul(level_width as usize))
.ok_or_else(|| {
Error::out_of_range("image::pyr_mean_shift_filtering workspace exceeds usize")
})?;
workspaces.push(Matrix::allocate(
runtime,
vec![
batch as usize,
channels as usize,
level_height as usize,
level_width as usize,
],
count,
DType::F32,
)?);
}
let output = allocate_like(input, "image::pyr_mean_shift_filtering")?;
let mut stages = Vec::new();
for level in (0..levels).rev() {
let (level_width, level_height) = level_dims[level as usize];
let shift_input = level_images[level as usize].as_matrix();
let shift_output: &Matrix = if level == 0 {
output.as_matrix()
} else {
&workspaces[level as usize - 1]
};
let (shift_seed, seed_width, seed_height, init_mode) = if level + 1 == levels {
(shift_input, level_width, level_height, 0u32)
} else {
let (seed_width, seed_height) = level_dims[level as usize + 1];
(&workspaces[level as usize], seed_width, seed_height, 1u32)
};
let pass_buffers = [
BufferBinding::read(shift_input.storage()),
BufferBinding::read(shift_seed.storage()),
BufferBinding::write(shift_output.storage()),
];
let pass_push = [
PushConstant::U32(batch),
PushConstant::U32(channels),
PushConstant::U32(level_height),
PushConstant::U32(level_width),
PushConstant::U32(seed_width),
PushConstant::U32(seed_height),
PushConstant::U32(spatial_radius),
PushConstant::U32(5),
PushConstant::U32(init_mode),
PushConstant::F32(range_radius_sqr),
];
stages.push((
KernelId::ImageMeanShiftPassF32,
pass_buffers.to_vec(),
pass_push.to_vec(),
[level_width.div_ceil(16), level_height.div_ceil(16), batch],
));
}
let attributes = [
float("sp", sp),
float("sr", sr),
unsigned("max_level", max_level),
];
let dispatches: Vec<ComputeDispatch> = stages
.iter()
.map(
|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
kernel: *kernel,
buffers: buffers.as_slice(),
push_constants: push_constants.as_slice(),
workgroups: *workgroups,
indirect: None,
},
)
.collect();
runtime.record_image_split_semantic(
&dispatches,
ImageSemanticDispatch {
contract: crate::core::operation::image::PYR_MEAN_SHIFT_FILTERING,
inputs: &[ImageSemanticInput::Image(input)],
outputs: &[ImageSemanticOutput::Image(&output)],
attributes: &attributes,
},
)?;
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.runtime(),
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(),
}
}
fn validate_accumulation_pair(
first: &Image,
second: &Image,
operation: &str,
) -> Result<(u32, u32, u32, u32)> {
let extent = image_extent(first, operation)?;
if second.as_matrix().shape() != first.as_matrix().shape()
|| second.layout() != first.layout()
|| second.format() != first.format()
|| second.dtype() != first.dtype()
{
return Err(Error::invalid_argument(format!(
"{operation} requires identically shaped FP32 images"
)));
}
Ok(extent)
}