How would I use MiDaS, a model aimed to estimate depth in a monocular setting. Write the…
- User
How would I use MiDaS, a model aimed to estimate depth in a monocular setting. Write the necessary code
Assistant
Here is some Python code to use the MiDaS depth estimation model:
import torch import cv2 from midas.midas_net import MidasNet from midas.midas_net_custom import MidasNet_small # Load the pretrained MiDaS model model_type = "DPT_Large" # MiDaS v3 - Large (highest accuracy, slowest inference speed) #model_type = "DPT_Hybrid" # MiDaS v3 - Hybrid (medium accuracy, medium inference speed) #model_type = "MiDaS_small" # MiDaS v2.1 - Small (lowest accuracy, highest inference speed) midas = torch.hub.load("intel-isl/MiDaS", model_type) midas.eval() midas.cuda() # Load input image img = cv2.imread("input_image.jpg") input_batch = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Inference with torch.no_grad(): input_batch = torch.from_numpy(input_batch).permute(2, 0, 1).float().unsqueeze(0).cuda() output = midas(input_batch) output = torch.nn.functional.interpolate(output.unsqueeze(1),size=img.shape[:2], mode="bicubic", align_corners=False).squeeze().cpu().numpy() # Display/save depth image depth_img = (output*255).astype("uint8") cv2.imwrite("depth.png", depth_img)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.