use crate::error::{BarracudaError, Result};
pub const WGSL_IOU_F64: &str = include_str!("../../shaders/misc/iou_f64.wgsl");
mod compute;
#[cfg(test)]
mod tests;
#[derive(Clone, Debug)]
pub struct BoundingBox {
pub x1: f32,
pub y1: f32,
pub x2: f32,
pub y2: f32,
pub score: f32,
}
pub struct NMS {
boxes: Vec<BoundingBox>,
iou_threshold: f32,
}
impl NMS {
pub fn new(boxes: Vec<BoundingBox>, iou_threshold: f32) -> Result<Self> {
if !(0.0..=1.0).contains(&iou_threshold) {
return Err(BarracudaError::invalid_op(
"NMS",
format!("iou_threshold must be in [0, 1], got {iou_threshold}"),
));
}
Ok(Self {
boxes,
iou_threshold,
})
}
pub(super) fn boxes(&self) -> &[BoundingBox] {
&self.boxes
}
pub(super) fn iou_threshold(&self) -> f32 {
self.iou_threshold
}
pub(super) fn wgsl_shader() -> &'static str {
static SHADER: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
include_str!("../../shaders/detection/nms_f64.wgsl").to_string()
});
SHADER.as_str()
}
}
#[must_use]
pub fn compute_iou(box1: &BoundingBox, box2: &BoundingBox) -> f32 {
let x1 = box1.x1.max(box2.x1);
let y1 = box1.y1.max(box2.y1);
let x2 = box1.x2.min(box2.x2);
let y2 = box1.y2.min(box2.y2);
let intersection = ((x2 - x1).max(0.0)) * ((y2 - y1).max(0.0));
let area1 = (box1.x2 - box1.x1) * (box1.y2 - box1.y1);
let area2 = (box2.x2 - box2.x1) * (box2.y2 - box2.y1);
let union = area1 + area2 - intersection;
if union > 0.0 {
intersection / union
} else {
0.0
}
}
pub fn nms(boxes: Vec<BoundingBox>, iou_threshold: f32) -> Result<Vec<usize>> {
NMS::new(boxes, iou_threshold)?.execute()
}