Of course! Applying a Gaussian kernel to a 1D vector is a common operation for smoothing or blurring data. This process is also known as convolution.
Here's a complete guide with Rust code, broken down into clear steps:
- Generate the Gaussian Kernel: A list of weights that follow a Gaussian (bell curve) distribution.
- Perform the Convolution: Slide the kernel across the input vector, and at each point, compute a weighted sum of the neighboring elements.
- Handle Boundaries: Decide what to do when the kernel hangs off the edges of the vector.
Let's build a complete, runnable example.
1. The Full Code Example
This example includes a function to generate the kernel and another to apply it.
fn main() {
// 1. Define our input data. A spike is good for seeing the smoothing effect.
let input_data: Vec<f64> = vec![0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
// 2. Define kernel parameters
let kernel_radius = 2; // The number of elements on each side of the center
let kernel_size = 2 * kernel_radius + 1; // Must be an odd number (e.g., 3, 5, 7)
let sigma = 1.5; // Standard deviation, controls the "width" of the blur
// 3. Generate the Gaussian kernel
let kernel = generate_gaussian_kernel(kernel_size, sigma);
// 4. Apply the kernel to the data
let smoothed_data = apply_kernel(&input_data, &kernel);
// 5. Print the results
println!("Original Data: {:?}", input_data);
println!("Gaussian Kernel (size={}, sigma={}):", kernel_size, sigma);
// Print kernel with formatting
let kernel_str: Vec<String> = kernel.iter().map(|&v| format!("{:.4}", v)).collect();
println!("[{}] (Sum: {:.4})", kernel_str.join(", "), kernel.iter().sum::<f64>());
println!("\nSmoothed Data:");
// Print smoothed data with formatting
let smoothed_str: Vec<String> = smoothed_data.iter().map(|&v| format!("{:.4}", v)).collect();
println!("[{}]", smoothed_str.join(", "));
}
/// Generates a 1D Gaussian kernel.
///
/// # Arguments
/// * `size` - The size of the kernel. Must be an odd number.
/// * `sigma` - The standard deviation of the Gaussian function.
///
/// # Returns
/// A `Vec<f64>` containing the normalized kernel weights.
fn generate_gaussian_kernel(size: usize, sigma: f64) -> Vec<f64> {
// Ensure the kernel size is odd
assert!(size % 2 == 1, "Kernel size must be odd.");
let mut kernel = vec![0.0; size];
let center = (size / 2) as i32;
let mut sum = 0.0;
for i in 0..size {
let x = (i as i32 - center) as f64;
// Gaussian function formula
let value = (- (x * x) / (2.0 * sigma * sigma)).exp();
kernel[i] = value;
sum += value;
}
// Normalize the kernel so that all its elements sum to 1.0
// This is crucial to not change the overall "energy" of the signal.
for val in kernel.iter_mut() {
*val /= sum;
}
kernel
}
/// Applies a 1D kernel (convolution) to a vector of data.
///
/// # Arguments
/// * `data` - A slice of the data to be processed.
/// * `kernel` - A slice representing the kernel to apply. Its length must be odd.
///
/// # Returns
/// A `Vec<f64>` containing the data after the kernel has been applied.
fn apply_kernel(data: &[f64], kernel: &[f64]) -> Vec<f64> {
let data_len = data.len();
let kernel_len = kernel.len();
let kernel_center = kernel_len / 2;
// Create an output vector of the same size as the input
let mut output = vec![0.0; data_len];
// Iterate over each data point
for i in 0..data_len {
let mut weighted_sum = 0.0;
// Iterate over the kernel
for j in 0..kernel_len {
// Calculate the corresponding index in the data vector
// We use `i32` to handle potential negative indices before clamping
let data_index = (i as i32) + (j as i32) - (kernel_center as i32);
// --- Boundary Handling ---
// Here, we "clamp" or "extend" the boundaries.
// If the index is out of bounds, we use the value at the nearest boundary.
let clamped_index = data_index.max(0).min(data_len as i32 - 1) as usize;
weighted_sum += data[clamped_index] * kernel[j];
}
output[i] = weighted_sum;
}
output
}
How to Run
- Save the code as
main.rs.
- Run it using
rustc main.rs && ./main.
Expected Output
Original Data: [0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Gaussian Kernel (size=5, sigma=1.5):
[0.1201, 0.2339, 0.2921, 0.2339, 0.1201] (Sum: 1.0000)
Smoothed Data:
[0.0000, 0.0000, 1.2008, 2.3386, 2.9211, 2.3386, 1.2008, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
As you can see, the single spike of 10.0 has been "spread out" or "smoothed" across its neighbors according to the weights in the Gaussian kernel.
Explanation of the Code
generate_gaussian_kernel
- Assertion: We ensure the kernel size is odd (
size % 2 == 1). An odd-sized kernel has a clear center element, which is essential for aligning it with the data points.
- Formula: The core of the function is
(- (x * x) / (2.0 * sigma * sigma)).exp(). This is the standard formula for a Gaussian function.
x is the distance from the kernel's center.
sigma (standard deviation) controls the "width" of the bell curve. A smaller sigma gives a sharper peak (less smoothing), while a larger sigma gives a wider, flatter curve (more smoothing).
- Normalization: We divide every element in the kernel by the sum of all its elements. This makes the kernel's weights sum to
1.0. This is critical because it ensures the overall brightness/magnitude of the signal is preserved after smoothing. Without normalization, the data would get progressively darker or brighter with each application.
apply_kernel
- Convolution Logic: The nested loops are the heart of the convolution. The outer loop (
i) iterates through each element of the data. The inner loop (j) slides the kernel over that data point.
- Weighted Sum: For each data point
data[i], we calculate a new value by summing up its neighbors, where each neighbor is multiplied by the corresponding weight from the kernel.
- Boundary Handling: The most important detail here is
let clamped_index = data_index.max(0).min(data_len as i32 - 1) as usize;.
- When the kernel is near the beginning of the data,
data_index can become negative.
- When it's near the end,
data_index can exceed the maximum index.
- This line "clamps" the index to the valid range
[0, data_len - 1]. This is called "Extend" or "Replicate" padding, where the value of the edge pixel is used for any out-of-bounds access.
Other common boundary handling methods include:
- Zero Padding: Assume all out-of-bounds values are
0.0.
- Wrap/Repeat: Treat the data as if it's circular (the end wraps around to the beginning).
- Mirror: Reflect the data at the boundary.
For Production Use: Using a Crate
For serious numerical computing, you'd typically use a library like ndarray. While it doesn't have a one-line convolve function like NumPy, its windows method makes the implementation very clean and efficient.
Here's how you might do it with ndarray:
Cargo.toml:
[dependencies]
ndarray = "0.15"
Rust code:
use ndarray::{Array1, Ix1};
// Use the same generate_gaussian_kernel function from before
fn apply_kernel_ndarray(data: &Array1<f64>, kernel: &Array1<f64>) -> Array1<f64> {
let data_len = data.len();
let kernel_len = kernel.len();
let kernel_center = kernel_len / 2;
// Pad the data array to handle boundaries easily
let mut padded_data = Array1::zeros(data_len + 2 * kernel_center);
padded_data.slice_mut(s![kernel_center..kernel_center + data_len]).assign(data);
// Replicate padding for the start and end
for i in 0..kernel_center {
padded_data[i] = data[0];
padded_data[kernel_center + data_len + i] = data[data_len - 1];
}
// Use sliding windows to perform the convolution
let convolved = padded_data
.windows(kernel.dim())
.into_iter()
.map(|window| (&window * kernel).sum())
.collect::<Array1<f64>>();
convolved
}
// In main, you would convert your Vec to an Array1:
// let data_arr = Array1::from(input_data);
// let kernel_arr = Array1::from(kernel);
// let smoothed_arr = apply_kernel_ndarray(&data_arr, &kernel_arr);
This ndarray approach is often more performant and expressive for complex array manipulations.