File size: 3,430 Bytes
37d34c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# By WASasquatch ( Discord: WAS#0263 | https://civitai.com/user/WAS )

import torch, time, sys, subprocess
import numpy as np
from PIL import Image, ImageFilter
import torchvision.transforms as transforms

MIDAS_INSTALLED = False

class MiDaS_Depth_Approx:
    def __init__(self):
        pass

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "image": ("IMAGE",),
                "use_cpu": (["false", "true"],),
                "midas_model": (["DPT_Large", "DPT_Hybrid", "DPT_Small"],),
                "invert_depth": (["false", "true"],),
            },
        }

    RETURN_TYPES = ("IMAGE",)
    FUNCTION = "midas_approx"
    CATEGORY = "WAS"

    def midas_approx(self, image, use_cpu, midas_model, invert_depth):
    
        global MIDAS_INSTALLED
 
        if not MIDAS_INSTALLED:
            self.install_midas()
            
        import cv2 as cv
    
        # Convert the input image tensor to a PIL Image
        i = 255. * image.cpu().numpy().squeeze()
        img = i

        print("Downloading and loading MiDaS Model...")
        midas = torch.hub.load("intel-isl/MiDaS", midas_model, trust_repo=True)
        device = torch.device("cuda") if torch.cuda.is_available() and use_cpu == 'false' else torch.device("cpu")
        
        print('MiDaS is using device:', device)

        midas.to(device).eval()
        midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")

        if midas_model == "DPT_Large" or midas_model == "DPT_Hybrid":
            transform = midas_transforms.dpt_transform
        else:
            transform = midas_transforms.small_transform

        img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        input_batch = transform(img).to(device)
        
        print('Approximating depth from image...')

        with torch.no_grad():
            prediction = midas(input_batch)
            prediction = torch.nn.functional.interpolate(
                prediction.unsqueeze(1),
                size=img.shape[:2],
                mode="bicubic",
                align_corners=False,
            ).squeeze()

        if invert_depth == 'true':
            depth = ( 255 - prediction.cpu().numpy().astype(np.uint8) )
            depth = depth.astype(np.float32)
        else:
            depth = prediction.cpu().numpy().astype(np.float32)
        depth = depth * 255 / (np.max(depth)) / 255
        # Invert depth map
        depth = cv.cvtColor(depth, cv.COLOR_GRAY2RGB)
        
        tensor = torch.from_numpy( depth )[None,]
        tensors = ( tensor, )

        del midas, device, midas_transforms
        del transform, img, input_batch, prediction
        
        return  tensors
        
    def install_midas(self):
        global MIDAS_INSTALLED
        if 'timm' not in self.packages():
            print("Installing timm...")
            subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'timm'])
        if 'opencv-python' not in self.packages():
            print("Installing CV2...")
            subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
        MIDAS_INSTALLED = True
        
    def packages(self):
        import sys, subprocess
        return [r.decode().split('==')[0] for r in subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).split()]

NODE_CLASS_MAPPINGS = {
    "MiDaS Depth Approximation": MiDaS_Depth_Approx
}