Spaces:
Running

hyperFVC / workflow /scripts /feather_smooth_uncertainty.py
lauransotomayor's picture
Mirror GitHub Pages presentation build (part 4)
d1ffd83 verified
Raw History Blame Contribute Delete
2.94 kB
#!/usr/bin/env python3
"""Feather-smooth a full uncertainty raster for visualization.
This applies a nodata-aware Gaussian feather over a single raster. It is meant
for visual seam reduction and figure generation, not for replacing raw values in
quantitative analysis.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import rasterio
from scipy.ndimage import gaussian_filter
def read_raster(path: Path) -> tuple[np.ndarray, rasterio.profiles.Profile]:
with rasterio.open(path) as src:
array = src.read(1).astype(np.float32)
profile = src.profile.copy()
nodata = src.nodata
if nodata is not None and np.isfinite(nodata):
array[array == nodata] = np.nan
array[~np.isfinite(array)] = np.nan
return array, profile
def feather_smooth(array: np.ndarray, sigma: float, truncate: float) -> np.ndarray:
valid = np.isfinite(array)
if not np.any(valid):
return np.full_like(array, np.nan, dtype=np.float32)
filled = np.where(valid, array, 0.0).astype(np.float32, copy=False)
weights = valid.astype(np.float32, copy=False)
smoothed_values = gaussian_filter(filled, sigma=sigma, truncate=truncate, mode="nearest")
smoothed_weights = gaussian_filter(weights, sigma=sigma, truncate=truncate, mode="nearest")
out = np.full_like(array, np.nan, dtype=np.float32)
safe = smoothed_weights > 1e-6
out[safe] = smoothed_values[safe] / smoothed_weights[safe]
return out
def write_output(path: Path, array: np.ndarray, profile: rasterio.profiles.Profile) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
profile = profile.copy()
profile.update(count=1, dtype=rasterio.float32, nodata=np.nan, compress="DEFLATE", predictor=3)
for key in ("INTERLEAVE", "interleave", "photometric", "PHOTOMETRIC"):
profile.pop(key, None)
with rasterio.open(path, "w", **profile) as dst:
dst.write(array.astype(np.float32), 1)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Feather-smooth a full uncertainty raster.")
parser.add_argument("--input-raster", required=True, help="Input uncertainty raster.")
parser.add_argument("--output-raster", required=True, help="Output feather-smoothed raster.")
parser.add_argument("--sigma", type=float, default=2.0, help="Gaussian sigma in pixels.")
parser.add_argument("--truncate", type=float, default=4.0, help="Gaussian truncate radius in sigma units.")
return parser
def main() -> int:
args = build_parser().parse_args()
array, profile = read_raster(Path(args.input_raster))
smoothed = feather_smooth(array, sigma=float(args.sigma), truncate=float(args.truncate))
write_output(Path(args.output_raster), smoothed, profile)
print(f"wrote_feathered_raster={args.output_raster}")
return 0
if __name__ == "__main__":
raise SystemExit(main())