| """ |
| Visualize depth predictions from different decoders on KITTI and DDAD datasets |
| """ |
| import os |
| import sys |
| import argparse |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| import torchvision.transforms as T |
| import torchvision.transforms.functional as TF |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| import matplotlib |
| matplotlib.use('Agg') |
|
|
| |
| DA2_REPO = '/home/ywan0794/Depth-Anything-V2' |
| DA3_REPO = '/home/ywan0794/Depth-Anything-3' |
|
|
| |
| CHECKPOINTS = { |
| 'da2_dpt': '/home/ywan0794/Depth-Anything-V2/training/exp/dpt_vitb_both/epoch_007.pth', |
| 'da2_sdt': '/home/ywan0794/Depth-Anything-V2/training/exp/sdt_vitb_both/epoch_008.pth', |
| 'da3_dpt': '/home/ywan0794/Depth-Anything-3/training/exp/da3_dpt_vitl_both/epoch_010.pth', |
| 'da3_sdt': '/home/ywan0794/Depth-Anything-3/training/exp/da3_sdt_vitl_both/epoch_010.pth', |
| 'da3_dualdpt': '/home/ywan0794/Depth-Anything-3/training/exp/da3_dualdpt_vitl_both/epoch_010.pth', |
| } |
|
|
| |
| KITTI_BASE = '/home/ywan0794/datasets/eval/moge_style_eval/KITTI' |
| DDAD_BASE = '/home/ywan0794/datasets/eval/moge_style_eval/DDAD/val' |
|
|
|
|
| |
| |
| |
| def load_da2_model(checkpoint_path, encoder='vitb', decoder='dpt'): |
| """Load DA2 model with DPT or SDT decoder""" |
| repo_path = DA2_REPO |
| training_path = os.path.join(repo_path, 'training') |
|
|
| if repo_path not in sys.path: |
| sys.path.insert(0, repo_path) |
| if training_path not in sys.path: |
| sys.path.insert(0, training_path) |
|
|
| |
| model_configs = { |
| 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]}, |
| 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]}, |
| 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]}, |
| 'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]} |
| } |
|
|
| |
| if decoder == 'dpt': |
| from depth_anything_v2.dpt import DepthAnythingV2 |
| model = DepthAnythingV2(**model_configs[encoder]) |
| elif decoder == 'sdt': |
| from depth_anything_v2.sdt import DepthAnythingV2SDT |
| model = DepthAnythingV2SDT( |
| encoder=encoder, |
| features=model_configs[encoder]['features'], |
| out_channels=model_configs[encoder]['out_channels'], |
| use_clstoken=True, |
| upsampler='dysample' |
| ) |
| else: |
| raise ValueError(f"Unknown decoder: {decoder}") |
|
|
| |
| ckpt = torch.load(checkpoint_path, map_location='cpu') |
| if 'model' in ckpt: |
| state_dict = ckpt['model'] |
| else: |
| state_dict = ckpt |
| state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} |
| missing, unexpected = model.load_state_dict(state_dict, strict=False) |
| print(f"Loaded DA2 {decoder} from {checkpoint_path}") |
| if missing: |
| print(f" Missing keys: {len(missing)}") |
| if unexpected: |
| print(f" Unexpected keys: {len(unexpected)}") |
|
|
| return model |
|
|
|
|
| |
| |
| |
| class DA3Wrapper(torch.nn.Module): |
| def __init__(self, model): |
| super().__init__() |
| self.model = model |
|
|
| def forward(self, x): |
| |
| x = x.unsqueeze(1) |
| output = self.model(x) |
| depth = output.depth.squeeze(1) |
| return depth |
|
|
|
|
| def load_da3_model(checkpoint_path, decoder='dpt'): |
| """Load DA3 model with DPT, SDT, or DualDPT decoder""" |
| repo_path = DA3_REPO |
| src_path = os.path.join(repo_path, 'src') |
| training_path = os.path.join(repo_path, 'training') |
|
|
| if src_path not in sys.path: |
| sys.path.insert(0, src_path) |
| if training_path not in sys.path: |
| sys.path.insert(0, training_path) |
|
|
| |
| config_dir = os.path.join(repo_path, 'src', 'depth_anything_3', 'configs') |
| if decoder == 'dpt': |
| config_path = os.path.join(config_dir, 'da3dpt-large.yaml') |
| elif decoder == 'sdt': |
| config_path = os.path.join(config_dir, 'da3sdt-large.yaml') |
| elif decoder == 'dualdpt': |
| config_path = os.path.join(config_dir, 'da3dualdpt-large.yaml') |
| else: |
| raise ValueError(f"Unknown decoder: {decoder}") |
|
|
| from depth_anything_3.cfg import load_config, create_object |
|
|
| |
| cfg = load_config(config_path) |
| base_model = create_object(cfg) |
| model = DA3Wrapper(base_model) |
|
|
| |
| ckpt = torch.load(checkpoint_path, map_location='cpu') |
| if 'model' in ckpt: |
| state_dict = ckpt['model'] |
| else: |
| state_dict = ckpt |
| state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} |
| missing, unexpected = model.load_state_dict(state_dict, strict=False) |
| print(f"Loaded DA3 {decoder} from {checkpoint_path}") |
| if missing: |
| print(f" Missing keys: {len(missing)}") |
| if unexpected: |
| print(f" Unexpected keys: {len(unexpected)}") |
|
|
| return model |
|
|
|
|
| |
| |
| |
| class ModelWrapper: |
| def __init__(self, model, device, use_amp=True): |
| self.model = model.to(device).eval() |
| self.device = device |
| self.use_amp = use_amp |
|
|
| @torch.inference_mode() |
| def predict(self, image): |
| """image: PIL Image, returns disparity numpy array""" |
| |
| img = TF.to_tensor(image).unsqueeze(0) |
| original_height, original_width = img.shape[-2:] |
|
|
| |
| resize_factor = 518 / min(original_height, original_width) |
| expected_width = round(original_width * resize_factor / 14) * 14 |
| expected_height = round(original_height * resize_factor / 14) * 14 |
|
|
| img = TF.resize(img, (expected_height, expected_width), interpolation=T.InterpolationMode.BICUBIC, antialias=True) |
| img = TF.normalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| img = img.to(self.device) |
|
|
| |
| if self.use_amp: |
| with torch.cuda.amp.autocast(dtype=torch.bfloat16): |
| disp = self.model(img) |
| else: |
| disp = self.model(img) |
|
|
| |
| disp = F.interpolate(disp[:, None], size=(original_height, original_width), mode='bilinear', align_corners=False)[:, 0] |
| disp = disp.squeeze().cpu().numpy() |
|
|
| return disp |
|
|
|
|
| def colorize_depth(depth, cmap='Spectral', reverse=False, mask_invalid=False): |
| """Convert depth/disparity to colorized image using Spectral colormap""" |
| depth = depth.copy() |
|
|
| |
| if mask_invalid: |
| invalid_mask = depth <= 0 |
|
|
| |
| if mask_invalid: |
| valid_depth = depth[~invalid_mask] |
| if len(valid_depth) > 0: |
| vmin = np.percentile(valid_depth, 2) |
| vmax = np.percentile(valid_depth, 98) |
| else: |
| vmin, vmax = 0, 1 |
| else: |
| vmin = np.percentile(depth, 2) |
| vmax = np.percentile(depth, 98) |
|
|
| depth = (depth - vmin) / (vmax - vmin + 1e-8) |
| depth = np.clip(depth, 0, 1) |
|
|
| |
| if reverse: |
| depth = 1 - depth |
|
|
| cm = plt.get_cmap(cmap) |
| colored = cm(depth)[:, :, :3] |
| colored = (colored * 255).astype(np.uint8) |
|
|
| |
| if mask_invalid: |
| colored[invalid_mask] = 0 |
|
|
| return colored |
|
|
|
|
| def load_gt_depth(depth_path): |
| """Load ground truth depth from PNG""" |
| depth = np.array(Image.open(depth_path)) |
| if depth.dtype == np.uint16: |
| depth = depth.astype(np.float32) / 256.0 |
| elif depth.dtype == np.uint8: |
| depth = depth.astype(np.float32) |
| return depth |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument('--output-dir', type=str, default='/home/ywan0794/MoGe/vis_output') |
| parser.add_argument('--num-samples', type=int, default=10) |
| parser.add_argument('--device', type=str, default='cuda') |
| args = parser.parse_args() |
|
|
| device = torch.device(args.device) |
|
|
| |
| datasets = ['KITTI', 'DDAD'] |
| subfolders = ['rgb', 'gt', 'gt_reverse', 'da2_dpt', 'da2_sdt', 'da3_dpt', 'da3_sdt', 'da3_dualdpt'] |
|
|
| for dataset in datasets: |
| for subfolder in subfolders: |
| os.makedirs(os.path.join(args.output_dir, dataset, subfolder), exist_ok=True) |
|
|
| print("Loading models...") |
| models = {} |
|
|
| |
| print(" Loading DA2-DPT...") |
| da2_dpt = load_da2_model(CHECKPOINTS['da2_dpt'], encoder='vitb', decoder='dpt') |
| models['da2_dpt'] = ModelWrapper(da2_dpt, device, use_amp=False) |
|
|
| print(" Loading DA2-SDT...") |
| da2_sdt = load_da2_model(CHECKPOINTS['da2_sdt'], encoder='vitb', decoder='sdt') |
| models['da2_sdt'] = ModelWrapper(da2_sdt, device, use_amp=False) |
|
|
| |
| print(" Loading DA3-DPT...") |
| da3_dpt = load_da3_model(CHECKPOINTS['da3_dpt'], decoder='dpt') |
| models['da3_dpt'] = ModelWrapper(da3_dpt, device, use_amp=True) |
|
|
| print(" Loading DA3-SDT...") |
| da3_sdt = load_da3_model(CHECKPOINTS['da3_sdt'], decoder='sdt') |
| models['da3_sdt'] = ModelWrapper(da3_sdt, device, use_amp=True) |
|
|
| print(" Loading DA3-DualDPT...") |
| da3_dualdpt = load_da3_model(CHECKPOINTS['da3_dualdpt'], decoder='dualdpt') |
| models['da3_dualdpt'] = ModelWrapper(da3_dualdpt, device, use_amp=True) |
|
|
| print("All models loaded!") |
|
|
| |
| kitti_samples = [] |
| for drive in os.listdir(KITTI_BASE): |
| drive_path = os.path.join(KITTI_BASE, drive, 'image_02') |
| if os.path.isdir(drive_path): |
| for frame in sorted(os.listdir(drive_path)): |
| sample_dir = os.path.join(drive_path, frame) |
| img_path = os.path.join(sample_dir, 'image.jpg') |
| gt_path = os.path.join(sample_dir, 'depth.png') |
| if os.path.exists(img_path) and os.path.exists(gt_path): |
| kitti_samples.append({ |
| 'image': img_path, |
| 'gt': gt_path, |
| 'name': f"{drive}_{frame}" |
| }) |
|
|
| |
| ddad_samples = [] |
| for scene in sorted(os.listdir(DDAD_BASE)): |
| scene_path = os.path.join(DDAD_BASE, scene) |
| if os.path.isdir(scene_path): |
| for cam in sorted(os.listdir(scene_path)): |
| sample_dir = os.path.join(scene_path, cam) |
| img_path = os.path.join(sample_dir, 'image.jpg') |
| gt_path = os.path.join(sample_dir, 'depth.png') |
| if os.path.exists(img_path) and os.path.exists(gt_path): |
| ddad_samples.append({ |
| 'image': img_path, |
| 'gt': gt_path, |
| 'name': f"{scene}_{cam}" |
| }) |
|
|
| |
| np.random.seed(42) |
| kitti_selected = np.random.choice(len(kitti_samples), min(args.num_samples, len(kitti_samples)), replace=False) |
| ddad_selected = np.random.choice(len(ddad_samples), min(args.num_samples, len(ddad_samples)), replace=False) |
|
|
| |
| print(f"\nProcessing {len(kitti_selected)} KITTI samples...") |
| for idx, i in enumerate(kitti_selected): |
| sample = kitti_samples[i] |
| print(f" [{idx+1}/{len(kitti_selected)}] {sample['name']}") |
|
|
| |
| image = Image.open(sample['image']).convert('RGB') |
|
|
| |
| image.save(os.path.join(args.output_dir, 'KITTI', 'rgb', f"{idx:03d}.png")) |
|
|
| |
| gt_depth = load_gt_depth(sample['gt']) |
| gt_colored = colorize_depth(gt_depth, reverse=False, mask_invalid=True) |
| gt_colored_rev = colorize_depth(gt_depth, reverse=True, mask_invalid=True) |
| Image.fromarray(gt_colored).save(os.path.join(args.output_dir, 'KITTI', 'gt', f"{idx:03d}.png")) |
| Image.fromarray(gt_colored_rev).save(os.path.join(args.output_dir, 'KITTI', 'gt_reverse', f"{idx:03d}.png")) |
|
|
| |
| for model_name, wrapper in models.items(): |
| pred = wrapper.predict(image) |
| |
| need_reverse = (model_name == 'da3_dpt') |
| pred_colored = colorize_depth(pred, reverse=need_reverse) |
| Image.fromarray(pred_colored).save( |
| os.path.join(args.output_dir, 'KITTI', model_name, f"{idx:03d}.png") |
| ) |
|
|
| |
| print(f"\nProcessing {len(ddad_selected)} DDAD samples...") |
| for idx, i in enumerate(ddad_selected): |
| sample = ddad_samples[i] |
| print(f" [{idx+1}/{len(ddad_selected)}] {sample['name']}") |
|
|
| |
| image = Image.open(sample['image']).convert('RGB') |
|
|
| |
| image.save(os.path.join(args.output_dir, 'DDAD', 'rgb', f"{idx:03d}.png")) |
|
|
| |
| gt_depth = load_gt_depth(sample['gt']) |
| gt_colored = colorize_depth(gt_depth, reverse=False, mask_invalid=True) |
| gt_colored_rev = colorize_depth(gt_depth, reverse=True, mask_invalid=True) |
| Image.fromarray(gt_colored).save(os.path.join(args.output_dir, 'DDAD', 'gt', f"{idx:03d}.png")) |
| Image.fromarray(gt_colored_rev).save(os.path.join(args.output_dir, 'DDAD', 'gt_reverse', f"{idx:03d}.png")) |
|
|
| |
| for model_name, wrapper in models.items(): |
| pred = wrapper.predict(image) |
| |
| need_reverse = (model_name == 'da3_dpt') |
| pred_colored = colorize_depth(pred, reverse=need_reverse) |
| Image.fromarray(pred_colored).save( |
| os.path.join(args.output_dir, 'DDAD', model_name, f"{idx:03d}.png") |
| ) |
|
|
| print(f"\nDone! Results saved to {args.output_dir}") |
| print(f"Structure:") |
| print(f" {args.output_dir}/") |
| print(f" KITTI/") |
| print(f" rgb/, gt/, gt_reverse/, da2_dpt/, da2_sdt/, da3_dpt/, da3_sdt/, da3_dualdpt/") |
| print(f" DDAD/") |
| print(f" rgb/, gt/, gt_reverse/, da2_dpt/, da2_sdt/, da3_dpt/, da3_sdt/, da3_dualdpt/") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|