To apply a Gaussian kernel (Gaussian blur) to a 1D vector in Rust, you generally need to:
- Define the Gaussian kernel (a small vector of weights).
- Convolve the input vector with the kernel.
Here’s a simple example of how you might do this in Rust:
fn gaussian_kernel_1d(sigma: f64, radius: usize) -> Vec<f64> {
let mut kernel = Vec::with_capacity(2 * radius + 1);
let sigma2 = 2.0 * sigma * sigma;
let mut sum = 0.0;
for i in 0..(2 * radius + 1) {
let x = i as isize - radius as isize;
let value = (-((x * x) as f64) / sigma2).exp();
kernel.push(value);
sum += value;
}
// Normalize the kernel so that sum = 1
for v in &mut kernel {
*v /= sum;
}
kernel
}
fn apply_gaussian_kernel_1d(input: &[f64], kernel: &[f64]) -> Vec<f64> {
let radius = kernel.len() / 2;
let n = input.len();
let mut output = vec![0.0; n];
for i in 0..n {
let mut acc = 0.0;
for j in 0..kernel.len() {
let idx = i as isize + j as isize - radius as isize;
if idx >= 0 && (idx as usize) < n {
acc += input[idx as usize] * kernel[j];
}
}
output[i] = acc;
}
output
}
fn main() {
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0];
let sigma = 1.0;
let radius = 3; // kernel size = 7 (2*radius + 1)
let kernel = gaussian_kernel_1d(sigma, radius);
println!("Kernel: {:?}", kernel);
let smoothed = apply_gaussian_kernel_1d(&data, &kernel);
println!("Smoothed data: {:?}", smoothed);
}
Explanation:
gaussian_kernel_1d generates a Gaussian kernel with a given sigma and radius.
apply_gaussian_kernel_1d convolves the input vector with the kernel, handling boundaries by ignoring out-of-range indices.
- The kernel is normalized so the sum of weights is 1, preserving the overall signal magnitude.
You can adjust sigma and radius to control the smoothness and size of the kernel.
If you want a more optimized or feature-rich approach, you might consider using crates like ndarray or convolve for convolution operations. But the above is a straightforward pure Rust implementation.