"""SynthForest: canopy height + tree crown delineation from overhead RGB. Runs the SynthForest models (frozen DINOv3 ViT-L/16 backbone) released with "SynthForest: A Multi-Task Synthetic Dataset for Real-World Forest Vision" (Novoselova, Song, Yokoya): * Syn-20 โ€” DINOv3 + DPT canopy-height model (`syn20.pth`) * HF+MT โ€” Mask R-CNN crown delineator with height fusion + Mean Teacher (`maskrcnn_syn_hf_mt.pth`), the best model in the paper's Table 5. The inference path replicates the reference implementation in https://github.com/iaroslavanovoselova/SynthForest exactly: border-black valid mask, 0.05m -> 0.20m BOX downscale, center pad to a /16 multiple, ImageNet normalisation, height precompute, 4-channel [RGB, height] detector input, eval resize to 992, and valid-fraction filtering of detections. """ from __future__ import annotations import math import os from collections import OrderedDict, deque from typing import Any import spaces # MUST be imported before torch import gradio as gr import numpy as np import torch import torch.nn.functional as F from huggingface_hub import hf_hub_download from PIL import Image from torch import nn from torchvision.models.detection import MaskRCNN from torchvision.models.detection.anchor_utils import AnchorGenerator from torchvision.models.detection.transform import GeneralizedRCNNTransform from torchvision.ops import MultiScaleRoIAlign # --------------------------------------------------------------------------- # Hyperparameters (from the checkpoint-embedded training configs) # --------------------------------------------------------------------------- DINOV3_REPO = "camenduru/dinov3-vitl16-pretrain-lvd1689m" HEIGHT_CKPT = "syn20.pth" DETECTOR_CKPT = "maskrcnn_syn_hf_mt.pth" IMAGENET_MEAN = (0.485, 0.456, 0.406) IMAGENET_STD = (0.229, 0.224, 0.225) # Syn-20 height model HEIGHT_FEATURE_LAYERS = (5, 11, 17, 23) HEIGHT_FEATURE_DIM = 256 HEIGHT_OUT_CHANNELS = (256, 512, 1024, 1024) # Height -> detector fusion SOURCE_GSD_M = 0.05 TARGET_GSD_M = 0.20 HEIGHT_CLIP_MIN_M = 0.0 HEIGHT_CLIP_MAX_M = 60.0 HEIGHT_MEAN_M = 30.0 HEIGHT_STD_M = 30.0 FUSION_LEVELS = ("p8", "p16") FUSION_INIT_SCALE = 0.1 FUSION_HIDDEN = 64 # Detector BACKBONE_OUT_CHANNELS = 256 NUM_CLASSES = 1 ANCHOR_SIZES = ((24, 34, 48), (68, 96, 136), (192, 272, 384)) ASPECT_RATIOS = ((0.75, 1.0, 1.25),) * 3 BOX_SCORE_THRESH = 0.05 BOX_NMS_THRESH = 0.5 BOX_DETECTIONS_PER_IMG = 500 EVAL_MIN_SIZE = 992 MAX_SIZE = 992 TRAIN_MIN_SIZES = (512, 608, 704, 800, 896, 992) MASK_PROBABILITY_THRESHOLD = 0.5 PREDICTION_MIN_VALID_FRACTION = 0.6 PATCH_SIZE = 16 EMBED_DIM = 1024 PYRAMID_FEATURE_NAMES = ("p8", "p16", "p32") FROZEN_BACKBONE_PREFIXES = ("backbone.dinov3.", "dinov3.") MAX_PIXELS = 4_000_000 # 4 MP safety cap keeps ZeroGPU calls short # --------------------------------------------------------------------------- # Valid masks (reference: synthforest/training/valid_masks.py) # --------------------------------------------------------------------------- def border_black_valid_mask(image: Image.Image, tolerance: int = 0) -> np.ndarray: array = np.asarray(image.convert("RGB")) black = np.all(array <= int(tolerance), axis=-1) if not bool(black.any()): return np.ones(black.shape, dtype=bool) seed = np.zeros(black.shape, dtype=bool) seed[0, :] = black[0, :] seed[-1, :] = black[-1, :] seed[:, 0] = black[:, 0] seed[:, -1] = black[:, -1] if not bool(seed.any()): return np.ones(black.shape, dtype=bool) try: from scipy.ndimage import binary_propagation invalid = np.asarray(binary_propagation(seed, mask=black), dtype=bool) except ImportError: invalid = _flood_fill(black, seed) return ~invalid def _flood_fill(candidate: np.ndarray, seed: np.ndarray) -> np.ndarray: height, width = candidate.shape connected = seed.copy() pending = deque(zip(*np.nonzero(seed))) while pending: row, col = pending.popleft() for next_row, next_col in ( (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), ): if ( 0 <= next_row < height and 0 <= next_col < width and candidate[next_row, next_col] and not connected[next_row, next_col] ): connected[next_row, next_col] = True pending.append((next_row, next_col)) return connected def fill_invalid_pixels(image: Image.Image, valid_mask: np.ndarray) -> Image.Image: if bool(valid_mask.all()): return image array = np.asarray(image.convert("RGB")).copy() fill = np.asarray( [round(float(value) * 255.0) for value in IMAGENET_MEAN], dtype=np.uint8 ) array[~valid_mask] = fill return Image.fromarray(array) def box_valid_fractions(valid_mask: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor: if boxes.ndim != 2 or boxes.shape[-1] != 4 or boxes.numel() == 0: return boxes.new_zeros((0,)) if boxes.numel() == 0 else boxes.new_ones((boxes.shape[0],)) if valid_mask.ndim == 3 and valid_mask.shape[0] == 1: valid_mask = valid_mask[0] valid_mask = valid_mask.to(device=boxes.device, dtype=torch.bool) if bool(valid_mask.all()): return boxes.new_ones((boxes.shape[0],)) height, width = valid_mask.shape x1 = boxes[:, 0].floor().clamp(0, width).to(torch.int64) y1 = boxes[:, 1].floor().clamp(0, height).to(torch.int64) x2 = boxes[:, 2].ceil().clamp(0, width).to(torch.int64) y2 = boxes[:, 3].ceil().clamp(0, height).to(torch.int64) integral = torch.nn.functional.pad( valid_mask.to(torch.int64).cumsum(0).cumsum(1), (1, 0, 1, 0) ) valid_area = integral[y2, x2] - integral[y1, x2] - integral[y2, x1] + integral[y1, x1] box_area = (x2 - x1) * (y2 - y1) fractions = valid_area.to(boxes.dtype) / box_area.clamp_min(1).to(boxes.dtype) return torch.where(box_area > 0, fractions, torch.zeros_like(fractions)) def filter_detections_by_valid_masks( detections: list[dict[str, Any]], valid_masks: list[torch.Tensor], min_valid_fraction: float, ) -> list[dict[str, Any]]: filtered = [] for detection, valid_mask in zip(detections, valid_masks): boxes = detection.get("boxes") if not torch.is_tensor(boxes): filtered.append(detection) continue fractions = box_valid_fractions(valid_mask, boxes) keep = fractions >= float(min_valid_fraction) filtered.append( { key: ( value[keep] if torch.is_tensor(value) and value.ndim > 0 and value.shape[0] == keep.shape[0] else value ) for key, value in detection.items() } ) return filtered # --------------------------------------------------------------------------- # Height model (reference: synthforest/training/models/height.py) # --------------------------------------------------------------------------- class ResidualConvUnit(nn.Module): def __init__(self, features: int, use_batch_norm: bool) -> None: super().__init__() self.activation = nn.ReLU(inplace=False) self.conv1 = nn.Conv2d(features, features, 3, 1, 1) self.conv2 = nn.Conv2d(features, features, 3, 1, 1) self.norm1 = _norm_layer(features, use_batch_norm) self.norm2 = _norm_layer(features, use_batch_norm) def forward(self, x: torch.Tensor) -> torch.Tensor: out = self.activation(x) out = self.norm1(self.conv1(out)) out = self.activation(out) out = self.norm2(self.conv2(out)) return out + x class FeatureFusionBlock(nn.Module): def __init__(self, features: int, use_batch_norm: bool) -> None: super().__init__() self.residual1 = ResidualConvUnit(features, use_batch_norm) self.residual2 = ResidualConvUnit(features, use_batch_norm) self.out_conv = nn.Conv2d(features, features, 1) def forward( self, x: torch.Tensor, skip: torch.Tensor | None = None, *, size: tuple[int, int] | None = None, ) -> torch.Tensor: if skip is not None: x = x + self.residual1(skip) x = self.residual2(x) if size is None: x = F.interpolate(x, scale_factor=2.0, mode="bilinear", align_corners=False) else: x = F.interpolate(x, size=size, mode="bilinear", align_corners=False) return self.out_conv(x) class DPTHeightDecoder(nn.Module): def __init__( self, *, in_channels: int, features: int, out_channels: tuple[int, ...], use_batch_norm: bool, output_channels: int = 1, ) -> None: super().__init__() self.projects = nn.ModuleList( [nn.Conv2d(in_channels, c, kernel_size=1) for c in out_channels] ) self.resize_layers = nn.ModuleList( [ nn.ConvTranspose2d(out_channels[0], out_channels[0], 4, 4), nn.ConvTranspose2d(out_channels[1], out_channels[1], 2, 2), nn.Identity(), nn.Conv2d(out_channels[3], out_channels[3], 3, 2, 1), ] ) self.layer1_rn = nn.Conv2d(out_channels[0], features, 3, padding=1, bias=False) self.layer2_rn = nn.Conv2d(out_channels[1], features, 3, padding=1, bias=False) self.layer3_rn = nn.Conv2d(out_channels[2], features, 3, padding=1, bias=False) self.layer4_rn = nn.Conv2d(out_channels[3], features, 3, padding=1, bias=False) self.refinenet1 = FeatureFusionBlock(features, use_batch_norm) self.refinenet2 = FeatureFusionBlock(features, use_batch_norm) self.refinenet3 = FeatureFusionBlock(features, use_batch_norm) self.refinenet4 = FeatureFusionBlock(features, use_batch_norm) self.output_conv = nn.Sequential( nn.Conv2d(features, features // 2, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(features // 2, 32, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(32, int(output_channels), 1), ) def forward(self, feature_maps: list[torch.Tensor], output_size) -> torch.Tensor: resized = [ resize(project(feature)) for feature, project, resize in zip(feature_maps, self.projects, self.resize_layers) ] layer1, layer2, layer3, layer4 = resized layer1_rn = self.layer1_rn(layer1) layer2_rn = self.layer2_rn(layer2) layer3_rn = self.layer3_rn(layer3) layer4_rn = self.layer4_rn(layer4) path4 = self.refinenet4(layer4_rn, size=layer3_rn.shape[-2:]) path3 = self.refinenet3(path4, layer3_rn, size=layer2_rn.shape[-2:]) path2 = self.refinenet2(path3, layer2_rn, size=layer1_rn.shape[-2:]) path1 = self.refinenet1(path2, layer1_rn) out = self.output_conv(path1) return F.interpolate(out, size=output_size, mode="bilinear", align_corners=False) class DinoV3DPTHeightModel(nn.Module): """DINOv3 encoder + DPT height decoder (returns meters).""" def __init__(self, dinov3: nn.Module) -> None: super().__init__() self.dinov3 = dinov3 self.patch_size = PATCH_SIZE self.feature_layers = list(HEIGHT_FEATURE_LAYERS) self.decoder = DPTHeightDecoder( in_channels=EMBED_DIM, features=HEIGHT_FEATURE_DIM, out_channels=list(HEIGHT_OUT_CHANNELS), use_batch_norm=False, output_channels=1, ) def forward(self, images: torch.Tensor) -> dict[str, torch.Tensor]: with torch.no_grad(): try: outputs = self.dinov3( pixel_values=images, output_hidden_states=True, return_dict=True, ) except TypeError: outputs = self.dinov3( images, output_hidden_states=True, return_dict=True ) hidden_states = getattr(outputs, "hidden_states", None) if hidden_states is None and isinstance(outputs, dict): hidden_states = outputs.get("hidden_states") if hidden_states is None: raise RuntimeError("DINOv3 did not return hidden_states; cannot decode height.") feature_maps = [] for layer in self.feature_layers: tokens = _tokens_to_feature_map( hidden_states[layer + 1], images, self.patch_size ) feature_maps.append(tokens) output = self.decoder(feature_maps, output_size=tuple(images.shape[-2:])) return {"height": output} def _norm_layer(features: int, use_batch_norm: bool) -> nn.Module: if use_batch_norm: return nn.BatchNorm2d(features) groups = 32 if features % 32 == 0 else 1 return nn.GroupNorm(groups, features) def _tokens_to_feature_map( patch_tokens: torch.Tensor, images: torch.Tensor, patch_size: int, ) -> torch.Tensor: if patch_tokens.ndim == 4: return patch_tokens batch_size, num_tokens, channels = patch_tokens.shape height = images.shape[-2] // patch_size width = images.shape[-1] // patch_size expected_tokens = height * width if expected_tokens <= 0: raise ValueError( f"Input shape {tuple(images.shape[-2:])} is smaller than patch_size={patch_size}." ) if num_tokens > expected_tokens: patch_tokens = patch_tokens[:, num_tokens - expected_tokens :, :] num_tokens = expected_tokens if expected_tokens != num_tokens: side = int(math.sqrt(num_tokens)) if side * side != num_tokens: raise ValueError( f"Cannot reshape {num_tokens} DINOv3 tokens into a feature map." ) height = width = side return patch_tokens.transpose(1, 2).reshape(batch_size, channels, height, width).contiguous() # --------------------------------------------------------------------------- # Detector (reference: synthforest/training/models/detector.py) # --------------------------------------------------------------------------- def _conv_norm_relu( in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, ) -> nn.Sequential: padding = kernel_size // 2 groups = 32 if out_channels % 32 == 0 else 1 return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.GroupNorm(groups, out_channels), nn.ReLU(inplace=True), ) def _resize_height_for_feature(height: torch.Tensor, size) -> torch.Tensor: if tuple(height.shape[-2:]) == tuple(size): return height in_h, in_w = int(height.shape[-2]), int(height.shape[-1]) out_h, out_w = int(size[0]), int(size[1]) if out_h <= in_h and out_w <= in_w: return F.interpolate(height, size=size, mode="area") return F.interpolate(height, size=size, mode="bilinear", align_corners=False) class HeightPyramidFusion(nn.Module): def __init__(self) -> None: super().__init__() self.levels = FUSION_LEVELS self.encoder = nn.Sequential( _conv_norm_relu(1, FUSION_HIDDEN, 3), _conv_norm_relu(FUSION_HIDDEN, BACKBONE_OUT_CHANNELS, 3), ) self.level_scales = nn.ParameterDict( { level: nn.Parameter(torch.tensor(float(FUSION_INIT_SCALE))) for level in self.levels } ) def forward( self, features: "OrderedDict[str, torch.Tensor]", height: torch.Tensor ) -> "OrderedDict[str, torch.Tensor]": fused = OrderedDict(features) for level in self.levels: target = fused[level] resized = _resize_height_for_feature(height, target.shape[-2:]) encoded = self.encoder(resized) fused[level] = target + self.level_scales[level].to(dtype=target.dtype) * encoded return fused class DinoV3FeatureBackbone(nn.Module): def __init__(self, dinov3: nn.Module) -> None: super().__init__() self.dinov3 = dinov3 self.patch_size = PATCH_SIZE self.input_projection = _conv_norm_relu(EMBED_DIM, BACKBONE_OUT_CHANNELS, 1) self.p8_smooth = _conv_norm_relu(BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3) self.p16_smooth = _conv_norm_relu(BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3) self.p32_downsample = _conv_norm_relu( BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3, stride=2 ) self.height_fusion = HeightPyramidFusion() self.out_channels = BACKBONE_OUT_CHANNELS def forward(self, images: torch.Tensor) -> "OrderedDict[str, torch.Tensor]": height = images[:, 3:4] images = images[:, :3] with torch.no_grad(): try: raw = self.dinov3(pixel_values=images, return_dict=True) except TypeError: raw = self.dinov3(images) if isinstance(raw, dict): last_hidden = raw.get("last_hidden_state") else: last_hidden = getattr(raw, "last_hidden_state", None) if last_hidden is None: raise RuntimeError("DINOv3 did not return last_hidden_state.") feature_map = _tokens_to_feature_map(last_hidden, images, self.patch_size) base = self.input_projection(feature_map) p8 = self.p8_smooth( F.interpolate(base, scale_factor=2.0, mode="bilinear", align_corners=False) ) p16 = self.p16_smooth(base) p32 = self.p32_downsample(base) features = OrderedDict([("p8", p8), ("p16", p16), ("p32", p32)]) return self.height_fusion(features, height) class TrainEvalResizeTransform(GeneralizedRCNNTransform): """Normalise [RGB, height-m] and resize to the fixed eval size (992).""" def __init__(self) -> None: image_mean = list(IMAGENET_MEAN) + [HEIGHT_MEAN_M] image_std = list(IMAGENET_STD) + [HEIGHT_STD_M] super().__init__( min_size=TRAIN_MIN_SIZES, max_size=MAX_SIZE, image_mean=image_mean, image_std=image_std, ) self.train_min_sizes = TRAIN_MIN_SIZES self.eval_min_size = EVAL_MIN_SIZE def normalize(self, image): dtype = image.dtype device = image.device rgb_mean = torch.as_tensor(self.image_mean[:3], dtype=dtype, device=device) rgb_std = torch.as_tensor(self.image_std[:3], dtype=dtype, device=device) rgb = (image[:3] - rgb_mean[:, None, None]) / rgb_std[:, None, None] height = image[3:4].clamp(HEIGHT_CLIP_MIN_M, HEIGHT_CLIP_MAX_M) height = (height - HEIGHT_MEAN_M) / max(HEIGHT_STD_M, 1e-6) return torch.cat([rgb, height], dim=0) def resize(self, image, target): original_min_size = self.min_size self.min_size = self.train_min_sizes if self.training else (self.eval_min_size,) try: return super().resize(image, target) finally: self.min_size = original_min_size def _build_detector(dinov3: nn.Module) -> MaskRCNN: backbone = DinoV3FeatureBackbone(dinov3) anchor_generator = AnchorGenerator(sizes=ANCHOR_SIZES, aspect_ratios=ASPECT_RATIOS) box_roi_pool = MultiScaleRoIAlign( featmap_names=list(PYRAMID_FEATURE_NAMES), output_size=7, sampling_ratio=2 ) mask_roi_pool = MultiScaleRoIAlign( featmap_names=list(PYRAMID_FEATURE_NAMES), output_size=14, sampling_ratio=2 ) model = MaskRCNN( backbone, num_classes=NUM_CLASSES + 1, rpn_anchor_generator=anchor_generator, box_roi_pool=box_roi_pool, mask_roi_pool=mask_roi_pool, min_size=TRAIN_MIN_SIZES, max_size=MAX_SIZE, image_mean=list(IMAGENET_MEAN), image_std=list(IMAGENET_STD), box_score_thresh=BOX_SCORE_THRESH, box_nms_thresh=BOX_NMS_THRESH, box_detections_per_img=BOX_DETECTIONS_PER_IMG, ) model.transform = TrainEvalResizeTransform() return model # --------------------------------------------------------------------------- # Checkpoint loading # --------------------------------------------------------------------------- def load_trained_state_dict(model: nn.Module, state_dict: dict) -> None: result = model.load_state_dict(state_dict, strict=False) missing = [ key for key in result.missing_keys if not key.startswith(FROZEN_BACKBONE_PREFIXES) or "lora" in key.lower() ] if missing or result.unexpected_keys: raise RuntimeError( "Checkpoint state does not match the model: " f"missing={missing[:5]}, unexpected={list(result.unexpected_keys)[:5]}" ) def _resolve_state_dict(checkpoint: dict) -> dict: for key in ("model_state_dict", "ema_teacher_state_dict", "student_state_dict"): value = checkpoint.get(key) if isinstance(value, dict) and value: return value raise RuntimeError("Checkpoint does not contain a model state dict.") # --------------------------------------------------------------------------- # Model loading (module scope, eager, on cuda) # --------------------------------------------------------------------------- print("Loading DINOv3 ViT-L/16 backbone from", DINOV3_REPO, flush=True) from transformers import AutoModel _dinov3 = AutoModel.from_pretrained(DINOV3_REPO, trust_remote_code=True) _dinov3.eval() for _p in _dinov3.parameters(): _p.requires_grad = False print("Loading Syn-20 height model", flush=True) _height_model = DinoV3DPTHeightModel(_dinov3) _height_ckpt = torch.load( hf_hub_download("novoselova/synthforest", HEIGHT_CKPT), map_location="cpu", weights_only=False ) load_trained_state_dict(_height_model, _resolve_state_dict(_height_ckpt)) del _height_ckpt print("Loading HF+MT crown detector", flush=True) _detector = _build_detector(_dinov3) _detector_ckpt = torch.load( hf_hub_download("novoselova/synthforest", DETECTOR_CKPT), map_location="cpu", weights_only=False, ) load_trained_state_dict(_detector, _resolve_state_dict(_detector_ckpt)) del _detector_ckpt del _dinov3 device = "cuda" if torch.cuda.is_available() else "cpu" _height_model = _height_model.to(device).eval() _detector = _detector.to(device).eval() print(f"Models on {device}", flush=True) # --------------------------------------------------------------------------- # Inference pipeline (reference: benchmarking/inference.py + detector_precompute.py) # --------------------------------------------------------------------------- def _predict_height_map(image: Image.Image, valid_mask: np.ndarray) -> np.ndarray: """Syn-20 height in meters at the input resolution.""" image = fill_invalid_pixels(image.convert("RGB"), valid_mask) original_size = image.size # (W, H) scale = SOURCE_GSD_M / TARGET_GSD_M low_size = ( max(1, int(round(original_size[0] * scale))), max(1, int(round(original_size[1] * scale))), ) low_image = image.resize(low_size, Image.Resampling.BOX) low_mask = np.asarray( Image.fromarray(valid_mask.astype(np.uint8) * 255).resize( low_size, Image.Resampling.BOX ) ) > 0 # Center-pad to a /16 multiple with the ImageNet-mean fill colour. multiple = PATCH_SIZE width, height = low_image.size padded_width = int(math.ceil(width / multiple) * multiple) padded_height = int(math.ceil(height / multiple) * multiple) crop_left = (padded_width - width) // 2 crop_top = (padded_height - height) // 2 if padded_width == width and padded_height == height: padded_image = low_image else: fill = tuple(int(round(float(v) * 255.0)) for v in IMAGENET_MEAN) canvas = Image.new("RGB", (padded_width, padded_height), fill) canvas.paste(low_image, (crop_left, crop_top)) padded_image = canvas array = np.asarray(padded_image.convert("RGB"), dtype=np.float32) / 255.0 padded_mask = np.zeros((padded_height, padded_width), dtype=bool) padded_mask[crop_top : crop_top + low_size[1], crop_left : crop_left + low_size[0]] = low_mask if not bool(padded_mask.all()): array[~padded_mask] = np.asarray(IMAGENET_MEAN, dtype=np.float32) tensor = torch.from_numpy(array).permute(2, 0, 1).contiguous() mean = torch.as_tensor(IMAGENET_MEAN, dtype=tensor.dtype).view(-1, 1, 1) std = torch.as_tensor(IMAGENET_STD, dtype=tensor.dtype).view(-1, 1, 1).clamp_min(1e-6) tensor = (tensor - mean) / std with torch.no_grad(): prediction = _height_model(tensor.unsqueeze(0).to(device))["height"] prediction = prediction.clamp_min(0.0) if prediction.shape[-2:] != tensor.shape[-2:]: prediction = F.interpolate( prediction, size=tensor.shape[-2:], mode="bilinear", align_corners=False ) crop = prediction[ :, :, crop_top : crop_top + low_size[1], crop_left : crop_left + low_size[0] ] upsampled = F.interpolate( crop, size=(original_size[1], original_size[0]), mode="bilinear", align_corners=False, ) height_map = ( upsampled.squeeze(0).squeeze(0).detach().cpu().numpy().astype(np.float32) ) return np.where(valid_mask, height_map, 0.0).astype(np.float32) def _detector_input(image: Image.Image, valid_mask: np.ndarray, height_map: np.ndarray): """[RGB(0-1), height(m)] tensor + valid mask, matching the reference dataset.""" array = np.asarray(image.convert("RGB"), dtype=np.float32, copy=True) / 255.0 if not bool(valid_mask.all()): array[~valid_mask] = np.asarray(IMAGENET_MEAN, dtype=np.float32) rgb = torch.from_numpy(array).permute(2, 0, 1).contiguous() height = torch.from_numpy(np.ascontiguousarray(height_map, dtype=np.float32)).unsqueeze(0) return torch.cat([rgb, height], dim=0) def _colourise_height(height_map: np.ndarray, valid_mask: np.ndarray) -> Image.Image: """Viridis-style colour ramp for the height map.""" mask = valid_mask & (height_map > 0.05) if not mask.any(): blank = np.zeros((height_map.shape[0], height_map.shape[1], 3), dtype=np.uint8) return Image.fromarray(blank) vmin, vmax = float(height_map[mask].min()), float(height_map[mask].max()) if vmax - vmin < 1e-6: vmax = vmin + 1e-6 t = (height_map - vmin) / (vmax - vmin) t[~valid_mask] = 0.0 stops = np.array( [ [68, 1, 84], [72, 40, 120], [62, 132, 146], [49, 104, 142], [56, 189, 40], [127, 255, 0], [253, 231, 37], ], dtype=np.float32, ) n = len(stops) - 1 positions = t.reshape(-1) * n idx = np.clip(np.floor(positions).astype(np.int64), 0, n - 1) frac = positions - idx colours = stops[idx] * (1.0 - frac[:, None]) + stops[idx + 1] * frac[:, None] rgb = colours.reshape(height_map.shape[0], height_map.shape[1], 3) rgb[~valid_mask] = np.array([0, 0, 0], dtype=np.float32) return Image.fromarray(np.clip(rgb, 0, 255).astype(np.uint8)) def _draw_detections( image: Image.Image, boxes: list[list[float]], scores: list[float], masks: np.ndarray, valid_mask: np.ndarray, ) -> Image.Image: """Draw crown masks (score-coloured fill) + boxes + score labels on the RGB.""" from PIL import ImageDraw base = np.asarray(image.convert("RGB"), dtype=np.float32) if len(masks): colour_sum = np.zeros(base.shape, dtype=np.float32) count = np.zeros(valid_mask.shape, dtype=np.float32) for score, mask in zip(scores, masks): binary = mask & valid_mask if not binary.any(): continue colour = np.array(_box_colour(score), dtype=np.float32) * 255.0 colour_sum[binary] += colour count[binary] += 1.0 covered = count > 0 if covered.any(): avg = np.zeros_like(colour_sum) avg[covered] = colour_sum[covered] / count[covered, None] base = np.where(covered[..., None], base * 0.55 + avg * 0.45, base) canvas = Image.fromarray(np.clip(base, 0, 255).astype(np.uint8)) draw = ImageDraw.Draw(canvas) for box, score in zip(boxes, scores): x1, y1, x2, y2 = box colour = tuple(int(c * 255) for c in _box_colour(score)) draw.rectangle([x1, y1, x2, y2], outline=colour, width=3) draw.text((x1 + 3, y1 + 3), f"{score:.2f}", fill=colour) return canvas def _box_colour(score: float) -> tuple[float, float, float]: """Score -> colour ramp from yellow (low) to red (high).""" t = max(0.0, min(1.0, float(score))) # yellow -> red return (1.0, 1.0 - t, 0.3 * (1.0 - t)) @spaces.GPU(duration=15) def analyse( image: Image.Image | None, score_threshold: float = 0.5, progress=gr.Progress(track_tqdm=True), ): """Estimate canopy height and delineate tree crowns from an overhead RGB image. Args: image: Overhead (aerial/satellite) RGB image. Best results at the paper's operating point: ~2-10 cm GSD, roughly 992x992 pixels. score_threshold: Minimum detection score to display (the model's own NMS already ran at the training threshold). Returns: (detection overlay, colourised height map, stats text) """ if image is None: raise gr.Error("Please upload an overhead RGB image first.") if image.mode != "RGB": image = image.convert("RGB") width, height = image.size if width * height > MAX_PIXELS: scale = math.sqrt(MAX_PIXELS / (width * height)) image = image.resize( (max(1, int(width * scale)), max(1, int(height * scale))), Image.Resampling.BILINEAR, ) gr.Info( f"Image resized to {image.size[0]}x{image.size[1]} to keep GPU time bounded." ) valid_mask = border_black_valid_mask(image, tolerance=0) height_map = _predict_height_map(image, valid_mask) detector_input = _detector_input(image, valid_mask, height_map).to(device) with torch.no_grad(): outputs = _detector([detector_input]) outputs = filter_detections_by_valid_masks( outputs, [torch.from_numpy(valid_mask)], PREDICTION_MIN_VALID_FRACTION ) output = outputs[0] boxes = output.get("boxes") scores = output.get("scores") masks = output.get("masks") boxes_list = boxes.detach().cpu().float().tolist() if torch.is_tensor(boxes) else [] scores_list = ( [float(v) for v in scores.detach().cpu().float().tolist()] if torch.is_tensor(scores) else [] ) if torch.is_tensor(masks): mask_tensor = masks[:, 0] if masks.ndim == 4 and masks.shape[1] == 1 else masks binary_masks = (mask_tensor.detach().cpu() >= MASK_PROBABILITY_THRESHOLD) & torch.from_numpy( valid_mask ) mask_list = binary_masks.numpy() else: mask_list = np.zeros((0, height, width), dtype=bool) keep = [i for i, s in enumerate(scores_list) if s >= float(score_threshold)] boxes_list = [boxes_list[i] for i in keep] scores_list = [scores_list[i] for i in keep] if len(mask_list): mask_list = mask_list[keep] overlay = _draw_detections(image, boxes_list, scores_list, mask_list, valid_mask) height_vis = _colourise_height(height_map, valid_mask) valid_pixels = int(valid_mask.sum()) if valid_pixels > 0: mean_height = float(height_map[valid_mask].mean()) max_height = float(height_map[valid_mask].max()) else: mean_height = 0.0 max_height = 0.0 canopy = valid_mask & (height_map > 1.0) canopy_pixels = int(canopy.sum()) stats = ( f"**Detections**: {len(boxes_list)} crowns (score โ‰ฅ {score_threshold:.2f})\n\n" f"**Mean canopy height**: {mean_height:.1f} m\n" f"**Max canopy height**: {max_height:.1f} m\n\n" f"**Canopy cover (>1 m)**: {100.0 * canopy_pixels / max(1, valid_pixels):.1f} %\n" f"**Valid pixels**: {100.0 * valid_pixels / valid_mask.size:.1f} % of image\n\n" f"**Input size**: {image.size[0]}ร—{image.size[1]} px" ) return overlay, height_vis, stats # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- _HEADER = """\ # ๐ŸŒฒ SynthForest โ€” canopy height & tree crowns Upload an **overhead RGB image** (aerial/satellite, ~2โ€“10 cm GSD works best). The demo runs the paper's two released models on it: 1. **Syn-20** โ€” DINOv3+DPT canopy-height estimation โ†’ height map (meters) 2. **HF+MT** โ€” Mask R-CNN crown delineation with height fusion + Mean Teacher (best model, Table 5) โ†’ per-tree crown masks and boxes Models and example tiles from the [SynthForest dataset & models](https://huggingface.co/novoselova/synthforest) (CC BY 4.0).""" _FOOTER = """\ --- **Citation** (Novoselova, Song, Yokoya โ€” *SynthForest: A Multi-Task Synthetic Dataset for Real-World Forest Vision*): ```bibtex @misc{novoselova2026synthforest, title = {SynthForest: A Multi-Task Synthetic Dataset for Real-World Forest Vision}, author = {Iaroslava Novoselova and Jian Song and Naoto Yokoya}, year = {2026}, eprint = {2612.03462}, archivePrefix = {arXiv}, primaryClass = {cs.CV} } ``` Code: [github.com/iaroslavanovoselova/SynthForest](https://github.com/iaroslavanovoselova/SynthForest) ยท Paper: [arXiv:2612.03462](https://arxiv.org/abs/2612.03462)""" with gr.Blocks() as demo: gr.Markdown(_HEADER) with gr.Row(): with gr.Column(): image_in = gr.Image( type="pil", label="Overhead RGB image", sources=["upload", "clipboard"], ) score_threshold = gr.Slider( 0.05, 0.95, value=0.5, step=0.05, label="Score threshold" ) run_btn = gr.Button("Analyse", variant="primary") with gr.Column(): overlay_out = gr.Image(type="pil", label="Tree crown detections") height_out = gr.Image(type="pil", label="Canopy height (m)") stats_out = gr.Markdown() run_btn.click( analyse, inputs=[image_in, score_threshold], outputs=[overlay_out, height_out, stats_out], ) gr.Examples( examples=[ ["assets/example_sm.png", 0.5], ["assets/example_hn.png", 0.5], ["assets/example_lcc.png", 0.5], ], inputs=[image_in, score_threshold], fn=analyse, outputs=[overlay_out, height_out, stats_out], cache_examples=True, cache_mode="lazy", label="Example tiles from the SynthForest dataset (CC BY 4.0)", ) gr.Markdown(_FOOTER) demo.launch(mcp_server=True, theme=gr.themes.Citrus())