Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions docs/docs/reference/wasm/modules/image/bilateral_filter/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@
id: api
title: Bilateral Filter — API & Reference
sidebar_label: API / Usage
sidebar_position: 5
sidebar_position: 4
---

# Bilateral Filter — API & Reference

Quick reference for the function implemented in the header.

```cpp title="Applies a bilateral filter to an RGBA image (modified in-place)."
void bilateral_filter(uint8_t *image,
size_t width, size_t height,
double sigma_spatial,
double sigma_range)
```cpp title="Applies a bilateral filter to an RGBA uint8_t* image (modified in-place)."
void bilateral_filter(uint8_t *image, size_t width, size_t height, double sigma_spatial, double sigma_range, uint8_t color_space)
```

:::important Alpha Channel Preservation
The alpha channel, `image[i + 3]`, is left untouched - it is not part of the bilateral filter implementation.
:::

## Parameters

| Parameter | Type | Description |
Expand All @@ -25,6 +26,7 @@ void bilateral_filter(uint8_t *image,
| `height` | `size_t` | Height of the image in pixels. |
| `sigma_spatial` | `double` | Spatial standard deviation ($\sigma_s$). Controls how far pixels influence each other spatially. |
| `sigma_range` | `double` | Range standard deviation ($\sigma_r$). Controls how much color definition is preserved (edge preservation). |
| `color_space` | `uint8_t` | Toggle color space to use for range distance (0 - CIELAB, 1 - RGB). CIELAB produces perceptually better results but requires more computation. |

:::info Implementation Details
- **Namespace**: `bilateral` (C++)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
id: explained
title: Implementation Explained
sidebar_position: 6
sidebar_position: 5
---

# Bilateral Filter — Implementation Explained
Expand All @@ -19,24 +19,37 @@ This prevents the "blurring" from crossing strong edges, where the color differe
## How It Works

For each pixel in the image, we look at a local window (kernel) around it. The new pixel value is a weighted average of its neighbors:

$$
I_{new}(x) = \frac{1}{W_p} \sum_{x_i \in \Omega} I(x_i) \cdot w_{spatial}(\|x_i - x\|) \cdot w_{range}(|I(x_i) - I(x)|)
$$

Where:
- $w_{spatial}$ is a Gaussian function of the distance.
- $w_{range}$ is a Gaussian function of the intensity difference.
- $W_p$ is the normalization factor (sum of all weights).



Where each component means:

- $x$: The coordinates of the **center pixel** being filtered.
- $\Omega$: The set of **neighboring pixels** in the local kernel around $x$ (from `-radius` to `+radius`).
- $I(x_i)$: The **color or intensity** of a neighbor pixel $x_i$.
- $C(x_i)$: The **color vector** of pixel $x_i$.
- RGB: `[R, G, B]`
- CIELAB: `[L*, a*, b*]`
- $w_{spatial}(|x_i - x|)$: A **Gaussian weight** based on the **spatial distance** between the neighbor and the center.
- Pixels closer to the center have **larger weights**.
- Formula: $\exp\Big(-\frac{\text{distance}^2}{2\sigma_s^2}\Big)$
- $w_\text{range}(|C(x_i) - C(x)|)$: A **Gaussian weight** based on the **color difference** between neighbor and center.
- Pixels with **similar colors** have higher weights, preserving edges.
- Formula: $\exp\Big(-\frac{|C(x_i) - C(x)|^2}{2\sigma_r^2}\Big)$
- RGB: Precomputed via **LUT**
- CIELAB: Computed **on the fly**
- $W_p = \sum_{x_i \in \Omega} w_{spatial} \cdot w_\text{range}$: **Normalization factor** to ensure the weighted average sums to a valid color.
- **Result $I_\text{new}(x)$**: The **filtered color** of the center pixel after combining spatial and color-based weighting.
- $|I(x_i) - I(x)|$: The Euclidean norm.
- **RGB**: $|I(x_i) - I(x)| = \sqrt{ \Delta R² + \Delta G² + \Delta B² }$
- **CIELAB**: $|I(x_i) - I(x)| = \sqrt{ \Delta L² + \Delta a² + \Delta b² }$

:::info
In this implementation, both weighting terms are **Gaussian kernels**:

$$
w_{\text{spatial}}(d) = \exp!\left(-\frac{d^2}{2\sigma_s^2}\right),
w_{spatial}(d) = \exp!\left(-\frac{d^2}{2\sigma_s^2}\right),
\quad
w_{\text{range}}(d) = \exp!\left(-\frac{d^2}{2\sigma_r^2}\right)
$$
Expand All @@ -45,9 +58,9 @@ where $ \sigma_s$ controls spatial smoothing and $\sigma_r$ controls edge sensit
:::
## Implementation Details

Our implementation uses a **naive sliding window** approach with **Look-Up Table (LUT) optimizations** to improve performance in WebAssembly.
Our implementation uses a **naive sliding window** approach with **Look-Up Table (LUT) optimizations / "On the Fly" computations** to improve performance.

### 1. Precomputed Look-Up Tables
### 1. Precomputed Look-Up Tables (RGB color space)

Calculating `std::exp()` inside the inner loop is expensive. We precompute the two Gaussian functions:
- **Spatial Weights**: A 2D grid of weights based on the kernel radius. Since the spatial distance between a neighbor and the center never changes, this is calculated once per filter application.
Expand All @@ -60,13 +73,35 @@ for (int i = 0; i <= MAX_RGB_DIST_SQ; ++i) {
}
```

### 2. The Loop
### 2. On-the-fly Range weights (CIE-LAB color space)

When deriving range weights in the CIELAB color space, the LUT approach does not work
(see the [Range Weights section in the implementation docs](../implementation/#range-weights) to understand why).
Instead range weights are computed on the fly using the `gaussian` function.

Since the RGB to CIELAB conversion is expensive, redundant computations are minimized by initially converting the full RGB image to CIELAB image.

In the convolution step LAB distance is computed by reading those values from the CIELAB image buffer, and the gaussian is then evaluated.
```
dL = cie_image[neighbor_idx] - L0;
dA = cie_image[neighbor_idx + 1] - A0;
dB = cie_image[neighbor_idx + 2] - B0;

dist = std::sqrt(dL * dL + dA * dA + dB * dB);
w_range = gaussian(dist, sigma_range);
```

:::note
`gaussian` itself is expensive to run. Future optimizations will include polynomial approximations of `exp(-x^2)` via Taylor expansion or Horner's method.
:::

### 3. The Loop

We iterate over every pixel `(y, x)` and then over every neighbor `(ky, kx)` within the kernel radius:

1. **Load Neighbor**: Get RGB values of the neighbor.
2. **Spatial Weight**: Look up precomputed $G_{\sigma_{spatial}}$.
3. **Range Weight**: Calculate squared color distance $\|C_p - C_q\|^2$ and look up precomputed $G_{\sigma_{range}}$.
3. **Range Weight**: Calculate squared color distance $\|C_p - C_q\|^2$ and look up precomputed $G_{\sigma_{range}}$ if using RGB, or compute on the fly if using CIELAB.
4. **Accumulate**: `pixel_acc += neighbor_rgb * (spatial_w * range_w)`.
5. **Normalize**: Divide by probability sum.

Expand Down
Loading