"""Run the SpaceNet 2 building detector on one image. python inference_example.py --image tile.tif --score 0.544 --overlay out.png Input ----- * SpaceNet-style 16-bit GeoTIFF (PS-RGB): stretched exactly as in training, per band, 2nd-98th percentile of the nonzero pixels, to 8-bit. * 8-bit RGB image (PNG, JPEG, 8-bit GeoTIFF): used as is. Pass --stretch to apply the same percentile stretch, which helps with low-contrast imagery. Output is in pixel coordinates of the input image (origin top-left). """ import argparse import os import numpy as np from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) def percentile_stretch(arr, low=2.0, high=98.0): """(H, W, 3) array of any integer type -> (H, W, 3) uint8, per band.""" out = np.empty(arr.shape[:2] + (3,), np.uint8) for c in range(3): band = arr[..., c] v = band[band > 0] if v.size == 0: lo, hi = 0.0, 1.0 else: lo, hi = float(np.percentile(v, low)), float(np.percentile(v, high)) scaled = (band.astype(np.float32) - lo) * (255.0 / max(hi - lo, 1.0)) out[..., c] = np.clip(scaled, 0, 255).astype(np.uint8) return out def load_tile(path, stretch=False): """Read an image as (H, W, 3) uint8 RGB, the form the model was trained on.""" if path.lower().endswith((".tif", ".tiff")): import rasterio with rasterio.open(path) as src: arr = src.read([1, 2, 3]).transpose(1, 2, 0) else: arr = np.asarray(Image.open(path).convert("RGB")) if arr.dtype != np.uint8 or stretch: arr = percentile_stretch(arr) return np.ascontiguousarray(arr) def build_predictor(config="config.yaml", weights="model_final.pth", device="cuda", score=0.544): from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor cfg = get_cfg() cfg.merge_from_file(os.path.join(HERE, config) if not os.path.isabs(config) else config) cfg.MODEL.WEIGHTS = os.path.join(HERE, weights) if not os.path.isabs(weights) else weights cfg.MODEL.DEVICE = device cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = score return DefaultPredictor(cfg) def predict(predictor, rgb): """rgb: (H, W, 3) uint8 RGB. Returns detectron2 Instances on the CPU.""" return predictor(rgb[:, :, ::-1])["instances"].to("cpu") # model expects BGR def save_overlay(rgb, inst, path): import cv2 img = rgb.copy() for m in inst.pred_masks.numpy().astype(np.uint8): contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img, contours, -1, (255, 220, 0), 2) Image.fromarray(img).save(path) def main(): p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) p.add_argument("--image", required=True) p.add_argument("--score", type=float, default=0.544, help="score threshold; 0.544 is the operating point used for the reported F1") p.add_argument("--device", default="cuda", choices=["cuda", "cpu"]) p.add_argument("--stretch", action="store_true", help="apply the percentile stretch to 8-bit input as well") p.add_argument("--overlay", help="write a PNG with predicted footprints outlined") a = p.parse_args() rgb = load_tile(a.image, stretch=a.stretch) inst = predict(build_predictor(device=a.device, score=a.score), rgb) print(f"{len(inst)} buildings at score >= {a.score} (pixel coordinates, origin top-left)") print(f"{'score':>6} {'x0':>7} {'y0':>7} {'x1':>7} {'y1':>7} {'area_px':>8}") boxes = inst.pred_boxes.tensor.numpy() areas = inst.pred_masks.numpy().sum(axis=(1, 2)) for s, (x0, y0, x1, y1), ar in sorted(zip(inst.scores.numpy(), boxes, areas), key=lambda t: -t[0]): print(f"{s:6.3f} {x0:7.1f} {y0:7.1f} {x1:7.1f} {y1:7.1f} {int(ar):8d}") if a.overlay: save_overlay(rgb, inst, a.overlay) print(f"overlay written to {a.overlay}") if __name__ == "__main__": main()