| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import os |
| import sys |
| from typing import * |
| from pathlib import Path |
|
|
| import click |
| import torch |
| import torch.nn.functional as F |
| import torchvision.transforms as T |
| import torchvision.transforms.functional as TF |
|
|
| from moge.test.baseline import MGEBaselineInterface |
|
|
|
|
| class Baseline(MGEBaselineInterface): |
| def __init__(self, repo_path: str, hf_id: str, num_tokens: Optional[int], device: Union[torch.device, str]): |
| repo_path = os.path.abspath(repo_path) |
| if not Path(repo_path).exists(): |
| raise FileNotFoundError( |
| f"Cannot find Depth-Anything-3 repo at {repo_path}. Clone " |
| f"https://github.com/ByteDance-Seed/Depth-Anything-3." |
| ) |
| src_path = os.path.join(repo_path, 'src') |
| if src_path not in sys.path: |
| sys.path.insert(0, src_path) |
|
|
| |
| os.environ.setdefault('DA3_LOG_LEVEL', 'WARN') |
|
|
| from depth_anything_3.api import DepthAnything3 |
|
|
| device = torch.device(device) |
| model = DepthAnything3.from_pretrained(hf_id) |
| model.to(device).eval() |
|
|
| self.model = model |
| self.num_tokens = num_tokens |
| self.device = device |
|
|
| @click.command() |
| @click.option('--repo', 'repo_path', type=click.Path(), default='../Depth-Anything-3', |
| help='Path to the ByteDance-Seed/Depth-Anything-3 repository.') |
| @click.option('--hf_id', type=str, default='depth-anything/DA3MONO-LARGE', |
| help='HF repo id of the DA3-Mono variant (e.g. depth-anything/DA3MONO-LARGE).') |
| @click.option('--num_tokens', type=int, default=None, |
| help='Number of tokens; None uses 518 / min(H, W) factor as in da3.py.') |
| @click.option('--device', type=str, default='cuda') |
| @staticmethod |
| def load(repo_path: str, hf_id: str, num_tokens: Optional[int], device: str = 'cuda'): |
| return Baseline(repo_path, hf_id, num_tokens, device) |
|
|
| @torch.inference_mode() |
| def infer(self, image: torch.Tensor, intrinsics: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]: |
| |
| assert intrinsics is None, "DA3-Mono does not consume intrinsics." |
| original_height, original_width = image.shape[-2:] |
|
|
| if image.ndim == 3: |
| image = image.unsqueeze(0) |
| omit_batch_dim = True |
| else: |
| omit_batch_dim = False |
|
|
| |
| |
| |
| |
| |
| import numpy as np |
| np_img = (image[0].cpu().permute(1, 2, 0).clamp(0, 1).numpy() * 255).astype(np.uint8) |
| prediction = self.model.inference([np_img]) |
|
|
| |
| depth_t = torch.as_tensor(prediction.depth[0], device=self.device, dtype=torch.float32) |
| if depth_t.shape != (original_height, original_width): |
| depth_t = F.interpolate(depth_t[None, None], size=(original_height, original_width), |
| mode='bilinear', align_corners=False)[0, 0] |
|
|
| if not omit_batch_dim: |
| depth_t = depth_t.unsqueeze(0) |
| return {'depth_scale_invariant': depth_t} |
|
|