import os
import numpy as np
from PIL import Image
from polsartools.utils.utils import conv2d, time_it
from osgeo import gdal
gdal.UseExceptions()
from .pauli_rgb import create_pgw, norm_data, read_bin
def ensure_array(x):
"""Convert a file path, NumPy array, or sequence into a float32 NumPy array."""
if isinstance(x, (str, os.PathLike)):
return np.array(read_bin(x), dtype=np.float32)
elif isinstance(x, np.ndarray):
return x.astype(np.float32)
else:
return np.array(x, dtype=np.float32)
def save_rgba_png(red, green, blue, alpha, out_png):
rgba = np.stack(
(red, green, blue, alpha),
axis=-1
).astype(np.uint8)
Image.fromarray(rgba).save(out_png)
def save_rgba_tif(
red: np.ndarray,
green: np.ndarray,
blue: np.ndarray,
alpha: np.ndarray,
georef_file: str | os.PathLike,
out_tif: str,
) -> None:
"""Save a georeferenced 4-band RGBA GeoTIFF with transparency."""
ref_ds = gdal.Open(str(georef_file), gdal.GA_ReadOnly)
if ref_ds is None:
raise FileNotFoundError(
f"Could not open georeference raster: {georef_file}"
)
rows, cols = red.shape
# Validate dimensions
for name, arr in [
("green", green),
("blue", blue),
("alpha", alpha),
]:
if arr.shape != (rows, cols):
raise ValueError(f"{name} dimensions do not match red channel.")
driver = gdal.GetDriverByName("GTiff")
dst_ds = driver.Create(
out_tif,
cols,
rows,
4,
gdal.GDT_Byte,
options=[
"COMPRESS=LZW",
"TILED=YES",
"PHOTOMETRIC=RGB",
"ALPHA=YES",
],
)
if dst_ds is None:
ref_ds = None
raise RuntimeError(f"Failed to create output GeoTIFF: {out_tif}")
# Copy georeferencing information
dst_ds.SetGeoTransform(ref_ds.GetGeoTransform())
proj = ref_ds.GetProjection()
if proj:
dst_ds.SetProjection(proj)
# Define RGBA bands
bands_data = [
(red, gdal.GCI_RedBand),
(green, gdal.GCI_GreenBand),
(blue, gdal.GCI_BlueBand),
(alpha, gdal.GCI_AlphaBand),
]
for band_idx, (arr, interp) in enumerate(bands_data, start=1):
band = dst_ds.GetRasterBand(band_idx)
# Set band interpretation
band.SetColorInterpretation(interp)
# Write pixel values
band.WriteArray(
np.clip(arr, 0, 255).astype(np.uint8)
)
band.FlushCache()
# Flush and close datasets
dst_ds.FlushCache()
dst_ds = None
ref_ds = None
print(f"RGBA GeoTIFF saved: {out_tif}")
[docs]
@time_it
def rgb(Rpath,Gpath,Bpath,
norm_each=True,lp=5,gp=95,
norm_span = False,
save_tif=False,
window_size=None,
nodata=None):
"""Generate false-color RGB visualization from three input raster files.
Examples
--------
>>> # Generate Pauli RGB from a polarimetric folder
>>> rgb("/path/to/red.tif", "/path/to/green.tif", "/path/to/blue.tif")
>>> # Output both PNG and GeoTIFF versions
>>> rgb("/path/to/red.tif", "/path/to/green.tif", "/path/to/blue.tif", tif_flag=True)
Parameters
----------
Rpath : str
Path to the red channel raster file.
Gpath : str
Path to the green channel raster file.
Bpath : str
Path to the blue channel raster file.
norm_each : bool, default=True
If True, normalize each channel separately.
lp : int, default=5
Lower percentile for normalization (0-100). Only used if `norm_each=True`.
gp : int, default=95
Upper percentile for normalization(0-100). Only used if `norm_each=True`.
norm_span : bool, default=False
If True, normalize each channel with total power.
save_tif : bool, default=False
If True, generates a GeoTIFF (.tif) file alongside the PNG image.
window_size : int, optional
Size of the moving average window for smoothing. If None, no smoothing is applied.
Returns
-------
None
Writes output to:
- RGB.png: RGB composite with world file for georeferencing
- RGB.tif: Optional GeoTIFF output if `tif_flag=True`
"""
# R = read_bin(Rpath)
# G = read_bin(Gpath)
# B = read_bin(Bpath)
R = ensure_array(Rpath)
G = ensure_array(Gpath)
B = ensure_array(Bpath)
if nodata is None:
# Automatically detect zero, NaN and infinite values
R_invalid = ~np.isfinite(R) | (R == 0)
G_invalid = ~np.isfinite(G) | (G == 0)
B_invalid = ~np.isfinite(B) | (B == 0)
else:
# Explicitly specified NoData value
R_invalid = ~np.isfinite(R) | (R == nodata)
G_invalid = ~np.isfinite(G) | (G == nodata)
B_invalid = ~np.isfinite(B) | (B == nodata)
nodata_mask = R_invalid & G_invalid & B_invalid
alpha = np.where(nodata_mask, 0, 255).astype(np.uint8)
if window_size is not None:
kernel = np.ones((window_size, window_size), np.float32) / (
window_size * window_size
)
R = conv2d(R, kernel).astype(np.float32)
G = conv2d(G, kernel).astype(np.float32)
B = conv2d(B, kernel).astype(np.float32)
if norm_each:
R = norm_data(R, lp, gp, dB_scale=True)
G = norm_data(G, lp, gp, dB_scale=True)
B = norm_data(B, lp, gp, dB_scale=True)
if norm_span:
total = R + G + B
valid_div = (total != 0) & (~np.isnan(total))
red_f = np.divide(
R * 255.0,
total,
out=np.zeros_like(R, dtype=np.float32),
where=valid_div,
)
green_f = np.divide(
G * 255.0,
total,
out=np.zeros_like(G, dtype=np.float32),
where=valid_div,
)
blue_f = np.divide(
B * 255.0,
total,
out=np.zeros_like(B, dtype=np.float32),
where=valid_div,
)
red = np.clip(red_f, 0, 255).astype(np.uint8)
green = np.clip(green_f, 0, 255).astype(np.uint8)
blue = np.clip(blue_f, 0, 255).astype(np.uint8)
del R, G, B, total, red_f, green_f, blue_f
else:
red = np.clip(np.nan_to_num(R, nan=0.0), 0, 255).astype(np.uint8)
green = np.clip(np.nan_to_num(G, nan=0.0), 0, 255).astype(np.uint8)
blue = np.clip(np.nan_to_num(B, nan=0.0), 0, 255).astype(np.uint8)
# Zero out RGB values on transparent pixels so they don't show faint fringes
red[nodata_mask] = 0
green[nodata_mask] = 0
blue[nodata_mask] = 0
if isinstance(Rpath, (str, os.PathLike)):
georef_file = Rpath
infolder = os.path.dirname(georef_file)
output_path = os.path.join(infolder, "RGB.png")
save_rgba_png(red, green, blue, alpha, output_path)
create_pgw(georef_file, output_path)
print(f"RGB image saved as {output_path}")
if save_tif:
tif_path = os.path.join(infolder, "RGB.tif")
save_rgba_tif(red, green, blue, alpha, georef_file, tif_path)
print(f"RGB GeoTIFF saved as {tif_path}")
elif isinstance(Rpath, np.ndarray):
output_path = os.path.join("./", "RGB.png")
save_rgba_png(red, green, blue, alpha, output_path)
print(f"RGB image saved as {output_path}")
else:
raise ValueError("Invalid input!!")