This should be headless. import torch
import cv2
import numpy as np
import sys
import os
def generate_depth_map(input_image_path, output_depth_path):
# Load MiDaS model
model_type = "DPT_Large" # Other options: "DPT_Hybrid", "MiDaS_small"
midas = torch.hub.load("intel-isl/MiDaS", model_type)
code
# Move model to device (GPU if available)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
midas.to(device)
midas.eval()
# Load transforms to resize and normalize the image
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if model_type == "DPT_Large" or model_type == "DPT_Hybrid":
transform = midas_transforms.dpt_transform
else:
transform = midas_transforms.small_transform
# Load and preprocess the image
img = cv2.imread(input_image_path)
if img is None:
print(f"Could not read input image {input_image_path}")
sys.exit(1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
input_batch = transform(img).to(device)
# Perform inference to get depth estimation
with torch.no_grad():
prediction = midas(input_batch)
# Upsample to original image resolution
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
# Convert to NumPy array and normalize
depth_map = prediction.cpu().numpy()
depth_min = depth_map.min()
depth_max = depth_map.max()
depth_map_normalized = (depth_map - depth_min) / (depth_max - depth_min)
depth_map_8bit = (depth_map_normalized * 255).astype(np.uint8)
# Save depth map
cv2.imwrite(output_depth_path, depth_map_8bit)
print(f"Depth map saved to {output_depth_path}")
Assistant
if name == "main":
import argparse
code
parser = argparse.ArgumentParser(description="Generate a depth map for Facebook 3D Photo.")
parser.add_argument("input_image", help="Path to input RGB image")
args = parser.parse_args()
input_image_path = args.input_image
base_name, ext = os.path.splitext(input_image_path)
output_depth_path = f"{base_name}_depth{ext}"
generate_depth_map(input_image_path, output_depth_path)
To run your script in a headless environment (one without a graphical display), you need to ensure that you're using the headless version of OpenCV. The standard opencv-python package depends on GUI libraries that may not be available in environments without a display server, leading to errors when running the script.
Here's how you can modify your setup to run the script headlessly:
Uninstall the standard OpenCV package if you have it installed:
bash
pip uninstall opencv-python
Install the headless version of OpenCV:
bash
pip install opencv-python-headless
The opencv-python-headless package is designed for server environments and does not include any GUI dependencies, ensuring that functions like cv2.imread and cv2.imwrite work without requiring a display.
Ensure your script doesn't use any GUI functions like cv2.imshow, cv2.waitKey, or cv2.destroyAllWindows. From your script, it appears you're only using cv2.imread and cv2.imwrite, which are safe to use in a headless environment.
Here's your script, which should now work in a headless setup:
python
import torch
import cv2
import numpy as np
import sys
import os
def generate_depth_map(input_image_path, output_depth_path):
# Load MiDaS model
model_type = "DPT_Large" # Other options: "DPT_Hybrid", "MiDaS_small"
midas = torch.hub.load("intel-isl/MiDaS", model_type)
# Move model to device (GPU if available)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
midas.to(device)
midas.eval()
# Load transforms to resize and normalize the image
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if model_type == "DPT_Large" or model_type == "DPT_Hybrid":
transform = midas_transforms.dpt_transform
else:
transform = midas_transforms.small_transform
# Load and preprocess the image
img = cv2.imread(input_image_path)
if img is None:
print(f"Could not read input image {input_image_path}")
sys.exit(1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
input_batch = transform(img).to(device)
# Perform inference to get depth estimation
with torch.no_grad():
prediction = midas(input_batch)
# Upsample to original image resolution
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
# Convert to NumPy array and normalize
depth_map = prediction.cpu().numpy()
depth_min = depth_map.min()
depth_max = depth_map.max()
depth_map_normalized = (depth_map - depth_min) / (depth_max - depth_min)
depth_map_8bit = (depth_map_normalized * 255).astype(np.uint8)
# Save depth map
cv2.imwrite(output_depth_path, depth_map_8bit)
print(f"Depth map saved to {output_depth_path}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate a depth map for Facebook 3D Photo.")
parser.add_argument("input_image", help="Path to input RGB image")
args = parser.parse_args()
input_image_path = args.input_image
base_name, ext = os.path.splitext(input_image_path)
output_depth_path = f"{base_name}_depth{ext}"
generate_depth_map(input_image_path, output_depth_path)