diff --git a/depth_estimators/__init__.py b/depth_estimators/__init__.py new file mode 100644 index 0000000..cf10e9c --- /dev/null +++ b/depth_estimators/__init__.py @@ -0,0 +1 @@ +from .apple_depth_pro import AppleDepthPro diff --git a/depth_estimators/apple_depth_pro.py b/depth_estimators/apple_depth_pro.py new file mode 100644 index 0000000..4edfb17 --- /dev/null +++ b/depth_estimators/apple_depth_pro.py @@ -0,0 +1,62 @@ +import time +import subprocess +from pathlib import Path +import tempfile +import torch +import depth_pro +import numpy as np +from PIL import Image + + +class AppleDepthPro: + def __init__(self): + self.model = None + self.transform = None + self.device = None + + def load_model(self): + if self.model is not None: + return + + self.model, self.transform = depth_pro.create_model_and_transforms() + self.model.eval() + + self.device = torch.device("cpu") + + def process_video(self, video_path: str, output_dir: str): + self.load_model() + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + with tempfile.TemporaryDirectory() as tmpdir: + frames_dir = Path(tmpdir) / "frames" + frames_dir.mkdir() + + cmd = ["ffmpeg", "-i", video_path, f"{frames_dir}/frame_%04d.png"] + subprocess.run(cmd, capture_output=True, check=True) + + frames = sorted(frames_dir.glob("frame_*.png")) + frame_times = [] + + for frame in frames: + output = output_dir / f"depth_{frame.name}" + + image, _, f_px = depth_pro.load_rgb(str(frame)) + image = self.transform(image) + + start = time.time() + with torch.no_grad(): + prediction = self.model.infer(image, f_px=f_px) + frame_times.append(time.time() - start) + + depth = prediction["depth"].cpu().numpy() + depth_normalized = ((depth - depth.min()) / (depth.max() - depth.min()) * 255).astype(np.uint8) + Image.fromarray(depth_normalized).save(output) + + total_time = sum(frame_times) + return { + "frames_processed": len(frame_times), + "total_time": total_time, + "avg_time_per_frame": total_time / len(frame_times), + "device": str(self.device) + } diff --git a/scripts/depth_pro.py b/scripts/depth_pro.py new file mode 100644 index 0000000..8b1be79 --- /dev/null +++ b/scripts/depth_pro.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +import time +import json +import sys +from pathlib import Path +import torch +from PIL import Image +from huggingface_hub import hf_hub_download +import numpy as np + + +def load_model(): + model_path = hf_hub_download(repo_id="apple/DepthPro", filename="depth_pro.pt") + model = torch.jit.load(model_path) + + if torch.backends.mps.is_available(): + device = torch.device("mps") + else: + device = torch.device("cpu") + + model = model.to(device) + model.eval() + return model, device + + +def estimate_depth(image_path: str, output_path: str = None): + if output_path is None: + p = Path(image_path) + output_path = f"{p.stem}_depth.png" + + model, device = load_model() + + img = Image.open(image_path).convert('RGB') + img_tensor = torch.from_numpy(np.array(img)).permute(2, 0, 1).unsqueeze(0).float() / 255.0 + img_tensor = img_tensor.to(device) + + start = time.time() + with torch.no_grad(): + depth = model(img_tensor) + inference_time = time.time() - start + + depth_np = depth.squeeze().cpu().numpy() + depth_normalized = ((depth_np - depth_np.min()) / (depth_np.max() - depth_np.min()) * 255).astype(np.uint8) + Image.fromarray(depth_normalized).save(output_path) + + stats = { + "input": image_path, + "output": output_path, + "inference_time": round(inference_time, 3), + "device": str(device) + } + + return stats + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: python depth_pro.py [output_depth]") + sys.exit(1) + + output = sys.argv[2] if len(sys.argv) > 2 else None + stats = estimate_depth(sys.argv[1], output) + + print(json.dumps(stats, indent=2))