|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
|
|
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 |
|
} |
|
|