Spaces:
Running on Zero
Running on Zero
Download app.py from chenlin/depth-pro-demo: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/chenlin/depth-pro-demo/resolve/main/app.py
- Command line
-
hf download hf://spaces/chenlin/depth-pro-demo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/chenlin/depth-pro-demo/resolve/main/app.py
14.5 kB
| 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 | |
| # --------------------------------------------------------- | |
| 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( | |
| """ | |
| <div class="hero-header"> | |
| <h1>π Apple Depth Pro: Sharp Monocular Metric Depth</h1> | |
| <p style="font-size: 1.1rem; color: #4b5563;"> | |
| Zero-shot metric depth and camera focal length estimation with boundary-sharp precision in <1 second. | |
| </p> | |
| <p> | |
| <a href="https://huggingface.co/apple/DepthPro-hf" target="_blank">π€ Model Card</a> | | |
| <a href="https://github.com/apple/ml-depth-pro" target="_blank">π» GitHub Code</a> | | |
| <a href="https://arxiv.org/abs/2410.02073" target="_blank">π Paper (arXiv:2410.02073)</a> | |
| </p> | |
| </div> | |
| """ | |
| ) | |
| stored_depth = gr.State() | |
| with gr.Tabs(): | |
| # --- TAB 1: Main Depth Estimation --- | |
| with gr.TabItem("π― Metric Depth & Intrinsics"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| input_img = gr.Image(label="Input Image", type="pil") | |
| with gr.Accordion("βοΈ Visualizer Settings", open=False): | |
| colormap_dropdown = gr.Dropdown( | |
| choices=COLORMAP_CHOICES, | |
| value="Spectral_r", | |
| label="Depth Colormap", | |
| ) | |
| invert_depth_cb = gr.Checkbox( | |
| label="Invert Depth Colors", | |
| value=False, | |
| ) | |
| depth_clip_slider = gr.Slider( | |
| minimum=0.0, | |
| maximum=50.0, | |
| step=0.5, | |
| value=0.0, | |
| label="Max Depth Clip (meters, 0 for unlimited)", | |
| ) | |
| estimate_btn = gr.Button("π Run Depth Pro", variant="primary", size="lg") | |
| with gr.Column(scale=1): | |
| comparison_slider = gr.ImageSlider( | |
| label="Original vs. Metric Depth (Interactive Slider)", | |
| show_label=True, | |
| ) | |
| with gr.Row(): | |
| out_fov = gr.Textbox(label="π Field of View (FoV)", interactive=False) | |
| out_focal = gr.Textbox(label="π· Focal Length", interactive=False) | |
| with gr.Row(): | |
| out_dmin = gr.Textbox(label="π’ Near Distance", interactive=False) | |
| out_dmax = gr.Textbox(label="π΄ Far Distance", interactive=False) | |
| with gr.Row(): | |
| download_file = gr.File(label="πΎ Download 16-bit Metric PNG (Millimeter Scale)") | |
| gr.Markdown("### πΌοΈ Example Images") | |
| example_paths = [] | |
| if os.path.exists("examples/001.png"): | |
| example_paths.append(["examples/001.png", "Spectral_r", False, 0.0]) | |
| if example_paths: | |
| gr.Examples( | |
| examples=example_paths, | |
| inputs=[input_img, colormap_dropdown, invert_depth_cb, depth_clip_slider], | |
| outputs=[ | |
| comparison_slider, | |
| gr.Image(visible=False), | |
| out_fov, | |
| out_focal, | |
| out_dmin, | |
| out_dmax, | |
| download_file, | |
| stored_depth, | |
| ], | |
| fn=estimate_depth, | |
| cache_examples=False, | |
| ) | |
| # --- TAB 2: Synthetic Depth of Field Simulator --- | |
| with gr.TabItem("π· Depth-of-Field Bokeh Simulator"): | |
| gr.Markdown( | |
| """ | |
| ### Optical Bokeh Simulation via Metric Depth | |
| Because **Depth Pro** outputs true metric scale (meters) and sharp object contours, it can simulate realistic optical lens blur (Circle of Confusion) without halo artifacts. | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| focus_slider = gr.Slider( | |
| minimum=0.2, | |
| maximum=15.0, | |
| step=0.1, | |
| value=1.5, | |
| label="Focal Plane Distance (Meters)", | |
| ) | |
| aperture_slider = gr.Slider( | |
| minimum=1.0, | |
| maximum=16.0, | |
| step=0.2, | |
| value=1.8, | |
| label="Aperture (f-stop: lower = shallower focus / creamier bokeh)", | |
| ) | |
| blur_scale_slider = gr.Slider( | |
| minimum=1.0, | |
| maximum=30.0, | |
| step=1.0, | |
| value=10.0, | |
| label="Bokeh Strength", | |
| ) | |
| render_bokeh_btn = gr.Button("β¨ Render Optical Bokeh", variant="primary") | |
| with gr.Column(scale=1): | |
| bokeh_output = gr.Image(label="Simulated Depth-of-Field Result", type="pil") | |
| # --- TAB 3: About & Architecture --- | |
| with gr.TabItem("βΉοΈ About & Citation"): | |
| gr.Markdown( | |
| """ | |
| ### About Apple Depth Pro | |
| **Depth Pro** is a zero-shot metric monocular depth estimation foundation model introduced by Apple ML Research. | |
| #### Key Highlights: | |
| - **Zero-shot Metric Depth**: Computes physical depth in meters without requiring camera calibration or metadata. | |
| - **Ultra-sharp Boundary Details**: Predicts razor-sharp occlusions, resolving hair strands, thin fences, and foliage without blur bleeding. | |
| - **Focal Length & FoV Inversion**: Predicts field of view directly from the input image. | |
| - **Efficiency**: Produces 2.25 megapixel depth maps in approximately 0.3 seconds on modern GPUs. | |
| #### Citation | |
| ```bibtex | |
| @article{Bochkovskii2024:arxiv, | |
| author = {Aleksei Bochkovskii and Ama\"{e}l Delaunoy and Hugo Germain and Marcel Santos and | |
| Yichao Zhou and Stephan R. Richter and Vladlen Koltun}, | |
| title = {Depth Pro: Sharp Monocular Metric Depth in Less Than a Second}, | |
| journal = {arXiv:2410.02073}, | |
| year = {2024} | |
| } | |
| ``` | |
| """ | |
| ) | |
| # Event Handlers | |
| estimate_btn.click( | |
| fn=estimate_depth, | |
| inputs=[input_img, colormap_dropdown, invert_depth_cb, depth_clip_slider], | |
| outputs=[ | |
| comparison_slider, | |
| gr.Image(visible=False), | |
| out_fov, | |
| out_focal, | |
| out_dmin, | |
| out_dmax, | |
| download_file, | |
| stored_depth, | |
| ], | |
| ) | |
| render_bokeh_btn.click( | |
| fn=render_bokeh, | |
| inputs=[input_img, stored_depth, focus_slider, aperture_slider, blur_scale_slider], | |
| outputs=[bokeh_output], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(mcp_server=True) | |