Spaces:
Runtime error
Runtime error
app
Browse files19 unmodified lines2021222324252627100 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531321331541551561571581591601611391621631411421431441451461471481491501511521531541641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032041582052062072 unmodified lines21021121216716821316921421521621721821922022122222319 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import showfrom rasterio.shutil import copy as rio_copyfrom rasterio.enums import ColorInterpfrom PIL import Image
from detectree2.preprocessing.tiling import tile_data100 unmodified lines raise RuntimeError(f"Could not read any of the requested bands {bands} (count={src.count}).") return np.stack(arrays, axis=0)
def _pick_rgb_bands(src) -> list: """ Returns 1-based indices for R,G,B. Prefers explicit RGB colorinterp; else drops alpha; else [1,2,3]. """ count = src.count ci = list(src.colorinterp) if src.colorinterp else [] if ci: try: r = ci.index(ColorInterp.red) + 1 g = ci.index(ColorInterp.green) + 1 b = ci.index(ColorInterp.blue) + 1 return [r, g, b] except ValueError: pass non_alpha = [i + 1 for i, c in enumerate(ci) if c != ColorInterp.alpha] if len(non_alpha) >= 3: return non_alpha[:3] return [i for i in range(1, min(3, count) + 1)]
def ensure_three_band_rgb_uint8(in_path: str, work_dir: Path, debug: dict) -> str: """ Build a clean 3×uint8 RGB GeoTIFF from a 3- or 4-band input. IMPORTANT: we write with a MINIMAL profile (no photometric/colorinterp tweaks) to avoid GDAL's 'list index out of range' edge-cases. Fast path: if source is uint8, use GDAL copy to select bands (rock-solid). Fallback: manual read + robust uint8 scaling. """ out_path = str(work_dir / "rgb_uint8_input.tif") with rasterio.open(in_path) as src: if src.count < 3: raise RuntimeError(f"Input has {src.count} band(s). Need at least 3.")
cand = _pick_rgb_bands(src) cand = _pick_rgb_bands(src) # 1-based debug["cand_bands_initial"] = cand data = _safe_read_bands(src, cand) if data.shape[0] < 3: remaining = [b for b in range(1, src.count + 1) if b not in cand] if remaining: extra = _safe_read_bands(src, remaining) need = 3 - data.shape[0] take = min(need, extra.shape[0]) data = np.concatenate([data, extra[:take]], axis=0) if data.shape[0] < 3: H, W = data.shape[-2], data.shape[-1] pad = np.zeros((3 - data.shape[0], H, W), dtype=data.dtype) data = np.concatenate([data, pad], axis=0) data = data[:3, :, :] debug["bands_used"] = data.shape[0]
# ---- Fast path: use GDAL copy when possible (avoids writer quirks) ---- if src.dtypes[0] == "uint8": # Only copy the 3 RGB bands directly from the dataset rio_copy( src, out_path, driver="GTiff", indexes=tuple(cand[:3]), BIGTIFF="IF_SAFER", compress="DEFLATE", tiled=False, # keep simple interleave="pixel" ) debug["bands_used"] = 3 return out_path
# ---- Fallback path (non-uint8 inputs): manual read + robust scaling ---- # Read bands one-by-one to avoid brittle bulk reads arrays = [] for b in cand[:3]: arrays.append(src.read(b)) data = np.stack(arrays, axis=0) # (3, H, W)
# Robust 2–98% scaling to uint8 if needed if data.dtype != np.uint8: def _robust_uint8(band_arr: np.ndarray) -> np.ndarray: arr = band_arr if arr.size > 50_000_000: arr = arr[::10, ::10] finite = np.isfinite(arr) if not finite.any(): return np.zeros_like(band_arr, dtype=np.uint8) lo, hi = np.percentile(arr[finite], [2, 98]) if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo: lo, hi = float(arr.min()), float(arr.max()) if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo: return np.zeros_like(band_arr, dtype=np.uint8) scaled = (band_arr.astype(np.float32) - lo) * (255.0 / (hi - lo)) return np.clip(scaled, 0, 255).astype(np.uint8) data = np.stack([_robust_uint8(data[i]) for i in range(3)], axis=0)
# Minimal, clean profile (avoid copying quirky keys) profile = { "driver": "GTiff", "height": src.height,2 unmodified lines "dtype": "uint8", "crs": src.crs, "transform": src.transform, "tiled": False, # keep simple "interleave": "pixel", # common default "interleave": "pixel", # no 'photometric', no 'nodata', no colorinterp writes } with rasterio.open(out_path, "w", **profile) as dst: dst.write(data) debug["bands_used"] = 3 return out_path
def strip_alpha_pngs(tiles_dir: Path): for p in tiles_dir.glob("*.png"): try:app.py+67-21