use crate::error::Error;
use crate::filter::gaussian_smooth;
use itertools::Itertools;
use ndarray::{Array, Array2, AsArray, Axis, Dimension, IntoDimension, stack};
use std::cmp::Ordering;
pub trait Filter {
type Error;
fn filter_array<'a, A, D>(&self, array: A) -> Result<Array<f64, D>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension;
}
#[derive(Debug, Clone, PartialEq)]
pub struct DoG {
pub lower: Vec<f64>,
pub upper: Vec<f64>,
}
impl DoG {
pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
Self { lower, upper }
}
}
impl Filter for DoG {
type Error = Error;
fn filter_array<'a, A, D>(&self, array: A) -> Result<Array<f64, D>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let array = array.into();
Ok(gaussian_smooth(&array, &self.lower)? - gaussian_smooth(array, &self.upper)?)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LoG {}
impl LoG {
pub fn new() -> Self {
Self {}
}
}
impl Default for LoG {
fn default() -> Self {
Self::new()
}
}
impl Filter for LoG {
type Error = Error;
fn filter_array<'a, A, D>(&self, _array: A) -> Result<Array<f64, D>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
todo!()
}
}
pub trait Detector {
type Error;
fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension;
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AbsoluteThreshold {
pub threshold: f64,
}
impl AbsoluteThreshold {
pub fn new(threshold: f64) -> Self {
Self { threshold }
}
}
impl Detector for AbsoluteThreshold {
type Error = Error;
fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let array = array.into().into_dyn();
let candidates = local_maxima(array.view());
let a = candidates
.rows()
.into_iter()
.filter(|&x| {
if let Some(s) = x.as_slice() {
array[s] > self.threshold
} else {
let s = x.to_vec();
array[s.as_slice()] > self.threshold
}
})
.collect::<Vec<_>>();
Ok(stack(Axis(0), &a)?)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StdThreshold {
pub threshold: f64,
}
impl StdThreshold {
pub fn new(threshold: f64) -> Self {
Self { threshold }
}
}
impl Detector for StdThreshold {
type Error = Error;
fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let array = array.into().into_dyn();
let std = array.std(0.0) * self.threshold;
let candidates = local_maxima(array.view());
let a = candidates
.rows()
.into_iter()
.filter(|&x| {
if let Some(s) = x.as_slice() {
array[s] > std
} else {
let s = x.to_vec();
array[s.as_slice()] > std
}
})
.collect::<Vec<_>>();
Ok(stack(Axis(0), &a)?)
}
}
pub fn local_maxima<'a, A, D>(frame: A) -> Array2<usize>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let frame = frame.into();
let shape = frame.shape();
let ndim = frame.ndim();
let offsets: Vec<Vec<i8>> = (0..ndim)
.map(|_| -1i8..=1)
.multi_cartesian_product()
.filter(|off| off.iter().any(|&d| d != 0))
.collect();
let mut coords = Vec::new();
for (position, ¢er) in frame.indexed_iter() {
let index = position.into_dimension();
let coord = index.as_array_view();
let mut is_max = true;
for off in &offsets {
let mut neighbor = index.clone();
let mut out_of_bounds = false;
for (axis, &d) in off.iter().enumerate() {
match d {
-1 => {
if coord[axis] == 0 {
out_of_bounds = true;
break;
}
neighbor[axis] -= 1;
}
1 => {
if coord[axis] + 1 >= shape[axis] {
out_of_bounds = true;
break;
}
neighbor[axis] += 1;
}
_ => {}
}
}
if out_of_bounds {
continue;
}
if let Some(Ordering::Less) =
center.partial_cmp(frame.get(neighbor).expect("neighbor out of bounds"))
{
is_max = false;
break;
}
}
if is_max {
coords.extend(coord.iter().copied());
}
}
let count = coords.len().checked_div(ndim).unwrap_or(frame.len());
let maxima: Array2<usize> =
Array2::<usize>::from_shape_vec((count, ndim), coords).expect("shape/length mismatch");
maxima
}