Spaces:
Runtime error
Runtime error
app
Browse files95 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112 unmodified lines21421521621721821922022122222395 unmodified linesscaled = (band_arr.astype(np.float32) - lo) * (255.0 / (hi - lo))return np.clip(scaled, 0, 255).astype(np.uint8)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.countci = list(src.colorinterp) if src.colorinterp else []if ci:try:r = ci.index(ColorInterp.red) + 1g = ci.index(ColorInterp.green) + 1b = ci.index(ColorInterp.blue) + 1return [r, g, b]except ValueError:passnon_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 _safe_read_bands(src, bands: list) -> np.ndarray:arrays = []for b in bands:try:if 1 <= b <= src.count:arrays.append(src.read(b))except (RasterioIOError, IndexError):continueif len(arrays) == 0: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.countci = list(src.colorinterp) if src.colorinterp else []if ci:try:r = ci.index(ColorInterp.red) + 1g = ci.index(ColorInterp.green) + 1b = ci.index(ColorInterp.blue) + 1return [r, g, b]except ValueError:passnon_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.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) # 1-baseddebug["cand_bands_initial"] = cand# ---- Fast path: use GDAL copy when possible (avoids writer quirks) ----if src.dtypes[0] == "uint8":# Only copy the 3 RGB bands directly from the datasetrio_copy(src, out_path,driver="GTiff",indexes=tuple(cand[:3]),BIGTIFF="IF_SAFER",compress="DEFLATE",tiled=False, # keep simpleinterleave="pixel")debug["bands_used"] = 3return out_path# ---- Fallback path (non-uint8 inputs): manual read + robust scaling ----# Read bands one-by-one to avoid brittle bulk readsarrays = []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 neededif data.dtype != np.uint8:def _robust_uint8(band_arr: np.ndarray) -> np.ndarray:arr = band_arrif 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)profile = {"driver": "GTiff","height": src.height,"width": src.width,"count": 3,"dtype": "uint8","crs": src.crs,2 unmodified lines}with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)debug["bands_used"] = 3return out_pathdef strip_alpha_pngs(tiles_dir: Path):for p in tiles_dir.glob("*.png"):try:95 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571582 unmodified lines16116216316416516616716816917017195 unmodified linesscaled = (band_arr.astype(np.float32) - lo) * (255.0 / (hi - lo))return np.clip(scaled, 0, 255).astype(np.uint8)def ensure_three_band_rgb_uint8(in_path: str, work_dir: Path, debug: dict) -> str:"""Create a simple 3×uint8 RGB GeoTIFF that Detectree2 can tile.Strategy:1) Try bands [1,2,3] (works for most RGBA files).2) If that fails, pick first 3 readable non-alpha bands by probing.3) Minimal write (no photometric/nodata/colorinterp), uint8 only."""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.")H, W = src.height, src.width# --- Attempt 1: hard-coded [1,2,3] ---bands_to_use = [1, 2, 3]debug["cand_bands_initial"] = bands_to_usearrays = []try:for b in bands_to_use:arrays.append(src.read(b))except Exception:arrays = [] # fall back# --- Attempt 2: probe for first 3 readable non-alpha bands ---if len(arrays) != 3:arrays = []bands_to_use = []ci = list(src.colorinterp) if src.colorinterp else []# prefer non-alpha; if ci empty, we’ll just try all bandspreferred = [i + 1 for i, c in enumerate(ci) if c != ColorInterp.alpha] or list(range(1, src.count + 1))for b in preferred:try:arr = src.read(b)arrays.append(arr)bands_to_use.append(b)if len(arrays) == 3:breakexcept Exception:continueif len(arrays) != 3:raise RuntimeError(f"Could not read three bands (read {len(arrays)} of {src.count}).")data = np.stack(arrays, axis=0) # (3,H,W)debug["bands_used"] = bands_to_use# Ensure uint8if data.dtype != np.uint8:data = np.stack([_robust_uint8(data[i]) for i in range(3)], axis=0)# Minimal profile (avoid GDAL quirks)profile = {"driver": "GTiff","height": H,"width": W,"count": 3,"dtype": "uint8","crs": src.crs,2 unmodified lines}with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)return out_pathdef strip_alpha_pngs(tiles_dir: Path):for p in tiles_dir.glob("*.png"):try:
app.py+44-96