Spaces:
Runtime error
Runtime error
app
Browse files13 unmodified lines1415161718192035 unmodified lines565758585960616223 unmodified lines868788888990919293939495969798969798991001011021031021031041061051061091071081111121131091101111121131141151161171181191201211221231241251261271281291301311321151331341351181191201361371381391401411421431441221231241451261271281461471481491501511521531541551561571341351361581591601611621631641431441651661671688 unmodified lines1771781791591601801811824 unmodified lines1871881891711901911921931948 unmodified lines2032042051862062071891902082092102111 unmodified line2132142151981992162172182192202212222012232242252264 unmodified lines23123223321223423521523623723821723924024124222122224324424524624722524824925025123023125225325425523425625725825926018 unmodified lines27928028125928228328428526226328628728828929026929129229329429529629727629829930030130230328228330430530630730813 unmodified linesimport gradio as grimport numpy as npimport rasteriofrom rasterio.enums import ColorInterpimport geopandas as gpdimport matplotlibmatplotlib.use("Agg")35 unmodified lines p = Path(WEIGHTS.get(chosen, WEIGHTS["Flexible"])) if p.exists(): return p if progress: progress(0.20, desc="Downloading model weights…") if progress: progress(0.18, desc="Downloading model weights…") last_err = None for url in ZENODO_CANDIDATES: try:23 unmodified lines Choose which 3 bands to use as RGB. Preference order: 1) Explicit Red/Green/Blue color interpretations 2) If there's an Alpha band, drop it and take first three non-alpha 2) Drop Alpha if present; take first three non-alpha 3) Fallback to [1,2,3] Returns 1-based band indices list of length 3. """ ci = list(src.colorinterp) if src.colorinterp else [] # Map color interps to indices if ci: try: r = ci.index(rasterio.enums.ColorInterp.red) + 1 g = ci.index(rasterio.enums.ColorInterp.green) + 1 b = ci.index(rasterio.enums.ColorInterp.blue) + 1 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 # Drop alpha if present non_alpha = [i+1 for i, c in enumerate(ci) if c != rasterio.enums.ColorInterp.alpha] non_alpha = [i + 1 for i, c in enumerate(ci) if c != ColorInterp.alpha] if len(non_alpha) >= 3: return non_alpha[:3] # Fallback return [1, 2, 3]
def ensure_three_band_rgb(in_path: str, work_dir: Path) -> str:def _robust_uint8(band_arr: np.ndarray) -> np.ndarray: """ If the input has 4 bands, write a 3-band RGB copy and return its path. If it already has 3 bands, return original path. Only supports 3 or 4 band inputs per the request. Convert a single band to uint8 using robust 2–98 percentile scaling. Handles 16-bit inputs safely; keeps uint8 as-is. """ if band_arr.dtype == np.uint8: return band_arr # Subsample for speed if huge arr = band_arr if arr.size > 50_000_000: # ~50M px arr = arr[::10, ::10] lo, hi = np.percentile(arr[np.isfinite(arr)], [2, 98]) if hi <= lo: lo, hi = float(arr.min()), float(arr.max()) if 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)
def ensure_three_band_rgb_uint8(in_path: str, work_dir: Path) -> str: """ Accepts 3- or 4-band GeoTIFF. - If 3 bands: ensure uint8 (robust scale if needed) - If 4 bands: pick RGB bands (drop alpha/NIR), ensure uint8 Returns path to a 3-band uint8 GeoTIFF suitable for RGB tiling. """ out_path = str(work_dir / "rgb_input.tif") out_path = str(work_dir / "rgb_uint8_input.tif") with rasterio.open(in_path) as src: if src.count not in (3, 4): raise RuntimeError(f"Input has {src.count} band(s). This app currently supports 3 or 4 band GeoTIFFs.") if src.count == 3: return in_path raise RuntimeError(f"Input has {src.count} band(s). This app supports 3 or 4 bands.")
bands = [1, 2, 3] if src.count == 3 else pick_rgb_bands(src) data = src.read(bands) # shape: (3, H, W)
# Make sure dtype is uint8 if data.dtype != np.uint8: data = np.stack([_robust_uint8(data[i]) for i in range(3)], axis=0)
# count == 4 → select RGB bands and write bands = pick_rgb_bands(src) # 1-based data = src.read(bands) profile = src.profile.copy() profile.update(count=3) # In case the source had nodata/alpha; we just write RGB profile.pop("photometric", None) profile.update(count=3, dtype="uint8", photometric="RGB") profile.pop("nodata", None) with rasterio.open(out_path, "w", **profile) as dst: dst.write(data) # Set color interpretation to RGB explicitly try: dst.colorinterp = (ColorInterp.red, ColorInterp.green, ColorInterp.blue) except Exception: pass return out_path
def strip_alpha_pngs(tiles_dir: Path): """ Ensure all PNG tiles (if any) are RGB (no alpha). Safe no-op if already RGB. """ """Ensure any PNG tiles are RGB (no alpha).""" for p in tiles_dir.glob("*.png"): try: with Image.open(p) as im: if im.mode != "RGB": im.convert("RGB").save(p) except Exception: # best-effort; don't fail the whole pipeline pass pass # best-effort only
def render_overlay(base_tif: str, crowns_gdf: gpd.GeoDataFrame, out_png: str) -> None: with rasterio.open(base_tif) as src:8 unmodified lines# -------------------- main inference --------------------
def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)): import glob
t0 = time.time() tmpdir = Path(tempfile.mkdtemp(prefix="dt2_")) out_png = tmpdir / "overlay.png"4 unmodified lines tiles_path.mkdir(parents=True, exist_ok=True)
try: # Normalize upload to a real file inside our tmpdir # --------------------- Stage 0: ingest upload --------------------- stage = "ingest" if not geom_file: return None, None, "Error: no file provided."
8 unmodified lines else: return None, None, f"Unsupported upload type: {type(geom_file)}"
# Basic raster checks meta = _summarize_raster(str(upload_src)) if not meta["crs"]: return None, None, "Input has no CRS. Reproject to a metric CRS (e.g., UTM) and try again." # Reject geographic CRS (degrees). Prefer projected (metres) like UTM. return None, None, "Input has no CRS. Reproject to a projected CRS (e.g., UTM, metres) and try again." try: is_geographic = bool(getattr(meta["crs"], "is_geographic", False)) except Exception:1 unmodified line if is_geographic: return None, None, f"Input CRS appears geographic ({meta['crs']}). Reproject to a projected CRS (e.g., UTM)."
# Convert 4-band → 3-band RGB if needed (always end up 3-band) rgb_path = ensure_three_band_rgb(str(upload_src), tmpdir) # --------------------- Stage 1: RGB uint8 conversion --------------------- stage = "rgb-conversion" if progress: progress(0.05, desc="Converting to 3-band RGB (uint8)…") rgb_path = ensure_three_band_rgb_uint8(str(upload_src), tmpdir)
# --------------------- Stage 2: tiling --------------------- stage = "tiling" if progress: progress(0.05, desc="Tiling image (RGB)…") if progress: progress(0.15, desc="Tiling image (RGB)…") buffer, tile_w, tile_h = 30, 40, 40 # metres tile_data(rgb_path, str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")
4 unmodified lines if n_tiles == 0: return None, None, "Tiling produced 0 tiles. Check CRS (must be projected/UTM) and tile/buffer sizes."
# Make sure no PNG tile has an alpha channel strip_alpha_pngs(tiles_path)
# Prepare model # --------------------- Stage 3: predictor --------------------- stage = "model" weights_path = ensure_weights(environment, progress=progress) if progress: progress(0.25, desc="Loading model…") if progress: progress(0.28, desc="Loading model…") cfg = setup_cfg(update_model=str(weights_path)) predictor = DefaultPredictor(cfg)
# Predict if progress: progress(0.35, desc="Predicting on tiles…") # --------------------- Stage 4: prediction --------------------- stage = "prediction" if progress: progress(0.38, desc="Predicting on tiles…") predict_on_data(str(tiles_path), predictor=predictor)
# Verify predictions exist preds_dir = tiles_path / "predictions" pred_jsons = list(preds_dir.glob("*.json")) if len(pred_jsons) == 0: return None, None, ( "No predictions were written. " "Ensure the image contains trees, and that RGB content is valid (not blank)." "No predictions were written after inference. " "Ensure the image truly contains trees and RGB content is valid (not blank/overexposed)." )
# Project → stitch → clean # --------------------- Stage 5: project + stitch + clean --------------------- stage = "postprocess" if progress: progress(0.65, desc="Projecting + stitching crowns…") preds_geo_dir = tiles_path / "predictions_geo" project_to_geojson(str(tiles_path), str(preds_dir), str(preds_geo_dir))18 unmodified lines clean.to_file(out_geojson, driver="GeoJSON") saved = out_geojson
# Overlay preview (use the 3-band RGB we tiled from) # --------------------- Stage 6: overlay + zip --------------------- stage = "render" if progress: progress(0.90, desc="Rendering overlay…") render_overlay(rgb_path, clean, str(out_png))
# Zip the vector output with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf: zf.write(saved, arcname=saved.name)
took = time.time() - t0 summary = ( f"Raster: {Path(upload_src).name} | bands_in={meta['bands']} → using RGB | " f"Raster: {Path(upload_src).name} | bands_in={meta['bands']} ({meta['dtype']}) → using RGB uint8 | " f"crs={meta['crs']} | res={meta['res']}\n" f"Tiles: {n_tiles} | Detected crowns: {len(clean)} | Took {took:.1f}s" ) return str(out_png), str(out_zip), summary
except Exception as e: return None, None, f"Error during inference: {e}" return None, None, f"Error during inference ({stage}): {e}"
# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo: gr.Markdown( "# 🌳 Detectree2 Demo\n" "Upload a GeoTIFF (3 or 4 bands). The app will convert to 3-band RGB and run Detectree2.\n\n" "Pipeline: tiling → prediction → project → stitch → clean." "Upload a GeoTIFF (3 or 4 bands). The app converts to 3-band RGB **uint8** and runs Detectree2.\n\n" "Pipeline: RGB conversion → tiling → prediction → project → stitch → clean." ) with gr.Row(): inp = gr.File(app.py+75-53