|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Bilateral filtering on a 2D image — denoising the NASA `astronaut` test image. |
| 5 | +
|
| 6 | +Demonstrates the three bilateral families shipped in `warpconvnet.nn`: |
| 7 | +
|
| 8 | + - BilateralFilter (KNN / radius) |
| 9 | + - BilateralFilterGrid (sparse d-cube lattice) |
| 10 | + - BilateralPermutohedralFilter (permutohedral lattice) |
| 11 | +
|
| 12 | +We treat each pixel as a point with 2D position (x, y) and 3D color (r, g, b). |
| 13 | +The bilateral guide is concat(xy/sigma_xy, rgb/sigma_rgb); the value being |
| 14 | +filtered is the noisy color. The astronaut image is in the public domain |
| 15 | +(NASA), shipped with scikit-image. |
| 16 | +
|
| 17 | +Saves five PNGs to <out-dir>: |
| 18 | + astronaut_original.png, astronaut_noisy.png, astronaut_knn.png, |
| 19 | + astronaut_grid.png, astronaut_permutohedral.png |
| 20 | +
|
| 21 | +Run: |
| 22 | + python examples/bilateral_image_example.py --out-dir docs/user_guide/img |
| 23 | +""" |
| 24 | + |
| 25 | +import argparse |
| 26 | +import time |
| 27 | + |
| 28 | +import numpy as np |
| 29 | +import torch |
| 30 | +from skimage import data, util |
| 31 | + |
| 32 | + |
| 33 | +def _to_pixel_pointcloud(img: np.ndarray, device: torch.device): |
| 34 | + """Flatten an (H, W, 3) image into (N, 2) xy + (N, 3) rgb tensors.""" |
| 35 | + h, w, _ = img.shape |
| 36 | + ys, xs = np.meshgrid(np.arange(h), np.arange(w), indexing="ij") |
| 37 | + xy = np.stack([xs, ys], axis=-1).reshape(-1, 2).astype(np.float32) |
| 38 | + rgb = img.reshape(-1, 3).astype(np.float32) |
| 39 | + return ( |
| 40 | + torch.from_numpy(xy).to(device), |
| 41 | + torch.from_numpy(rgb).to(device), |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +def _from_pixel_pointcloud(values: torch.Tensor, h: int, w: int) -> np.ndarray: |
| 46 | + return values.detach().cpu().numpy().reshape(h, w, 3).clip(0, 1) |
| 47 | + |
| 48 | + |
| 49 | +def _save_image(path: str, arr: np.ndarray) -> None: |
| 50 | + from PIL import Image |
| 51 | + |
| 52 | + arr = (np.clip(arr, 0.0, 1.0) * 255.0).round().astype(np.uint8) |
| 53 | + img = Image.fromarray(arr) |
| 54 | + if path.lower().endswith((".jpg", ".jpeg")): |
| 55 | + img.save(path, quality=92, optimize=True, progressive=True) |
| 56 | + else: |
| 57 | + img.save(path, optimize=True) |
| 58 | + |
| 59 | + |
| 60 | +def main(): |
| 61 | + parser = argparse.ArgumentParser() |
| 62 | + parser.add_argument("--out-dir", default="docs/user_guide/img") |
| 63 | + parser.add_argument("--noise-var", type=float, default=0.01) |
| 64 | + parser.add_argument("--sigma-xy", type=float, default=4.0) |
| 65 | + parser.add_argument("--sigma-rgb", type=float, default=0.1) |
| 66 | + parser.add_argument("--knn-k", type=int, default=24) |
| 67 | + args = parser.parse_args() |
| 68 | + import os |
| 69 | + |
| 70 | + os.makedirs(args.out_dir, exist_ok=True) |
| 71 | + |
| 72 | + if not torch.cuda.is_available(): |
| 73 | + raise SystemExit("CUDA required for bilateral filters") |
| 74 | + device = torch.device("cuda") |
| 75 | + |
| 76 | + import warpconvnet.nn as wn |
| 77 | + |
| 78 | + # ---- input image ------------------------------------------------------- |
| 79 | + img = util.img_as_float(data.astronaut()) # (512, 512, 3) in [0, 1] |
| 80 | + noisy = util.random_noise(img, mode="gaussian", var=args.noise_var) |
| 81 | + h, w, _ = img.shape |
| 82 | + |
| 83 | + xy, rgb_clean = _to_pixel_pointcloud(img, device) |
| 84 | + _, rgb_noisy = _to_pixel_pointcloud(noisy.astype(np.float32), device) |
| 85 | + |
| 86 | + # ---- KNN bilateral ----------------------------------------------------- |
| 87 | + knn_filter = wn.BilateralFilter( |
| 88 | + sigma_xyz=args.sigma_xy, |
| 89 | + sigma_feat=args.sigma_rgb, |
| 90 | + k=args.knn_k, |
| 91 | + mode="knn", |
| 92 | + ) |
| 93 | + torch.cuda.synchronize() |
| 94 | + t0 = time.perf_counter() |
| 95 | + out_knn = knn_filter(xy, rgb_noisy, rgb_noisy) |
| 96 | + torch.cuda.synchronize() |
| 97 | + t_knn = time.perf_counter() - t0 |
| 98 | + |
| 99 | + # ---- sparse d-cube grid ----------------------------------------------- |
| 100 | + grid_filter = wn.BilateralFilterGrid( |
| 101 | + sigma_xyz=args.sigma_xy, |
| 102 | + sigma_feat=args.sigma_rgb, |
| 103 | + ) |
| 104 | + torch.cuda.synchronize() |
| 105 | + t0 = time.perf_counter() |
| 106 | + out_grid = grid_filter(xy, rgb_noisy, rgb_noisy) |
| 107 | + torch.cuda.synchronize() |
| 108 | + t_grid = time.perf_counter() - t0 |
| 109 | + |
| 110 | + # ---- permutohedral lattice -------------------------------------------- |
| 111 | + perm_filter = wn.BilateralPermutohedralFilter( |
| 112 | + sigma_xyz=args.sigma_xy, |
| 113 | + sigma_feat=args.sigma_rgb, |
| 114 | + ) |
| 115 | + torch.cuda.synchronize() |
| 116 | + t0 = time.perf_counter() |
| 117 | + out_perm = perm_filter(xy, rgb_noisy, rgb_noisy) |
| 118 | + torch.cuda.synchronize() |
| 119 | + t_perm = time.perf_counter() - t0 |
| 120 | + |
| 121 | + # ---- save individual PNGs --------------------------------------------- |
| 122 | + knn_img = _from_pixel_pointcloud(out_knn, h, w) |
| 123 | + grid_img = _from_pixel_pointcloud(out_grid, h, w) |
| 124 | + perm_img = _from_pixel_pointcloud(out_perm, h, w) |
| 125 | + outputs = { |
| 126 | + "astronaut_original.jpg": img, |
| 127 | + "astronaut_noisy.jpg": noisy, |
| 128 | + "astronaut_knn.jpg": knn_img, |
| 129 | + "astronaut_grid.jpg": grid_img, |
| 130 | + "astronaut_permutohedral.jpg": perm_img, |
| 131 | + } |
| 132 | + for name, arr in outputs.items(): |
| 133 | + path = os.path.join(args.out_dir, name) |
| 134 | + _save_image(path, arr) |
| 135 | + print(f"Saved {path}") |
| 136 | + |
| 137 | + # ---- PSNR vs original (data_range=1.0 since img is float in [0, 1]) --- |
| 138 | + from skimage.metrics import peak_signal_noise_ratio as psnr |
| 139 | + |
| 140 | + ref = img.astype(np.float32) |
| 141 | + psnr_noisy = psnr(ref, np.clip(noisy, 0, 1).astype(np.float32), data_range=1.0) |
| 142 | + psnr_knn = psnr(ref, np.clip(knn_img, 0, 1).astype(np.float32), data_range=1.0) |
| 143 | + psnr_grid = psnr(ref, np.clip(grid_img, 0, 1).astype(np.float32), data_range=1.0) |
| 144 | + psnr_perm = psnr(ref, np.clip(perm_img, 0, 1).astype(np.float32), data_range=1.0) |
| 145 | + |
| 146 | + print() |
| 147 | + print(f" {'Stage':<22}{'Time':>10} PSNR (dB)") |
| 148 | + print(f" {'-' * 46}") |
| 149 | + print(f" {'Noisy input':<22}{'-':>10} {psnr_noisy:6.2f}") |
| 150 | + print(f" {'KNN (k=' + str(args.knn_k) + ')':<22}{t_knn*1e3:>8.1f} ms {psnr_knn:6.2f}") |
| 151 | + print(f" {'Grid':<22}{t_grid*1e3:>8.1f} ms {psnr_grid:6.2f}") |
| 152 | + print(f" {'Permutohedral':<22}{t_perm*1e3:>8.1f} ms {psnr_perm:6.2f}") |
| 153 | + |
| 154 | + |
| 155 | +if __name__ == "__main__": |
| 156 | + main() |
0 commit comments