File size: 14,514 Bytes
da3ed5b | 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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | """
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')
# Paths
DA2_REPO = '/home/ywan0794/Depth-Anything-V2'
DA3_REPO = '/home/ywan0794/Depth-Anything-3'
# Checkpoints
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',
}
# Dataset paths
KITTI_BASE = '/home/ywan0794/datasets/eval/moge_style_eval/KITTI'
DDAD_BASE = '/home/ywan0794/datasets/eval/moge_style_eval/DDAD/val'
# ============================================
# DA2 Model Loading (same as da2_custom.py)
# ============================================
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 configurations (same as training)
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]}
}
# Build model based on decoder type
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}")
# Load checkpoint
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
# ============================================
# DA3 Model Loading (same as da3_custom.py)
# ============================================
class DA3Wrapper(torch.nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
def forward(self, x):
# x: [B, 3, H, W]
x = x.unsqueeze(1) # [B, 1, 3, H, W]
output = self.model(x)
depth = output.depth.squeeze(1) # [B, H, W]
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 paths
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
# Build model
cfg = load_config(config_path)
base_model = create_object(cfg)
model = DA3Wrapper(base_model)
# Load checkpoint
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
# ============================================
# Inference Wrapper
# ============================================
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"""
# Convert to tensor
img = TF.to_tensor(image).unsqueeze(0) # [1, 3, H, W]
original_height, original_width = img.shape[-2:]
# Resize to multiple of 14
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)
# Forward
if self.use_amp:
with torch.cuda.amp.autocast(dtype=torch.bfloat16):
disp = self.model(img)
else:
disp = self.model(img)
# Resize back
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()
# Create mask for invalid (zero) regions
if mask_invalid:
invalid_mask = depth <= 0
# Only use valid values for percentile calculation
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)
# Reverse if needed
if reverse:
depth = 1 - depth
cm = plt.get_cmap(cmap)
colored = cm(depth)[:, :, :3]
colored = (colored * 255).astype(np.uint8)
# Set invalid regions to black
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)
# Create output directories
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 = {}
# Load DA2 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)
# Load DA3 models
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!")
# Get KITTI samples
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}"
})
# Get DDAD samples
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}"
})
# Select random samples
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)
# Process KITTI
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']}")
# Load image
image = Image.open(sample['image']).convert('RGB')
# Save RGB
image.save(os.path.join(args.output_dir, 'KITTI', 'rgb', f"{idx:03d}.png"))
# Load and save GT (both versions)
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"))
# Predict and save for each model
for model_name, wrapper in models.items():
pred = wrapper.predict(image)
# DA3 DPT needs reverse
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")
)
# Process DDAD
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']}")
# Load image
image = Image.open(sample['image']).convert('RGB')
# Save RGB
image.save(os.path.join(args.output_dir, 'DDAD', 'rgb', f"{idx:03d}.png"))
# Load and save GT (both versions)
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"))
# Predict and save for each model
for model_name, wrapper in models.items():
pred = wrapper.predict(image)
# DA3 DPT needs reverse
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()
|