Spaces:
Runtime error
Runtime error
revert
Browse files19 unmodified lines202122232425262728293022 unmodified lines535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512611 unmodified lines13813914014114214314414514634 unmodified lines18118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928019 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grimport mathimport numpy as npfrom shapely.geometry import boximport pyprojfrom detectron2.engine import DefaultPredictorfrom detectree2.preprocessing.tiling import tile_data22 unmodified linesexcept Exception:passdef pad_for_tiling(src_path, buffer_m, tile_w_m, tile_h_m):"""Create a padded copy of src_path so that:- We add 'buffer_m' on all sides (in pixels).- The final width/height are exact multiples of the tile size (in pixels).Returns (out_path, original_bounds)"""out_path = src_path.replace(".tif", "_padded.tif").replace(".tiff", "_padded.tiff")with rasterio.open(src_path) as src:if src.crs is None:raise ValueError("Input has no CRS; cannot compute meter-to-pixel sizes reliably.")# Pixel sizes (assumes no rotation/skew)res_x = abs(src.transform.a)res_y = abs(src.transform.e)# Convert meters to pixelsbuf_px_x = int(math.ceil(buffer_m / res_x))buf_px_y = int(math.ceil(buffer_m / res_y))tile_px_w = int(math.ceil(tile_w_m / res_x))tile_px_h = int(math.ceil(tile_h_m / res_y))w, h = src.width, src.height# We will add buffer on all sides, then extend right/bottom to multiples of tile sizebase_w = w + 2 * buf_px_xbase_h = h + 2 * buf_px_ytarget_w = int(math.ceil(base_w / tile_px_w) * tile_px_w)target_h = int(math.ceil(base_h / tile_px_h) * tile_px_h)pad_right = target_w - base_wpad_bottom = target_h - base_hnew_w = base_w + pad_rightnew_h = base_h + pad_bottomprofile = src.profile.copy()# Choose/ensure a nodata valuenodata = profile.get("nodata", None)if nodata is None:nodata = 0profile["nodata"] = nodataprofile.update(width=new_w,height=new_h,# shift origin up/left by the buffer so original data lands insettransform=Affine(src.transform.a, src.transform.b, src.transform.c - buf_px_x * res_x,src.transform.d, src.transform.e, src.transform.f + buf_px_y * res_y))# Allocate padded raster and paste original into the centerdata = np.full((src.count, new_h, new_w), nodata, dtype=src.dtypes[0])data[:, buf_px_y:buf_px_y + h, buf_px_x:buf_px_x + w] = src.read()with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)# Save original bounds to clip lateroriginal_bounds = src.boundsreturn out_path, original_bounds# Tiling defaultsBUFFER, TILE_W, TILE_H = 30, 40, 4011 unmodified lineswith rasterio.open(infile) as src:if src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."padded_file, orig_bounds = pad_for_tiling(infile, BUFFER, TILE_W, TILE_H)tile_data(padded_file, tiles_dir, BUFFER, TILE_W, TILE_H)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)34 unmodified lines# stitch + clean + filtercrowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0)cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)]with rasterio.open(infile) as _src:raster_crs = _src.crsraster_bounds = _src.boundsif cleaned.crs is None:cleaned = cleaned.set_crs("EPSG:4326", allow_override=True)if not cleaned.empty:cleaned = cleaned[cleaned.geometry.notna()]bad = ~cleaned.geometry.is_validif bad.any():cleaned.loc[bad, "geometry"] = cleaned.loc[bad, "geometry"].buffer(0)if cleaned.crs != raster_crs:cleaned = cleaned.to_crs(raster_crs)if not cleaned.empty:cleaned = cleaned.clip(box(*orig_bounds))crowns_boundary = Noneif not cleaned.empty:try:crowns_boundary = cleaned.copy()crowns_boundary.set_geometry(crowns_boundary.boundary, inplace=True)except Exception:crowns_boundary = None# save vectorgpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path, driver="GPKG")# save overlay# save overlay ON ORIGINAL RASTER (what the UI shows)overlay_path = os.path.join(workdir, "crowns_out.png")with rasterio.open(infile) as src:fig, ax = plt.subplots(figsize=(10, 10))show(src, ax=ax, zorder=1)ax.set_aspect('equal')rb = src.boundsax.set_xlim(rb.left, rb.right)ax.set_ylim(rb.bottom, rb.top)if not cleaned.empty:# draw filled polygons faintly, then crisp boundaries on topcleaned.plot(ax=ax,facecolor="none",edgecolor="lime",linewidth=2.0,zorder=50,alpha=1.0)if crowns_boundary is not None:crowns_boundary.plot(ax=ax, color="cyan", linewidth=1.2, zorder=21)ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False)plt.savefig(overlay_path, dpi=220, bbox_inches="tight", pad_inches=0)plt.close(fig)# EXTRA: save a DEBUG image of crowns ALONE (no raster), same extent/CRSdebug_path = os.path.join(workdir, "crowns_debug.png")fig, ax = plt.subplots(figsize=(8, 8))ax.set_aspect('equal')ax.set_xlim(rb.left, rb.right)ax.set_ylim(rb.bottom, rb.top)if not cleaned.empty:cleaned.plot(ax=ax, facecolor="none", edgecolor="magenta", linewidth=1.5)if crowns_boundary is not None:crowns_boundary.plot(ax=ax, color="magenta", linewidth=1.0)ax.set_title("Crowns (reprojected) over raster extent")ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(True)plt.savefig(debug_path, dpi=200, bbox_inches="tight", pad_inches=0)plt.close(fig)total = int(len(cleaned))log = []log.append(f"Raster CRS: {raster_crs}")log.append(f"Crowns CRS after set/reproj: {cleaned.crs}")log.append(f"Raster bounds: {raster_bounds}")try:tb = cleaned.total_boundslog.append(f"Crowns bounds (after reproj+clip): {tb}")except Exception as _:log.append("Crown bounds unavailable.")log.append(f"Total crowns after filter+clip: {total}")log.append(f"Debug crowns-only image: {debug_path}")out_err = "\n".join(map(str, log))stats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, out_errexcept Exception as e:return None, None, None, f"Error: {e}"19 unmodified lines20212223242522 unmodified lines48495051525311 unmodified lines656667686970717234 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213319 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grfrom detectron2.engine import DefaultPredictorfrom detectree2.preprocessing.tiling import tile_data22 unmodified linesexcept Exception:pass# Tiling defaultsBUFFER, TILE_W, TILE_H = 30, 40, 4011 unmodified lineswith rasterio.open(infile) as src:if src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."tile_data(infile, tiles_dir, BUFFER, TILE_W, TILE_H)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)34 unmodified lines# stitch + clean + filtercrowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0)cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)].set_geometry(cleaned.simplify(0.4))# save vectorgpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path, driver="GPKG")# save overlayoverlay_path = os.path.join(workdir, "crowns_out.png")with rasterio.open(infile) as src:fig, ax = plt.subplots(figsize=(10, 10))show(src, ax=ax)if not cleaned.empty:cleaned.plot(ax=ax, facecolor="none", edgecolor="cyan", linewidth=1.2)ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False)plt.savefig(overlay_path, dpi=220, bbox_inches="tight", pad_inches=0)plt.close(fig)stats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, ""except Exception as e:return None, None, None, f"Error: {e}"
app.py+8-155