Spaces:
Runtime error
Runtime error
4 channel support
Browse files1 unmodified line2345567811 unmodified lines202122232425264 unmodified lines31323333343536371 unmodified line39404141424343444511 unmodified lines5758596160616216 unmodified lines798081848283844 unmodified lines8990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141961421431441451461471481491507 unmodified lines1581591601141611621631641181191651661671681221231241251691701711271721731291301741751761771781791801812 unmodified lines1841851861391871881891421901911921441931941951961481971981992002012021542032041561571582052062072082091602102112121631641651661671681691701711721731741751762132142152162172182192202212222232242252262272282292301792312322332341831842352362372382392402412422431911922442452462471971982482492502512522532542042552562572581 unmodified lineimport os# Be defensive about Spaces' env quirks before any heavy importsos.environ.setdefault("OMP_NUM_THREADS", "1") # avoid libgomp crashos.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") # writable cacheos.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") # writable cacheos.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)
import io11 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import showfrom PIL import Image # used to strip alpha from any png tiles
# detectree2 / detectron2from detectree2.preprocessing.tiling import tile_data4 unmodified lines
# ---------------------------------------------------------------------# Weights: local path + auto-download from Zenodo if missing.# The detectree2 docs & model garden point to '230103_randresize_full.pth'.# The detectree2 model garden points to '230103_randresize_full.pth'.# ---------------------------------------------------------------------WEIGHTS = { "Forest": "weights/230103_randresize_full.pth",1 unmodified line "Flexible": "weights/230103_randresize_full.pth",}ZENODO_CANDIDATES = [ # 2024 record "https://zenodo.org/records/10522461/files/230103_randresize_full.pth?download=1", # 2025 record (duplicate hosting) "https://zenodo.org/records/15014353/files/230103_randresize_full.pth?download=1",]
11 unmodified lines p = Path(WEIGHTS.get(chosen, WEIGHTS["Flexible"])) if p.exists(): return p # try to download if progress: progress(0.20, desc="Downloading model weights…") last_err = None for url in ZENODO_CANDIDATES:16 unmodified lines plt.close(fig)
def _summarize_raster(path): import rasterio with rasterio.open(path) as src: return { "bands": src.count,4 unmodified lines "height": src.height, }
# --- NEW: force any 4+ band input down to 3-band RGB (keep 1-3 bands sane) ---def ensure_three_band_rgb(in_path: str) -> (str, int): """ Returns path to a 3-band RGB GeoTIFF and the original band count. - If input already has 3 bands: returns the original path. - If input has >=4 bands (e.g., RGBA or MS): writes a copy with bands 1,2,3. - If input has 2 bands: duplicates band 2 to make 3. - If input has 1 band: repeats band 1 to make 3. """ with rasterio.open(in_path) as src: orig_bands = src.count if orig_bands == 3: return in_path, orig_bands
profile = src.profile.copy() profile.update(count=3)
rgb_path = os.path.join(os.path.dirname(in_path), "rgb_input.tif")
if orig_bands >= 3: data = src.read([1, 2, 3]) elif orig_bands == 2: b1, b2 = src.read([1, 2]) data = np.stack([b1, b2, b2], axis=0) elif orig_bands == 1: b1 = src.read(1) data = np.stack([b1, b1, b1], axis=0) else: raise RuntimeError(f"Unexpected band count: {orig_bands}")
with rasterio.open(rgb_path, "w", **profile) as dst: dst.write(data)
return rgb_path, orig_bands
def strip_alpha_pngs(tiles_dir: str) -> int: """Ensure all PNG tiles are RGB (no alpha). Returns number of files patched.""" import glob patched = 0 for p in glob.glob(os.path.join(tiles_dir, "*.png")): try: with Image.open(p) as im: if im.mode != "RGB": im.convert("RGB").save(p) patched += 1 except Exception: pass return patched
def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)): import glob, os, io, time, shutil, zipfile, tempfile import glob t_all = time.time() tmpdir = tempfile.mkdtemp(prefix="dt2_") out_png = os.path.join(tmpdir, "overlay.png") out_gpkg = os.path.join(tmpdir, "crowns_out.gpkg") out_geojson = os.path.join(tmpdir, "crowns_out.geojson") out_zip = os.path.join(tmpdir, "crowns_out.zip") tiles_path = os.path.join(tmpdir, "tiles_pred") os.makedirs(tiles_path, exist_ok=True)7 unmodified lines else: raise RuntimeError(f"Unsupported upload type: {type(geom_file)}")
# Basic raster sanity check # Validate georeferencing (need a projected CRS in metres) meta = _summarize_raster(src_path) if not meta["crs"]: raise RuntimeError("Input has no CRS. Reproject to a metric CRS (e.g., UTM) and try again.") if "UTM" not in (meta["crs"] or "").upper() and "EPSG:32" not in (meta["crs"] or "") and "EPSG:33" not in (meta["crs"] or ""): # Heuristic: most UTM EPSG codes start with 32xxx or 33xxx crs_str = (meta["crs"] or "").upper() if "UTM" not in crs_str and "EPSG:32" not in crs_str and "EPSG:33" not in crs_str: raise RuntimeError(f"Input CRS looks non-metric ({meta['crs']}). Reproject to local UTM before running.")
bands = meta["bands"] img_mode = "rgb" if bands <= 3 else "ms" if bands == 1: raise RuntimeError("Input has 1 band. The bundled model expects RGB (3-band) or multispectral (4+).") # 🔴 Force 3-band RGB no matter what was uploaded (handles 4-band/alpha etc.) src_path_rgb, orig_bands = ensure_three_band_rgb(src_path)
progress(0.05, desc=f"Tiling image ({img_mode})…") if progress: progress(0.05, desc=f"Tiling image (forced 3-band RGB)…") buffer, tile_w, tile_h = 30, 40, 40 # meters # dtype_bool=True per docs to avoid blank PNG bug tile_data(src_path, tiles_path, buffer, tile_w, tile_h, dtype_bool=True, mode=img_mode) # RGB mode → PNG tiles tile_data(src_path_rgb, tiles_path, buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")
# Ensure any PNGs are RGB (strip alpha if present) patched = strip_alpha_pngs(tiles_path)
# Verify tiles exist pngs = glob.glob(os.path.join(tiles_path, "*.png"))2 unmodified lines if n_tiles == 0: raise RuntimeError("Tiling produced 0 tiles. Check CRS (must be metric/UTM) and tile/buffer sizes.")
# Choose weights # Load weights weights = WEIGHTS.get(environment, WEIGHTS["Flexible"]) if not os.path.exists(weights): raise RuntimeError(f"Model weights not found: {weights}") # Attempt download if missing ensure_weights(environment, progress=progress)
progress(0.25, desc="Loading model…") if progress: progress(0.25, desc="Loading model…") cfg = setup_cfg(update_model=weights) predictor = DefaultPredictor(cfg)
progress(0.35, desc="Predicting on tiles…") if progress: progress(0.35, desc="Predicting on tiles…") predict_on_data(tiles_path, predictor=predictor)
# Verify predictions exist preds_dir = os.path.join(tiles_path, "predictions") if not os.path.isdir(preds_dir) or not os.listdir(preds_dir): raise RuntimeError("No predictions were written. Try a smaller confidence, check band count/CRS, or use RGB data.") raise RuntimeError("No predictions were written. Check that imagery is RGB-like and contains trees.")
progress(0.65, desc="Projecting + stitching crowns…") project_to_geojson(tiles_path, preds_dir, os.path.join(tiles_path, "predictions_geo")) crowns = stitch_crowns(os.path.join(tiles_path, "predictions_geo"), 1) if progress: progress(0.65, desc="Projecting + stitching crowns…") preds_geo_dir = os.path.join(tiles_path, "predictions_geo") project_to_geojson(tiles_path, preds_dir, preds_geo_dir) crowns = stitch_crowns(preds_geo_dir, 1)
progress(0.8, desc="Cleaning crowns…") if progress: progress(0.80, desc="Cleaning crowns…") clean = clean_crowns(crowns, 0.6, confidence=0) clean = clean[clean["Confidence_score"] > float(confidence)] clean = clean.set_geometry(clean.simplify(0.3)) clean.to_file(out_gpkg, driver="GPKG") total = len(clean)
progress(0.9, desc="Rendering overlay…") with rasterio.open(src_path) as src: fig, ax = plt.subplots(figsize=(10, 10)) show(src, ax=ax) clean.plot(ax=ax, facecolor="none", edgecolor="red", linewidth=1.2) ax = plt.gca() ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False) plt.tight_layout(pad=0) plt.savefig(out_png, dpi=250, bbox_inches="tight", pad_inches=0) plt.close(fig) try: clean = clean.set_geometry(clean.geometry.simplify(0.3, preserve_topology=True)) except Exception: pass
# Save vector output (prefer GPKG; fallback to GeoJSON) saved = None try: clean.to_file(out_gpkg, driver="GPKG") saved = out_gpkg except Exception: clean.to_file(out_geojson, driver="GeoJSON") saved = out_geojson
if progress: progress(0.90, desc="Rendering overlay…") render_overlay(src_path_rgb, clean, out_png)
with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf: zf.write(out_gpkg, arcname="crowns_out.gpkg") zf.write(saved, arcname=os.path.basename(saved))
took = time.time() - t_all summary = ( f"Raster: {os.path.basename(src_path)} | bands={bands} | crs={meta['crs']} | res={meta['res']}\n" f"Tiles: {n_tiles} | Detected crowns: {total} | Took {took:.1f}s" f"Original bands: {orig_bands} → processed as 3-band RGB" f"{' (patched PNG alpha)' if patched else ''}\n" f"CRS: {meta['crs']} | res={meta['res']} | tiles={n_tiles} | crowns={len(clean)} | {took:.1f}s" ) return out_png, out_zip, summary
except Exception as e: return None, None, f"Error during inference: {e}"
# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo: gr.Markdown( "# 🌳 Detectree2 Demo\n" "Upload an orthomosaic (GeoTIFF preferred), pick an environment, and get a crown overlay and GPKG/GeoJSON.\n\n" "Pipeline: tiling → prediction → project → stitch → clean (per detectree2 tutorial)." "Upload an orthomosaic (GeoTIFF), pick an environment, and get a crown overlay + vector output.\n\n" "This app forces inputs to 3-band RGB (drops alpha/extra bands) for compatibility with the bundled model." ) with gr.Row(): inp = gr.File( label="Upload GeoTIFF / Image", file_types=[".tif", ".tiff", ".png", ".jpg", ".jpeg"], type="filepath" # IMPORTANT: gives a string path, not a file-like type="filepath" # gives a string path, not a file-like ) env = gr.Dropdown(choices=["Forest", "Urban", "Flexible"], value="Forest", label="Environment preset") conf = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Min confidence")app.py+99-48