-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdepth_estimation_node.py
More file actions
3242 lines (2763 loc) · 164 KB
/
depth_estimation_node.py
File metadata and controls
3242 lines (2763 loc) · 164 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gc
import json
import logging
import os
import time
import traceback
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Tuple, List, Dict, Any, Optional, Union
import numpy as np
import requests
import torch
import torch.nn as nn
import torch.nn.functional as F
import wget
from PIL import Image, ImageFilter, ImageOps, ImageDraw, ImageFont
from transformers import pipeline
import folder_paths
from comfy.model_management import get_torch_device, get_free_memory
# Custom ComfyUI type definitions for camera parameters
CAMERA_EXTRINSICS = "CAMERA_EXTRINSICS"
CAMERA_INTRINSICS = "CAMERA_INTRINSICS"
# Try to import timm (for vision transformers)
try:
import timm
TIMM_AVAILABLE = True
except ImportError:
TIMM_AVAILABLE = False
print("Warning: timm not available. Direct loading of Depth Anything models may not work.")
# Get logger instance (basicConfig is called in __init__.py)
logger = logging.getLogger("DepthEstimation")
# Import DA3 availability status from the package's __init__
from . import DA3_AVAILABLE
# Conditionally import Depth Anything V3 if available
# Use defensive import guard to handle edge cases where DA3_AVAILABLE check passes
# but the actual import still fails (e.g., corrupted install, version mismatch)
if DA3_AVAILABLE:
try:
from depth_anything_3.api import DepthAnything3
except ImportError as e:
DA3_AVAILABLE = False
logger.warning(f"DA3 import failed despite availability check: {e}. DA3 models disabled.")
# Depth Anything V2 Implementation
class DepthAnythingV2(nn.Module):
"""Direct implementation of Depth Anything V2 model"""
def __init__(self, encoder='vits', features=64, out_channels=[48, 96, 192, 384]):
super().__init__()
self.encoder = encoder
self.features = features
self.out_channels = out_channels
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Create encoder based on specification
if TIMM_AVAILABLE:
if encoder == 'vits':
self.backbone = timm.create_model('vit_small_patch16_224', pretrained=False)
self.embed_dim = 384
elif encoder == 'vitb':
self.backbone = timm.create_model('vit_base_patch16_224', pretrained=False)
self.embed_dim = 768
elif encoder == 'vitl':
self.backbone = timm.create_model('vit_large_patch16_224', pretrained=False)
self.embed_dim = 1024
else: # fallback to vits
self.backbone = timm.create_model('vit_small_patch16_224', pretrained=False)
self.embed_dim = 384
# Implement the rest of the model architecture
self.initialize_decoder()
else:
# Fallback if timm is not available
from torchvision.models import resnet50
self.backbone = resnet50(pretrained=False)
self.embed_dim = 2048
logger.warning("Using fallback ResNet50 model (timm not available)")
def initialize_decoder(self):
"""Initialize the decoder layers"""
self.neck = nn.Sequential(
nn.Conv2d(self.embed_dim, self.features, 1, 1, 0),
nn.Conv2d(self.features, self.features, 3, 1, 1),
)
# Create decoders for each level
self.decoders = nn.ModuleList([
self.create_decoder_level(self.features, self.out_channels[0]),
self.create_decoder_level(self.out_channels[0], self.out_channels[1]),
self.create_decoder_level(self.out_channels[1], self.out_channels[2]),
self.create_decoder_level(self.out_channels[2], self.out_channels[3])
])
# Final depth head
self.depth_head = nn.Sequential(
nn.Conv2d(self.out_channels[3], self.out_channels[3], 3, 1, 1),
nn.BatchNorm2d(self.out_channels[3]),
nn.ReLU(True),
nn.Conv2d(self.out_channels[3], 1, 1)
)
def create_decoder_level(self, in_channels, out_channels):
"""Create a decoder level"""
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, 1, 1),
nn.BatchNorm2d(out_channels),
nn.ReLU(True),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
)
def forward(self, x):
"""Forward pass of the model"""
# For timm ViT models
if hasattr(self.backbone, 'forward_features'):
features = self.backbone.forward_features(x)
# Reshape features based on model type
if 'vit' in self.encoder:
# Reshape transformer output to spatial features
# Exact reshape depends on the model details
h = w = int(features.shape[1]**0.5)
features = features.reshape(-1, h, w, self.embed_dim).permute(0, 3, 1, 2)
# Process through decoder
x = self.neck(features)
# Apply decoder stages
for decoder in self.decoders:
x = decoder(x)
# Final depth prediction
depth = self.depth_head(x)
return depth
else:
# Fallback for ResNet
x = self.backbone.conv1(x)
x = self.backbone.bn1(x)
x = self.backbone.relu(x)
x = self.backbone.maxpool(x)
x = self.backbone.layer1(x)
x = self.backbone.layer2(x)
x = self.backbone.layer3(x)
x = self.backbone.layer4(x)
# Process through simple decoder
x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)
x = self.depth_head(x)
return x
def infer_image(self, image):
"""Process an image and return the depth map
Args:
image: A numpy image in BGR format (OpenCV) or RGB PIL Image
Returns:
depth: A numpy array containing the depth map
"""
# Convert input to tensor
if isinstance(image, np.ndarray):
# Convert BGR to RGB
if image.shape[2] == 3:
image = image[:, :, ::-1]
# Normalize
image = image.astype(np.float32) / 255.0
# HWC to CHW
image = image.transpose(2, 0, 1)
# Add batch dimension
image = torch.from_numpy(image).unsqueeze(0)
elif isinstance(image, Image.Image):
# Convert PIL image to numpy
image = np.array(image).astype(np.float32) / 255.0
# HWC to CHW
image = image.transpose(2, 0, 1)
# Add batch dimension
image = torch.from_numpy(image).unsqueeze(0)
# Move to device
image = image.to(self.device)
# Set model to eval mode
self.eval()
# Get prediction
with torch.no_grad():
depth = self.forward(image)
# Convert to numpy
depth = depth.squeeze().cpu().numpy()
return depth
def __call__(self, image):
"""Compatible interface with the pipeline API"""
if isinstance(image, Image.Image):
# Convert to numpy for processing
depth = self.infer_image(image)
# Return in the format expected by the node
return {"predicted_depth": torch.from_numpy(depth).unsqueeze(0)}
else:
# Already a tensor, process directly
self.eval()
with torch.no_grad():
depth = self.forward(image)
return {"predicted_depth": depth}
# Configure model paths
if not hasattr(folder_paths, "models_dir"):
folder_paths.models_dir = os.path.join(folder_paths.base_path, "models")
# Register depth models path - support multiple possible directory structures
DEPTH_DIR = "depth_anything"
DEPTH_ANYTHING_DIR = "depthanything"
# Check which directory structure exists
possible_paths = [
os.path.join(folder_paths.models_dir, DEPTH_DIR),
os.path.join(folder_paths.models_dir, DEPTH_ANYTHING_DIR),
os.path.join(folder_paths.models_dir, DEPTH_ANYTHING_DIR, DEPTH_DIR),
os.path.join(folder_paths.models_dir, "checkpoints", DEPTH_DIR),
os.path.join(folder_paths.models_dir, "checkpoints", DEPTH_ANYTHING_DIR),
]
# Filter to only paths that exist
existing_paths = [p for p in possible_paths if os.path.exists(p)]
if not existing_paths:
# If none exists, create the default one
existing_paths = [os.path.join(folder_paths.models_dir, DEPTH_DIR)]
os.makedirs(existing_paths[0], exist_ok=True)
logger.info(f"Created model directory: {existing_paths[0]}")
# Log all found paths for debugging
logger.info(f"Found depth model directories: {existing_paths}")
# Register all possible paths for model loading
folder_paths.folder_names_and_paths[DEPTH_DIR] = (existing_paths, folder_paths.supported_pt_extensions)
# Set primary models directory to the first available path
MODELS_DIR = existing_paths[0]
logger.info(f"Using primary models directory: {MODELS_DIR}")
# Set Hugging Face cache to the models directory to ensure models are saved there
os.environ["TRANSFORMERS_CACHE"] = MODELS_DIR
os.environ["HF_HOME"] = MODELS_DIR
# Define model configurations for direct loading
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]}
}
# Define all models mentioned in the README with memory requirements
DEPTH_MODELS = {
"Depth-Anything-Small": {
"path": "LiheYoung/depth-anything-small-hf", # Correct HF path for V1
"vram_mb": 1500,
"direct_url": "https://github.com/LiheYoung/Depth-Anything/releases/download/v1.0/depth_anything_vitb14.pt",
"model_type": "v1",
"encoder": "vitb"
},
"Depth-Anything-Base": {
"path": "LiheYoung/depth-anything-base-hf", # Correct HF path for V1
"vram_mb": 2500,
"direct_url": "https://github.com/LiheYoung/Depth-Anything/releases/download/v1.0/depth_anything_vitl14.pt",
"model_type": "v1",
"encoder": "vitl"
},
"Depth-Anything-Large": {
"path": "LiheYoung/depth-anything-large-hf", # Correct HF path for V1
"vram_mb": 4000,
"direct_url": "https://github.com/LiheYoung/Depth-Anything/releases/download/v1.0/depth_anything_vitl14.pt",
"model_type": "v1",
"encoder": "vitl"
},
"Depth-Anything-V2-Small": {
"path": "depth-anything/Depth-Anything-V2-Small-hf", # Updated corrected path as shown in example
"vram_mb": 1500,
"direct_url": "https://huggingface.co/depth-anything/Depth-Anything-V2-Small-hf/resolve/main/pytorch_model.bin",
"model_type": "v2",
"encoder": "vits",
"config": MODEL_CONFIGS["vits"]
},
"Depth-Anything-V2-Base": {
"path": "depth-anything/Depth-Anything-V2-Base-hf", # Updated corrected path
"vram_mb": 2500,
"direct_url": "https://huggingface.co/depth-anything/Depth-Anything-V2-Base-hf/resolve/main/pytorch_model.bin",
"model_type": "v2",
"encoder": "vitb",
"config": MODEL_CONFIGS["vitb"]
},
# Add MiDaS models as dedicated options with direct download URLs
"MiDaS-Small": {
"path": "Intel/dpt-hybrid-midas",
"vram_mb": 1000,
"midas_type": "MiDaS_small",
"direct_url": "https://github.com/intel-isl/MiDaS/releases/download/v2_1/midas_v21_small_256.pt"
},
"MiDaS-Base": {
"path": "Intel/dpt-hybrid-midas",
"vram_mb": 1200,
"midas_type": "DPT_Hybrid",
"direct_url": "https://github.com/intel-isl/MiDaS/releases/download/v3/dpt_hybrid-midas-501f0c75.pt"
},
# DA3 (Depth Anything V3) Models - Apache 2.0 Licensed (Commercial Friendly)
# Note: These models require the depth_anything_v3 package to be installed
"Depth-Anything-V3-Small": {
"path": "depth-anything/DA3-Small",
"vram_mb": 2000, # Estimated: 80M params
"model_type": "v3",
"encoder": "vits",
"license": "Apache-2.0",
"supports_batch": True, # Multi-view support
"supports_pose": True,
"params": "80M"
},
"Depth-Anything-V3-Base": {
"path": "depth-anything/DA3-Base",
"vram_mb": 2500, # Estimated: 120M params
"model_type": "v3",
"encoder": "vitb",
"license": "Apache-2.0",
"supports_batch": True, # Multi-view support
"supports_pose": True,
"params": "120M"
},
"Depth-Anything-V3-Large": {
"path": "depth-anything/DA3-Large",
"vram_mb": 4000,
"model_type": "v3",
"encoder": "vitl",
"license": "CC BY-NC 4.0",
"supports_batch": True,
"supports_pose": True,
"params": "350M"
},
"Depth-Anything-V3-Giant": {
"path": "depth-anything/DA3-Giant",
"vram_mb": 6000,
"model_type": "v3",
"encoder": "vitg",
"license": "CC BY-NC 4.0",
"supports_batch": True,
"supports_pose": True,
"params": "1.15B"
},
"Depth-Anything-V3-Nested-Giant-Large": {
"path": "depth-anything/DA3NESTED-GIANT-LARGE",
"vram_mb": 7000,
"model_type": "v3",
"encoder": "nested",
"license": "CC BY-NC 4.0",
"supports_batch": True,
"supports_pose": True,
"metric_scaling": True,
"params": "1.4B"
},
"Depth-Anything-V3-Mono-Large": {
"path": "depth-anything/DA3Mono-Large",
"vram_mb": 4000,
"model_type": "v3",
"encoder": "vitl",
"license": "Apache-2.0",
"supports_batch": False,
"supports_pose": False,
"params": "350M",
"note": "Monocular only, no camera estimation"
},
"Depth-Anything-V3-Metric-Large": {
"path": "depth-anything/DA3Metric-Large",
"vram_mb": 4000,
"model_type": "v3",
"encoder": "vitl",
"license": "Apache-2.0",
"supports_batch": False,
"supports_pose": False,
"metric_depth": True,
"params": "350M",
"note": "Metric depth only, no camera estimation"
},
"Depth-Anything-V3-Large-1.1": {
"path": "depth-anything/DA3-LARGE-1.1",
"vram_mb": 4000,
"model_type": "v3",
"encoder": "vitl",
"license": "Apache-2.0",
"supports_batch": True,
"supports_pose": True,
"params": "350M"
},
"Depth-Anything-V3-Giant-1.1": {
"path": "depth-anything/DA3-GIANT-1.1",
"vram_mb": 6000,
"model_type": "v3",
"encoder": "vitg",
"license": "CC BY-NC 4.0",
"supports_batch": True,
"supports_pose": True,
"params": "1.15B"
},
"Depth-Anything-V3-Nested-Giant-Large-1.1": {
"path": "depth-anything/DA3NESTED-GIANT-LARGE-1.1",
"vram_mb": 7000,
"model_type": "v3",
"encoder": "nested",
"license": "CC BY-NC 4.0",
"supports_batch": True,
"supports_pose": True,
"metric_scaling": True,
"params": "1.4B"
},
}
class MiDaSWrapper:
def __init__(self, model_type, device):
self.device = device
try:
# Import required libraries
import torch.nn.functional as F
# Use a more reliable approach to loading MiDaS models
if model_type == "DPT_Hybrid" or model_type == "dpt_hybrid":
# Use direct URL download for MiDaS models
midas_url = "https://github.com/intel-isl/MiDaS/releases/download/v3/dpt_hybrid-midas-501f0c75.pt"
local_path = os.path.join(MODELS_DIR, "dpt_hybrid_midas.pt")
if not os.path.exists(local_path):
logger.info(f"Downloading MiDaS model from {midas_url}")
try:
response = requests.get(midas_url, stream=True)
if response.status_code == 200:
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logger.info(f"Downloaded MiDaS model to {local_path}")
else:
logger.error(f"Failed to download model: {response.status_code}")
except Exception as e:
logger.error(f"Error downloading MiDaS model: {e}")
# Load pretrained model
try:
# Create a simple model architecture
from torchvision.models import resnet50
self.model = resnet50()
self.model.fc = torch.nn.Linear(2048, 1)
# Load state dict if available
if os.path.exists(local_path):
logger.info(f"Loading MiDaS model from {local_path}")
state_dict = torch.load(local_path, map_location=device)
# Convert all parameters to float
floated_state_dict = {k: v.float() for k, v in state_dict.items()}
self.model.load_state_dict(floated_state_dict)
except Exception as e:
logger.error(f"Error loading MiDaS model state dict: {e}")
# Fallback to ResNet
self.model = resnet50(pretrained=True)
self.model.fc = torch.nn.Linear(2048, 1)
else: # Other model types or fallback
from torchvision.models import resnet50
self.model = resnet50(pretrained=True)
self.model.fc = torch.nn.Linear(2048, 1)
# Ensure model parameters are float
for param in self.model.parameters():
param.data = param.data.float()
# Explicitly convert model to FloatTensor
self.model = self.model.float()
# Move model to device and set to eval mode
self.model = self.model.to(device)
self.model.eval()
except Exception as e:
logger.error(f"Failed to load MiDaS model: {e}")
logger.error(traceback.format_exc())
# Create a minimal model as absolute fallback
from torchvision.models import resnet18
self.model = resnet18(pretrained=True).float().to(device)
self.model.fc = torch.nn.Linear(512, 1).float().to(device)
self.model.eval()
def __call__(self, image):
"""Process an image and return the depth map"""
try:
# Convert PIL image to tensor for processing
if isinstance(image, Image.Image):
# Get original dimensions
original_width, original_height = image.size
# Ensure dimensions are multiple of 32 (required for some models)
# This helps prevent tensor dimension mismatches
target_height = ((original_height + 31) // 32) * 32
target_width = ((original_width + 31) // 32) * 32
# Keep original dimensions - don't force 384x384
# The caller should already have resized to the requested input_size
# Log resize information if needed
if (target_width != original_width) or (target_height != original_height):
logger.info(f"Adjusting dimensions from {original_width}x{original_height} to {target_width}x{target_height} (multiples of 32)")
img_resized = image.resize((target_width, target_height), Image.LANCZOS)
else:
img_resized = image
# Convert to numpy array
img_np = np.array(img_resized).astype(np.float32) / 255.0
# Check for NaN values and replace them with zeros
if np.isnan(img_np).any():
logger.warning("Input image contains NaN values. Replacing with zeros.")
img_np = np.nan_to_num(img_np, nan=0.0)
# Convert to tensor with proper shape (B,C,H,W)
if len(img_np.shape) == 3:
# RGB image
img_np = img_np.transpose(2, 0, 1) # (H,W,C) -> (C,H,W)
else:
# Grayscale image - add channel dimension
img_np = np.expand_dims(img_np, axis=0)
# Add batch dimension and ensure float32
input_tensor = torch.from_numpy(img_np).unsqueeze(0).float()
else:
# Already a tensor - ensure float32 by explicitly converting
# This is the key fix for the "Input type (torch.cuda.DoubleTensor) and weight type (torch.cuda.FloatTensor)" error
input_tensor = None
# Handle potential error cases with clearer messages
if not torch.is_tensor(image):
logger.error(f"Expected tensor or PIL image, got {type(image)}")
# Create dummy tensor as fallback
input_tensor = torch.ones((1, 3, 512, 512), dtype=torch.float32)
elif image.numel() == 0:
logger.error("Input tensor is empty")
# Create dummy tensor as fallback
input_tensor = torch.ones((1, 3, 512, 512), dtype=torch.float32)
else:
# Check for NaN values
if torch.isnan(image).any():
logger.warning("Input tensor contains NaN values. Replacing with zeros.")
image = torch.nan_to_num(image, nan=0.0)
# Always convert to float32 to prevent type mismatches
input_tensor = image.float() # Convert any tensor to FloatTensor
# Handle tensor shape issues with more robust dimension checking
if input_tensor.dim() == 2: # [H, W]
# Single channel 2D tensor
input_tensor = input_tensor.unsqueeze(0).unsqueeze(0) # Add batch and channel dims [1, 1, H, W]
logger.info(f"Converted 2D tensor to 4D with shape: {input_tensor.shape}")
elif input_tensor.dim() == 3:
# Could be [C, H, W] or [B, H, W] or [H, W, C]
shape = input_tensor.shape
if shape[-1] == 3 or shape[-1] == 1: # [H, W, C] format
# Convert from HWC to BCHW
input_tensor = input_tensor.permute(2, 0, 1).unsqueeze(0) # [H, W, C] -> [1, C, H, W]
logger.info(f"Converted HWC tensor to BCHW with shape: {input_tensor.shape}")
elif shape[0] <= 3: # Likely [C, H, W]
input_tensor = input_tensor.unsqueeze(0) # Add batch dim [1, C, H, W]
logger.info(f"Added batch dimension to CHW tensor: {input_tensor.shape}")
else: # Likely [B, H, W]
input_tensor = input_tensor.unsqueeze(1) # Add channel dim [B, 1, H, W]
logger.info(f"Added channel dimension to BHW tensor: {input_tensor.shape}")
# Ensure proper shape after corrections
if input_tensor.dim() != 4:
logger.warning(f"Tensor still has incorrect dimensions ({input_tensor.dim()}). Forcing reshape.")
# Force reshape to 4D
orig_shape = input_tensor.shape
if input_tensor.dim() > 4:
# Too many dimensions, collapse extras
input_tensor = input_tensor.reshape(1, -1, orig_shape[-2], orig_shape[-1])
else:
# Create a standard 4D tensor as fallback
input_tensor = torch.ones((1, 3, 512, 512), dtype=torch.float32)
# Move to device and ensure float type
input_tensor = input_tensor.to(self.device).float()
# Log tensor shape for debugging
logger.info(f"MiDaS input tensor shape: {input_tensor.shape}, dtype: {input_tensor.dtype}")
# Run inference with better error handling
with torch.no_grad():
try:
# Make sure input is float32 and model weights are float32
output = self.model(input_tensor)
# Handle various output shapes
if output.dim() == 1: # [B*H*W] flattened output
# Reshape based on input dimensions
b, _, h, w = input_tensor.shape
output = output.reshape(b, 1, h, w)
elif output.dim() == 2: # [B, H*W] or similar
# Could be flattened spatial dimensions
b = output.shape[0]
if b == input_tensor.shape[0]: # Batch size matches
h = int(np.sqrt(output.shape[1])) # Estimate height assuming square
w = h
if h * w == output.shape[1]: # Perfect square
output = output.reshape(b, 1, h, w)
else:
# Not a perfect square, use input dimensions
_, _, h, w = input_tensor.shape
output = output.reshape(b, 1, h, w)
else:
# Add dimensions to make 4D
output = output.unsqueeze(1).unsqueeze(1)
# Ensure output has standard 4D shape (B,C,H,W) for interpolation
if output.dim() != 4:
logger.warning(f"Output has non-standard dimensions: {output.shape}, adding dimensions")
# Add dimensions until we have 4D
while output.dim() < 4:
output = output.unsqueeze(-1)
# Resize to match input resolution
if isinstance(image, Image.Image):
w, h = image.size
# Log the shape for debugging
logger.info(f"Resizing output tensor from shape {output.shape} to size ({h}, {w})")
# Ensure output tensor has correct number of dimensions for interpolation
# Standard interpolation requires 4D tensor (B,C,H,W)
try:
# Now interpolate with proper dimensions
output = torch.nn.functional.interpolate(
output,
size=(h, w),
mode="bicubic",
align_corners=False
)
except RuntimeError as resize_err:
logger.error(f"Interpolation error: {resize_err}. Attempting to fix tensor shape.")
# Last resort: create compatible tensor from output data
try:
# Get data and reshape to simple 2D first
output_data = output.view(-1).cpu().numpy()
output_reshaped = torch.from_numpy(
np.resize(output_data, (h * w))
).reshape(1, 1, h, w).to(self.device).float()
logger.info(f"Corrected output shape to {output_reshaped.shape}")
output = output_reshaped
except Exception as reshape_err:
logger.error(f"Reshape fix failed: {reshape_err}. Using fallback tensor.")
# Create a basic gradient as fallback
output = torch.ones((1, 1, h, w), device=self.device, dtype=torch.float32)
y_coords = torch.linspace(0, 1, h).reshape(-1, 1).repeat(1, w)
output[0, 0, :, :] = y_coords.to(self.device)
except Exception as model_err:
logger.error(f"Model inference error: {model_err}")
logger.error(traceback.format_exc())
# Create a visually distinguishable gradient pattern fallback
if isinstance(image, Image.Image):
w, h = image.size
else:
# Extract dimensions from input tensor
_, _, h, w = input_tensor.shape if input_tensor.dim() >= 4 else (1, 1, 512, 512)
# Create gradient depth map as fallback
output = torch.ones((1, 1, h, w), device=self.device, dtype=torch.float32)
y_coords = torch.linspace(0, 1, h).reshape(-1, 1).repeat(1, w)
output[0, 0, :, :] = y_coords.to(self.device)
# Final validation - ensure output is float32 and has no NaNs
output = output.float()
if torch.isnan(output).any():
logger.warning("Output contains NaN values. Replacing with zeros.")
output = torch.nan_to_num(output, nan=0.0)
# Use same interface as the pipeline
return {"predicted_depth": output}
except Exception as e:
logger.error(f"Error in MiDaS inference: {e}")
logger.error(traceback.format_exc())
# Return a placeholder depth map
if isinstance(image, Image.Image):
w, h = image.size
dummy_tensor = torch.ones((1, 1, h, w), device=self.device)
else:
# Try to get shape from tensor
shape = image.shape
if len(shape) >= 3:
if shape[0] == 3: # CHW format
h, w = shape[1], shape[2]
else: # HWC format
h, w = shape[0], shape[1]
else:
h, w = 512, 512
dummy_tensor = torch.ones((1, 1, h, w), device=self.device)
return {"predicted_depth": dummy_tensor}
@dataclass
class DA3Prediction:
"""
Structured output from DA3 models containing all prediction fields.
"""
depth: torch.Tensor # [N, H, W] normalized 0-1
confidence: Optional[torch.Tensor] = None # [N, H, W] or None
extrinsics: Optional[torch.Tensor] = None # [N, 3, 4] or None
intrinsics: Optional[torch.Tensor] = None # [N, 3, 3] or None
processed_images: Optional[torch.Tensor] = None # [N, H, W, 3] uint8
raw_depth: Optional[torch.Tensor] = None # [N, H, W] unnormalized
supports_pose: bool = False
class DA3ModelWrapper:
"""
Enhanced wrapper for Depth Anything V3 API.
"""
def __init__(self, model, device, model_name: str):
self.model = model
self.device = device
self.model_name = model_name
self.supports_pose = self._check_pose_support(model_name)
logger.info(f"DA3ModelWrapper initialized: {model_name}, Pose support: {self.supports_pose}, Device: {device}")
def _check_pose_support(self, model_name: str) -> bool:
"""Check if model supports camera pose estimation (DA3 variants only)."""
model_lower = model_name.lower()
# Mono/metric variants don't support pose estimation
if "mono" in model_lower or "metric" in model_lower:
return False
# DA3 models with size variants support pose estimation
is_da3 = "v3" in model_lower or "da3" in model_lower
size_variants = ["small", "base", "large", "giant", "nested"]
return is_da3 and any(v in model_lower for v in size_variants)
def __call__(self, image: Union[Image.Image, List[Image.Image]]) -> DA3Prediction:
try:
if isinstance(image, Image.Image):
images = [image]
is_batch = False
else:
images = list(image)
is_batch = True
with torch.inference_mode():
prediction = self.model.inference(images)
# Extract depth maps
raw_depths = prediction.depth if hasattr(prediction, 'depth') else np.array(prediction)
# Normalize depths
normalized_depths = []
for depth in raw_depths:
depth_min, depth_max = depth.min(), depth.max()
if depth_max - depth_min > 1e-6:
norm_depth = (depth - depth_min) / (depth_max - depth_min)
else:
norm_depth = np.zeros_like(depth)
normalized_depths.append(norm_depth)
depth_array = np.stack(normalized_depths, axis=0)
depth_tensor = torch.from_numpy(depth_array).float().to(self.device)
raw_depth_tensor = torch.from_numpy(raw_depths).float().to(self.device)
# Extract confidence
confidence_tensor = None
if hasattr(prediction, 'conf') and prediction.conf is not None:
conf_array = prediction.conf
confidence_tensor = torch.from_numpy(conf_array).float().to(self.device)
# Extract camera parameters
extrinsics_tensor = None
intrinsics_tensor = None
if self.supports_pose:
if hasattr(prediction, 'extrinsics') and prediction.extrinsics is not None:
ext_array = prediction.extrinsics
extrinsics_tensor = torch.from_numpy(ext_array).float().to(self.device)
if hasattr(prediction, 'intrinsics') and prediction.intrinsics is not None:
int_array = prediction.intrinsics
intrinsics_tensor = torch.from_numpy(int_array).float().to(self.device)
# Extract processed images
processed_tensor = None
if hasattr(prediction, 'processed_images') and prediction.processed_images is not None:
proc_array = prediction.processed_images
processed_tensor = torch.from_numpy(proc_array).to(self.device)
# Handle single image case - squeeze batch dimension from all tensors
if not is_batch:
tensors = [depth_tensor, raw_depth_tensor, confidence_tensor,
extrinsics_tensor, intrinsics_tensor, processed_tensor]
depth_tensor, raw_depth_tensor, confidence_tensor, \
extrinsics_tensor, intrinsics_tensor, processed_tensor = \
[t.squeeze(0) if t is not None else None for t in tensors]
return DA3Prediction(
depth=depth_tensor,
confidence=confidence_tensor,
extrinsics=extrinsics_tensor,
intrinsics=intrinsics_tensor,
processed_images=processed_tensor,
raw_depth=raw_depth_tensor,
supports_pose=self.supports_pose
)
except Exception as e:
logger.error(f"Error in DA3 inference: {e}")
logger.error(traceback.format_exc())
if isinstance(image, Image.Image): w, h = image.size
elif isinstance(image, list) and len(image) > 0: w, h = image[0].size
else: w, h = 512, 512
dummy_depth = torch.ones((h, w), device=self.device, dtype=torch.float32)
return DA3Prediction(depth=dummy_depth, supports_pose=False)
def eval(self):
if hasattr(self.model, 'eval'): self.model.eval()
return self
def to(self, device):
if hasattr(self.model, 'to'): self.model = self.model.to(device)
self.device = device
return self
def get_available_models():
"""
Returns a list of available depth models based on installed dependencies.
DA3 models are only included if depth_anything_v3 package is installed.
"""
available = []
for model_name, model_info in DEPTH_MODELS.items():
model_type = model_info.get("model_type", "v1") if isinstance(model_info, dict) else "v1"
# DA3 models require the depth_anything_v3 package
if model_type == "v3" and not DA3_AVAILABLE:
continue
available.append(model_name)
return available
class DepthEstimationNode:
"""
ComfyUI node for depth estimation using Depth Anything models.
This node provides depth map generation from images using various Depth Anything models
with configurable post-processing options like blur, median filtering, contrast enhancement,
and gamma correction.
"""
MEDIAN_SIZES = ["3", "5", "7", "9", "11"]
def __init__(self):
self.device = None
self.depth_estimator = None
self.current_model = None
logger.info("Initialized DepthEstimationNode")
@classmethod
def INPUT_TYPES(cls) -> Dict[str, Dict[str, Any]]:
"""Define the input types for the node.
Note: DA3 models are only shown if depth_anything_v3 package is installed.
"""
return {
"required": {
"image": ("IMAGE",),
"model_name": (get_available_models(),),
},
"optional": {
"input_size": ("INT", {"default": 1024, "min": 384, "max": 8192, "step": 32}),
"blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}),
"median_size": ("INT", {"default": 0, "min": 0, "max": 21, "step": 2}), # Odd values only, max 21 for PIL
"apply_auto_contrast": ("BOOLEAN", {"default": False}),
"apply_gamma": ("BOOLEAN", {"default": False}),
"force_reload": ("BOOLEAN", {"default": False}),
"force_cpu": ("BOOLEAN", {"default": False}),
"enable_camera_estimation": ("BOOLEAN", {"default": True}),
"output_raw_depth": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = (
"IMAGE",
"IMAGE",
CAMERA_EXTRINSICS,
CAMERA_INTRINSICS,
"STRING"
)
RETURN_NAMES = (
"depth",
"confidence",
"extrinsics",
"intrinsics",
"camera_json"
)
FUNCTION = "estimate_depth"
CATEGORY = "depth"
def cleanup(self) -> None:
"""Clean up resources and free VRAM."""
try:
if self.depth_estimator is not None:
# Save model name before deletion for logging
model_name = self.current_model
# Delete the estimator
del self.depth_estimator
self.depth_estimator = None
self.current_model = None
# Force CUDA cache clearing
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
logger.info(f"Cleaned up model resources for {model_name}")
# Log available memory after cleanup if CUDA is available
if torch.cuda.is_available():
try:
free_mem_info = get_free_memory(get_torch_device())
# Handle return value whether it's a tuple or a single value
if isinstance(free_mem_info, tuple):
free_mem, total_mem = free_mem_info
logger.info(f"Available VRAM after cleanup: {free_mem/1024:.2f}MB of {total_mem/1024:.2f}MB")
else:
logger.info(f"Available VRAM after cleanup: {free_mem_info/1024:.2f}MB")
except Exception as e:
logger.warning(f"Error getting memory info: {e}")
except Exception as e:
logger.warning(f"Error during cleanup: {e}")
logger.debug(traceback.format_exc())
def ensure_model_loaded(self, model_name: str, force_reload: bool = False, force_cpu: bool = False) -> None:
"""
Ensures the correct model is loaded with proper VRAM management and fallback options.
Args:
model_name: The name of the model to load
force_reload: If True, reload the model even if it's already loaded
force_cpu: If True, force loading on CPU regardless of GPU availability
Raises:
RuntimeError: If the model fails to load after all fallback attempts
"""
try:
# Check for valid model name with more helpful fallback
if model_name not in DEPTH_MODELS:
# Find the most similar model name if possible
available_models = list(DEPTH_MODELS.keys())
if len(available_models) > 0:
# First try to find a model with a similar name
model_name_lower = model_name.lower()
# Prioritized fallback selection logic:
# 1. Try to find a model with a similar name
# 2. Prefer V3 models if V3 was requested (and DA3 is available)
# 3. Prefer V2 models if V2 was requested
# 4. Prefer smaller models (more reliable)
if "v3" in model_name_lower and DA3_AVAILABLE:
if "small" in model_name_lower:
fallback_model = "Depth-Anything-V3-Small"
else:
fallback_model = "Depth-Anything-V3-Base"
elif "v2" in model_name_lower and "small" in model_name_lower:
fallback_model = "Depth-Anything-V2-Small"
elif "v2" in model_name_lower and "base" in model_name_lower:
fallback_model = "Depth-Anything-V2-Base"
elif "v2" in model_name_lower:
fallback_model = "Depth-Anything-V2-Small"
elif "small" in model_name_lower:
fallback_model = "Depth-Anything-Small"
elif "midas" in model_name_lower:
fallback_model = "MiDaS-Small"
else:
# Default to the first model if no better match found
fallback_model = available_models[0]
logger.warning(f"Unknown model: {model_name}. Falling back to {fallback_model}")