Spaces:
Running on Zero
Running on Zero
File size: 8,970 Bytes
eafeb70 ebe119f eafeb70 ebe119f eafeb70 ebe119f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | """DANIEL student depth — attention-free monocular depth for onboard robot navigation.
Runs the float PyTorch student (v5, 24.5M params, ResNet-34 U-Net, distilled from
Depth Anything V2-Large) from itaimizlish/daniel-student-depth on a single image.
Input: RGB image. Output: relative inverse-depth (disparity) map, near = bright,
rendered with the authors' INFERNO percentile-stretch convention.
"""
import spaces # must be imported before any torch/CUDA-touching import
import time
from pathlib import Path
import cv2
import gradio as gr
import numpy as np
import torch
import torch.nn as nn
import torchvision
from huggingface_hub import hf_hub_download
# ---------------------------------------------------------------- model ----
# Architecture replicated 1:1 from the authors' onboard/student_depth.py
# (DANIEL repo, MIT license). Input 288x512 RGB in [0, 1]; output relative
# disparity (near = high) at 288x512.
def build_student() -> nn.Module:
"""Build the 24.5M-param attention-free depth student (ResNet-34 U-Net)."""
def block(i: int, o: int) -> nn.Module:
return nn.Sequential(
nn.Conv2d(i, o, 3, padding=1, bias=False),
nn.BatchNorm2d(o),
nn.ReLU(inplace=True),
nn.Conv2d(o, o, 3, padding=1, bias=False),
nn.BatchNorm2d(o),
nn.ReLU(inplace=True),
)
class Student(nn.Module):
def __init__(self) -> None:
super().__init__()
# weights=None: the trained checkpoint below replaces every
# parameter, so the ImageNet download would be wasted bytes.
r = torchvision.models.resnet34(weights=None)
self.stem = nn.Sequential(r.conv1, r.bn1, r.relu) # /2, 64ch
self.pool = r.maxpool
self.l1, self.l2, self.l3, self.l4 = (
r.layer1, r.layer2, r.layer3, r.layer4
)
self.d4 = block(512 + 256, 256)
self.d3 = block(256 + 128, 128)
self.d2 = block(128 + 64, 64)
self.d1 = block(64 + 64, 48)
self.d0 = block(48, 32)
self.head = nn.Conv2d(32, 1, 3, padding=1)
self.register_buffer(
"mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
)
self.register_buffer(
"std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
up = lambda t: nn.functional.interpolate(
t, scale_factor=2, mode="bilinear", align_corners=False
)
x = (x - self.mean) / self.std
s0 = self.stem(x)
s1 = self.l1(self.pool(s0))
s2 = self.l2(s1)
s3 = self.l3(s2)
s4 = self.l4(s3)
y = self.d4(torch.cat([up(s4), s3], 1))
y = self.d3(torch.cat([up(y), s2], 1))
y = self.d2(torch.cat([up(y), s1], 1))
y = self.d1(torch.cat([up(y), s0], 1))
return self.head(self.d0(up(y)))[:, 0] # H x W disparity
return Student()
H, W = 288, 512 # model input resolution (height x width)
_student = build_student()
_ckpt = hf_hub_download(
"itaimizlish/daniel-student-depth", "student_v5.pt", repo_type="model"
)
_student.load_state_dict(torch.load(_ckpt, map_location="cpu"))
_student.eval().to("cuda")
# ------------------------------------------------------- pre/post (deployed path, from onboard/edge_depth.py) ----
def crop_box(h: int, w: int, out_h: int, out_w: int) -> tuple:
"""Center-crop box (x, y, cw, ch) of aspect out_w/out_h inside an h x w frame."""
a = out_w / out_h
cw, ch = (w, round(w / a)) if w / h < a else (round(h * a), h)
return (w - cw) // 2, (h - ch) // 2, cw, ch
def preprocess(rgb: np.ndarray) -> torch.Tensor:
"""Center-crop to the model's aspect, INTER_AREA-resize to 512x288, scale to [0,1]."""
x, y, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W)
img = cv2.resize(
rgb[y : y + ch, x : x + cw], (W, H), interpolation=cv2.INTER_AREA
)
arr = (img.astype(np.float32) / 255.0).transpose(2, 0, 1)[None]
return torch.from_numpy(np.ascontiguousarray(arr))
def colour_disp(d: np.ndarray) -> np.ndarray:
"""Percentile-stretched INFERNO rendering of disparity (near = bright)."""
lo, hi = np.percentile(d, [1, 99])
norm = np.clip((d - lo) / (hi - lo + 1e-8), 0, 1)
bgr = cv2.applyColorMap((norm * 255).astype(np.uint8), cv2.COLORMAP_INFERNO)
return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
# ------------------------------------------------------------------ app ----
@spaces.GPU(duration=10)
def predict_depth(
image, max_side: int = 1280
) -> tuple[np.ndarray, np.ndarray, str]:
"""Estimate a relative depth map from a single RGB image.
Args:
image: input RGB image (upload, webcam, or example).
max_side: longest side (px) the image is downscaled to before the crop,
to bound the pre-processing cost on huge inputs.
Returns:
Tuple of (colorized depth, grayscale disparity, status text).
"""
if image is None:
raise ValueError("Please provide an input image first.")
t0 = time.perf_counter()
if isinstance(image, str):
bgr = cv2.imread(image, cv2.IMREAD_COLOR)
if bgr is None:
raise ValueError(f"Could not read image: {image}")
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
else:
rgb = np.asarray(image.data if hasattr(image, "data") else image)
if rgb.ndim == 3 and rgb.shape[2] == 4: # RGBA -> RGB
rgb = cv2.cvtColor(rgb, cv2.COLOR_RGBA2RGB)
if rgb.dtype != np.uint8:
if rgb.max() <= 1.0:
rgb = (rgb * 255)
rgb = rgb.astype(np.uint8)
h, w = rgb.shape[:2]
if max(h, w) > max_side:
s = max_side / max(h, w)
rgb = cv2.resize(
rgb, (max(1, round(w * s)), max(1, round(h * s))),
interpolation=cv2.INTER_AREA,
)
x = preprocess(rgb).to("cuda")
with torch.no_grad():
disp = _student(x)[0].float().cpu().numpy() # 288x512, near = high
coloured = colour_disp(disp)
gray = (np.clip(disp, 0, None) / max(disp.max(), 1e-8) * 255).astype(np.uint8)
ms = (time.perf_counter() - t0) * 1000
x0, y0, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W)
status = (
f"inference {ms:.0f} ms · input {rgb.shape[1]}x{rgb.shape[0]} -> "
f"crop ({x0},{y0},{cw},{ch}) -> {W}x{H} · disparity range "
f"[{disp.min():.2f}, {disp.max():.2f}]"
)
return coloured, gray, status
EXAMPLES = sorted(str(p) for p in Path("examples").glob("*.jpg"))
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
TITLE = """
# DANIEL student depth
**Attention-free monocular depth for onboard robot navigation** — a 24.5M-parameter
ResNet-34 U-Net distilled from Depth Anything V2-Large, built to run on a
$35 single-board computer. Upload an image (or click an example) to get the
relative depth map the robot actually navigates on.
[Paper](https://huggingface.co/papers/2611.32718) ·
[GitHub](https://github.com/itaim18/DANIEL) ·
[Model](https://huggingface.co/itaimizlish/daniel-student-depth)
"""
with gr.Blocks() as demo:
gr.Markdown(TITLE)
with gr.Column(elem_id="col-container"):
with gr.Row():
with gr.Column():
input_img = gr.Image(
type="numpy", label="Input image", sources=["upload", "clipboard", "webcam"]
)
run_btn = gr.Button("Estimate depth", variant="primary")
with gr.Column():
depth_img = gr.Image(
type="numpy", label="Depth (relative, near = bright)", interactive=False
)
disp_img = gr.Image(
type="numpy", label="Raw disparity (grayscale)", interactive=False
)
status_txt = gr.Markdown()
with gr.Accordion("Advanced options", open=False):
max_side = gr.Slider(
minimum=512, maximum=4096, value=1280, step=64,
label="Downscale longest side to (px)",
info="Bounds pre-processing cost on very large inputs; the model always sees 512x288.",
)
gr.Examples(
examples=[[p] for p in EXAMPLES],
inputs=[input_img],
outputs=[depth_img, disp_img, status_txt],
fn=predict_depth,
cache_examples=True,
cache_mode="lazy",
)
run_btn.click(
predict_depth,
inputs=[input_img, max_side],
outputs=[depth_img, disp_img, status_txt],
api_name="predict_depth",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
|