import os import tempfile from typing import Optional, Tuple import spaces import torch import numpy as np import PIL.Image import matplotlib as mpl from scipy.ndimage import gaussian_filter import gradio as gr from transformers import DepthProForDepthEstimation, DepthProImageProcessorFast # --------------------------------------------------------- # Global Setup & Model Loading # --------------------------------------------------------- device = torch.device("cuda" if torch.cuda.is_available() else "cpu") MODEL_ID = "apple/DepthPro-hf" print(f"Loading DepthPro model and image processor from {MODEL_ID} on {device}...") image_processor = DepthProImageProcessorFast.from_pretrained(MODEL_ID) model = DepthProForDepthEstimation.from_pretrained(MODEL_ID).to(device) model.eval() print("DepthPro initialized successfully.") # Cache colormaps COLORMAP_CHOICES = ["Spectral_r", "turbo", "viridis", "plasma", "inferno", "magma"] # --------------------------------------------------------- # Core Depth Inference # --------------------------------------------------------- @spaces.GPU(duration=30) @torch.inference_mode() def estimate_depth( image: PIL.Image.Image, colormap_name: str = "Spectral_r", invert_colormap: bool = False, max_depth_clip: float = 0.0, ) -> Tuple[Tuple[PIL.Image.Image, PIL.Image.Image], PIL.Image.Image, str, str, str, str, str, np.ndarray]: """ Estimate zero-shot metric depth, horizontal field of view, and camera focal length from an RGB image. Args: image: Input RGB image. colormap_name: Matplotlib colormap for visualizing inverse depth. invert_colormap: Invert the depth colormap mapping. max_depth_clip: Maximum depth threshold in meters (0 for no clipping). Returns: A tuple of: - ImageSlider pair: (Original Image, Colored Depth Map) - Colored Depth Map PIL Image - Horizontal Field of View string - Estimated Focal Length string - Minimum Depth in meters - Maximum Depth in meters - Path to exported 16-bit PNG depth map (mm scale) - Raw depth numpy array in meters (stored in Gradio state) """ if image is None: raise gr.Error("Please upload or select an input image first.") orig_w, orig_h = image.size # Prepare inputs inputs = image_processor(images=image, return_tensors="pt").to(device) outputs = model(**inputs) # Post-process to restore exact input dimensions post_processed = image_processor.post_process_depth_estimation( outputs, target_sizes=[(orig_h, orig_w)], )[0] predicted_depth = post_processed["predicted_depth"].squeeze().detach().cpu().numpy() fov_deg = float(post_processed["field_of_view"].item()) focal_length_px = float(post_processed["focal_length"].item()) min_m = float(np.nanmin(predicted_depth)) max_m = float(np.nanmax(predicted_depth)) # Apply clipping if requested proc_depth = predicted_depth.copy() if max_depth_clip > 0.0: proc_depth = np.clip(proc_depth, 0.0, max_depth_clip) # Convert to disparity / inverse depth for high-frequency perceptual visualization inv_depth = 1.0 / np.clip(proc_depth, 1e-4, 1e4) inv_min, inv_max = np.nanmin(inv_depth), np.nanmax(inv_depth) if inv_max > inv_min: norm_inv = (inv_depth - inv_min) / (inv_max - inv_min) else: norm_inv = np.zeros_like(inv_depth) if invert_colormap: norm_inv = 1.0 - norm_inv # Render colored depth visualization cmap = mpl.colormaps.get(colormap_name, mpl.colormaps["Spectral_r"]) colored_np = (cmap(norm_inv)[:, :, :3] * 255.0).astype(np.uint8) colored_pil = PIL.Image.fromarray(colored_np) # Export 16-bit PNG depth in millimeters depth_mm = np.clip(predicted_depth * 1000.0, 0, 65535).astype(np.uint16) tmp_dir = tempfile.gettempdir() depth_png_path = os.path.join(tmp_dir, "depth_metric_16bit.png") PIL.Image.fromarray(depth_mm).save(depth_png_path) return ( (image, colored_pil), colored_pil, f"{fov_deg:.2f}°", f"{focal_length_px:.1f} px", f"{min_m:.2f} m", f"{max_m:.2f} m", depth_png_path, predicted_depth, ) # --------------------------------------------------------- # Synthetic Bokeh (Depth-of-Field) Simulation # --------------------------------------------------------- def render_bokeh( image: PIL.Image.Image, depth_array: Optional[np.ndarray], focal_distance_m: float, aperture_f_stop: float, blur_scale: float, ) -> PIL.Image.Image: """ Simulate realistic optical depth-of-field blur using metric depth estimates. Args: image: Original RGB image. depth_array: 2D numpy array of estimated metric depths in meters. focal_distance_m: In-focus distance in meters. aperture_f_stop: Lens aperture f-number (lower = shallower DoF / larger blur). blur_scale: Scaling factor for circle-of-confusion kernel radius. Returns: Rendered image with synthetic optical bokeh. """ if image is None: raise gr.Error("Please run depth estimation on an image first.") if depth_array is None: raise gr.Error("Depth data is not available. Please run 'Estimate Depth' first.") img_np = np.array(image).astype(np.float32) / 255.0 h, w, _ = img_np.shape # Physical circle-of-confusion (CoC) radius model: # CoC ~ |depth - focal_depth| / depth * (1 / aperture) depth_safe = np.clip(depth_array, 0.1, 100.0) coc_radius = np.abs(depth_safe - focal_distance_m) / depth_safe coc_radius = (coc_radius / max(aperture_f_stop, 0.5)) * blur_scale max_radius = min(30.0, max(w, h) * 0.05) coc_radius = np.clip(coc_radius, 0.0, max_radius) # Fast multi-plane layer blur approximation num_layers = 5 radii_bins = np.linspace(0.0, max_radius, num_layers + 1) accum_img = np.zeros_like(img_np) accum_weight = np.zeros((h, w, 1), dtype=np.float32) for i in range(num_layers): r_low, r_high = radii_bins[i], radii_bins[i + 1] sigma = (r_low + r_high) / 4.0 mask = (coc_radius >= r_low) & (coc_radius <= r_high) if not np.any(mask): continue weight = mask.astype(np.float32)[:, :, None] if sigma > 0.5: blurred_plane = gaussian_filter(img_np, sigma=(sigma, sigma, 0)) else: blurred_plane = img_np accum_img += blurred_plane * weight accum_weight += weight accum_weight = np.maximum(accum_weight, 1e-4) rendered_np = np.clip((accum_img / accum_weight) * 255.0, 0, 255).astype(np.uint8) return PIL.Image.fromarray(rendered_np) # --------------------------------------------------------- # Gradio UI Layout # --------------------------------------------------------- css = """ #metric-box { font-size: 1.15rem; font-weight: 600; } .hero-header { text-align: center; margin-bottom: 1.5rem; } """ with gr.Blocks(title="Apple Depth Pro Demo", css=css, theme=gr.themes.Soft()) as demo: gr.HTML( """
Zero-shot metric depth and camera focal length estimation with boundary-sharp precision in <1 second.
đ¤ Model Card | đģ GitHub Code | đ Paper (arXiv:2410.02073)