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.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)
}
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)
}
#[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.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(),
}
}