Spaces:
Running

File size: 2,942 Bytes
d1ffd83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/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())