Skip to content

Commit

Permalink
Improvements on median_filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Agathoklis Papadopoulos committed Oct 18, 2023
1 parent afda38c commit 787d638
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "utils-box"
version = "0.1.4"
version = "0.1.5"
edition = "2021"
authors = ["Agathoklis Papadopoulos <klis.pap@gmail.com>"]
license = "MIT"
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ A toolbox library that holds a useful collection of small unitilies written in R

# Utilities provided:

## Mathematics
A collection of useful methematic methods used in various DSP and other applications

## Archives
Extract files from Tar, Gz and Zip Files

Expand Down
22 changes: 11 additions & 11 deletions src/mathematics/median_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ pub enum MedianPaddingMode {
/// Wrapper to call median_filter() with the most useful configuration
/// ZeroPad and IncludeNaN are active
pub fn medianfilter_default(x: &[f64], n: usize) -> Vec<f64> {
return moving_median_filter(
moving_median_filter(
x,
n,
MedianPaddingMode::ZeroPad,
MedianMissingMode::IncludeNaN,
);
)
}

/// An implementation of Moving Median Filtering
Expand All @@ -32,7 +32,7 @@ pub fn moving_median_filter(
) -> Vec<f64> {
let len = x.len();
let mut y = vec![0.0; len];
for i in 0..len {
for (i, y_value) in y.iter_mut().enumerate() {
let mut segment: Vec<f64> = vec![];
let mut segment_start: i64 = i as i64 - (n as i64 - 1) / 2;
if n % 2 == 0 {
Expand All @@ -41,10 +41,9 @@ pub fn moving_median_filter(
for j in 0..n {
let index = segment_start + j as i64;
if index < 0 || index >= len as i64 {
if padding == MedianPaddingMode::ZeroPad {
segment.push(0.0);
} else if padding == MedianPaddingMode::Truncate {
continue;
match padding {
MedianPaddingMode::ZeroPad => segment.push(0.0),
MedianPaddingMode::Truncate => continue,
}
} else {
segment.push(x[index as usize]);
Expand All @@ -56,20 +55,21 @@ pub fn moving_median_filter(
}

if segment.iter().any(|x| x.is_nan()) {
y[i] = f64::NAN;
*y_value = f64::NAN;
continue;
}

segment.sort_by(|a, b| a.partial_cmp(b).unwrap());

if segment.len() % 2 == 1 {
y[i] = segment[segment.len() / 2];
*y_value = segment[segment.len() / 2];
} else {
let middle = segment.len() / 2;
y[i] = (segment[middle - 1] + segment[middle]) / 2.0;
*y_value = (segment[middle - 1] + segment[middle]) / 2.0;
}
}
return y;

y
}

fn remove_nan(segment: &[f64]) -> Vec<f64> {
Expand Down

0 comments on commit 787d638

Please sign in to comment.