diff --git a/docs/foundation/depth_estimation.md b/docs/foundation/depth_estimation.md new file mode 100644 index 0000000000..06773c2c04 --- /dev/null +++ b/docs/foundation/depth_estimation.md @@ -0,0 +1,92 @@ +Depth-Anything-V2-Small is a depth estimation model developed by Hugging Face. + +You can use Depth-Anything-V2-Small to estimate the depth of objects in images, creating a depth map where: +- Each pixel's value represents its relative distance from the camera +- Lower values (darker colors) indicate closer objects +- Higher values (lighter colors) indicate further objects + +You can deploy Depth-Anything-V2-Small with Inference. + +### Installation + +To install inference with the extra dependencies necessary to run Depth-Anything-V2-Small, run + +```pip install inference[transformers]``` + +or + +```pip install inference-gpu[transformers]``` + +### How to Use Depth-Anything-V2-Small + +Create a new Python file called `app.py` and add the following code: + +```python +from PIL import Image +import matplotlib.pyplot as plt +import numpy as np + +from inference.models.depth_estimation.depthestimation import DepthEstimator + +# Initialize the model +model = DepthEstimator() + +# Load an image +image = Image.open("your_image.jpg") + +# Run inference +results = model.predict(image) + +# Get the depth map and visualization +depth_map = results[0]['normalized_depth'] +visualization = results[0]['image'] + +# Convert visualization to numpy array for display +visualization_array = visualization.numpy() + +# Display the results +plt.figure(figsize=(12, 6)) +plt.subplot(1, 2, 1) +plt.imshow(image) +plt.title('Original Image') +plt.axis('off') + +plt.subplot(1, 2, 2) +plt.imshow(visualization_array) +plt.title('Depth Map') +plt.axis('off') + +plt.show() +``` + +In this code, we: +1. Load the Depth-Anything-V2-Small model +2. Load an image for depth estimation +3. Run inference to get the depth map +4. Display both the original image and the depth map visualization + +The depth map visualization uses a viridis colormap where: +- Darker colors (purple/blue) represent objects closer to the camera +- Lighter colors (yellow/green) represent objects further from the camera + +To use Depth-Anything-V2-Small with Inference, you will need a Hugging Face token. If you don't already have a Hugging Face account, sign up for a free Hugging Face account. + +Then, set your Hugging Face token as an environment variable: + +```bash +export HUGGING_FACE_HUB_TOKEN=your_token_here +``` + +Or you can log in using the Hugging Face CLI: + +```bash +huggingface-cli login +``` + +Then, run the Python script you have created: + +```bash +python app.py +``` + +The script will display both the original image and the depth map visualization. diff --git a/inference/core/entities/requests/inference.py b/inference/core/entities/requests/inference.py index 4ea3129c7c..fb204ffec4 100644 --- a/inference/core/entities/requests/inference.py +++ b/inference/core/entities/requests/inference.py @@ -89,6 +89,22 @@ class CVInferenceRequest(InferenceRequest): ) +class DepthEstimationRequest(BaseRequest): + """Request for depth estimation. + + Attributes: + image (Union[List[InferenceRequestImage], InferenceRequestImage]): Image(s) to be estimated. + """ + + image: Union[List[InferenceRequestImage], InferenceRequestImage] + + visualize_predictions: Optional[bool] = Field( + default=False, + examples=[False], + description="If true, the predictions will be drawn on the original image and returned as a base64 string", + ) + + class ObjectDetectionInferenceRequest(CVInferenceRequest): """Object Detection inference request. diff --git a/inference/core/env.py b/inference/core/env.py index 9ce3a8415f..1b8738214d 100644 --- a/inference/core/env.py +++ b/inference/core/env.py @@ -149,6 +149,8 @@ QWEN_2_5_ENABLED = str2bool(os.getenv("QWEN_2_5_ENABLED", True)) +DEPTH_ESTIMATION_ENABLED = str2bool(os.getenv("DEPTH_ESTIMATION_ENABLED", True)) + SMOLVLM2_ENABLED = str2bool(os.getenv("SMOLVLM2_ENABLED", True)) MOONDREAM2_ENABLED = str2bool(os.getenv("MOONDREAM2_ENABLED", True)) diff --git a/inference/core/managers/base.py b/inference/core/managers/base.py index d06258622f..a962c97db8 100644 --- a/inference/core/managers/base.py +++ b/inference/core/managers/base.py @@ -57,14 +57,18 @@ def add_model( f"ModelManager - model with model_id={resolved_identifier} is already loaded." ) return + logger.debug("ModelManager - model initialisation...") - model = self.model_registry.get_model(resolved_identifier, api_key)( - model_id=model_id, - api_key=api_key, - ) - logger.debug("ModelManager - model successfully loaded.") - self._models[resolved_identifier] = model + try: + model = self.model_registry.get_model(resolved_identifier, api_key)( + model_id=model_id, + api_key=api_key, + ) + logger.debug("ModelManager - model successfully loaded.") + self._models[resolved_identifier] = model + except Exception as e: + raise def check_for_model(self, model_id: str) -> None: """Checks whether the model with the given ID is in the manager. diff --git a/inference/core/registries/roboflow.py b/inference/core/registries/roboflow.py index 1f1957442a..9b592703d2 100644 --- a/inference/core/registries/roboflow.py +++ b/inference/core/registries/roboflow.py @@ -55,6 +55,7 @@ "yolo_world": ("object-detection", "yolo-world"), "owlv2": ("object-detection", "owlv2"), "smolvlm2": ("lmm", "smolvlm-2.2b-instruct"), + "depth-anything-v2": ("depth-estimation", "small"), "moondream2": ("lmm", "moondream2"), } diff --git a/inference/core/utils/roboflow.py b/inference/core/utils/roboflow.py index a295503e5a..5cfb23dcaf 100644 --- a/inference/core/utils/roboflow.py +++ b/inference/core/utils/roboflow.py @@ -10,7 +10,9 @@ def get_model_id_chunks( model_id_chunks = model_id.split("/") if len(model_id_chunks) != 2: raise InvalidModelIDError(f"Model ID: `{model_id}` is invalid.") + dataset_id, version_id = model_id_chunks[0], model_id_chunks[1] + if dataset_id.lower() in { "clip", "doctr", @@ -25,9 +27,11 @@ def get_model_id_chunks( "yolo_world", "smolvlm2", "moondream2", + "depth-anything-v2", }: return dataset_id, version_id + try: return dataset_id, str(int(version_id)) - except Exception: + except Exception as e: return model_id, None diff --git a/inference/core/workflows/core_steps/loader.py b/inference/core/workflows/core_steps/loader.py index 40f7794c8d..4ef0dd0e42 100644 --- a/inference/core/workflows/core_steps/loader.py +++ b/inference/core/workflows/core_steps/loader.py @@ -167,6 +167,9 @@ from inference.core.workflows.core_steps.models.foundation.cog_vlm.v1 import ( CogVLMBlockV1, ) +from inference.core.workflows.core_steps.models.foundation.depth_estimation.v1 import ( + DepthEstimationBlockV1, +) from inference.core.workflows.core_steps.models.foundation.florence2.v1 import ( Florence2BlockV1, ) @@ -515,6 +518,7 @@ def load_blocks() -> List[Type[WorkflowBlock]]: DynamicCropBlockV1, DetectionsFilterBlockV1, DetectionOffsetBlockV1, + DepthEstimationBlockV1, ByteTrackerBlockV1, RelativeStaticCropBlockV1, DetectionsTransformationBlockV1, diff --git a/inference/core/workflows/core_steps/models/foundation/depth_estimation/__init__.py b/inference/core/workflows/core_steps/models/foundation/depth_estimation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/inference/core/workflows/core_steps/models/foundation/depth_estimation/v1.py b/inference/core/workflows/core_steps/models/foundation/depth_estimation/v1.py new file mode 100644 index 0000000000..a2ef4a976a --- /dev/null +++ b/inference/core/workflows/core_steps/models/foundation/depth_estimation/v1.py @@ -0,0 +1,172 @@ +from typing import List, Literal, Optional, Type, Union + +from pydantic import ConfigDict, Field + +from inference.core.entities.requests.inference import DepthEstimationRequest +from inference.core.managers.base import ModelManager +from inference.core.workflows.core_steps.common.entities import StepExecutionMode +from inference.core.workflows.execution_engine.entities.base import ( + Batch, + OutputDefinition, + WorkflowImageData, +) +from inference.core.workflows.execution_engine.entities.types import ( + IMAGE_KIND, + NUMPY_ARRAY_KIND, + ROBOFLOW_MODEL_ID_KIND, + ImageInputField, + RoboflowModelField, + Selector, +) +from inference.core.workflows.prototypes.block import ( + BlockResult, + WorkflowBlock, + WorkflowBlockManifest, +) + + +class BlockManifest(WorkflowBlockManifest): + # Standard model configuration for UI, schema, etc. + model_config = ConfigDict( + json_schema_extra={ + "name": "Depth Estimation", + "version": "v1", + "short_description": "Run Depth Estimation on an image.", + "long_description": ( + """ + 🎯 This workflow block performs depth estimation on images using Apple's DepthPro model. It analyzes the spatial relationships + and depth information in images to create a depth map where: + + πŸ“Š Each pixel's value represents its relative distance from the camera + πŸ” Lower values (darker colors) indicate closer objects + πŸ”­ Higher values (lighter colors) indicate further objects + + The model outputs: + 1. πŸ—ΊοΈ A depth map showing the relative distances of objects in the scene + 2. πŸ“ The camera's field of view (in degrees) + 3. πŸ”¬ The camera's focal length + + This is particularly useful for: + - πŸ—οΈ Understanding 3D structure from 2D images + - 🎨 Creating depth-aware visualizations + - πŸ“ Analyzing spatial relationships in scenes + - πŸ•ΆοΈ Applications in augmented reality and 3D reconstruction + + ⚑ The model runs efficiently on Apple Silicon (M1-M4) using Metal Performance Shaders (MPS) for accelerated inference. + """ + ), + "license": "Apache-2.0", + "block_type": "model", + "search_keywords": [ + "Depth Estimation", + "Depth Anything", + "Depth Anything V2", + "Hugging Face", + "HuggingFace", + ], + "is_vlm_block": True, + "ui_manifest": { + "section": "model", + "icon": "fal fa-atom", + "blockPriority": 5.5, + }, + }, + protected_namespaces=(), + ) + type: Literal["roboflow_core/depth_estimation@v1"] + images: Selector(kind=[IMAGE_KIND]) = ImageInputField + + model_version: str = Field( + default="depth-anything-v2/small", + description="The Depth Estimation model to be used for inference.", + examples=["depth-anything-v2/small"], + ) + + @classmethod + def describe_outputs(cls) -> List[OutputDefinition]: + return [ + OutputDefinition(name="image", kind=[IMAGE_KIND]), + OutputDefinition(name="normalized_depth", kind=[NUMPY_ARRAY_KIND]), + ] + + @classmethod + def get_parameters_accepting_batches(cls) -> List[str]: + # Only images can be passed in as a list/batch + return ["images"] + + @classmethod + def get_execution_engine_compatibility(cls) -> Optional[str]: + return ">=1.3.0,<2.0.0" + + +class DepthEstimationBlockV1(WorkflowBlock): + def __init__( + self, + model_manager: ModelManager, + api_key: Optional[str], + step_execution_mode: StepExecutionMode, + ): + self._model_manager = model_manager + self._api_key = api_key + self._step_execution_mode = step_execution_mode + + @classmethod + def get_init_parameters(cls) -> List[str]: + return ["model_manager", "api_key", "step_execution_mode"] + + @classmethod + def get_manifest(cls) -> Type[WorkflowBlockManifest]: + return BlockManifest + + def run( + self, + images: Batch[WorkflowImageData], + model_version: str = "depth-anything-v2/small", + ) -> BlockResult: + if self._step_execution_mode == StepExecutionMode.LOCAL: + return self.run_locally( + images=images, + model_version=model_version, + ) + elif self._step_execution_mode == StepExecutionMode.REMOTE: + raise NotImplementedError( + "Remote execution is not supported for Depth Estimation. Please use a local or dedicated inference server." + ) + else: + raise ValueError( + f"Unknown step execution mode: {self._step_execution_mode}" + ) + + def run_locally( + self, + images: Batch[WorkflowImageData], + model_version: str = "depth-anything-v2/small", + ) -> BlockResult: + # Convert each image to the format required by the model. + inference_images = [ + i.to_inference_format(numpy_preferred=False) for i in images + ] + + # Register Depth Estimation with the model manager. + try: + self._model_manager.add_model(model_id=model_version, api_key=self._api_key) + except Exception as e: + raise + + predictions = [] + for idx, image in enumerate(inference_images): + # Run inference. + request = DepthEstimationRequest( + image=image, + ) + + try: + prediction = self._model_manager.infer_from_request_sync( + model_id=model_version, request=request + ) + response_text = prediction.response + predictions.append(response_text) + except Exception as e: + raise + + return predictions diff --git a/inference/models/README.md b/inference/models/README.md index 70050bdb20..2762059b2f 100644 --- a/inference/models/README.md +++ b/inference/models/README.md @@ -27,6 +27,7 @@ The models supported by Roboflow Inference have their own licenses. View the lic | `inference/models/yolov11` | [AGPL-3.0](https://github.com/ultralytics/ultralytics/blob/master/LICENSE) | βœ… | | `inference/models/yolov12` | [AGPL-3.0](https://github.com/sunsmarterjie/yolov12?tab=AGPL-3.0-1-ov-file) | βœ… | | `inference/models/smolvlm2` | [Apache 2.0](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct) | πŸ‘ | +| `inference/models/depth_estimation` | [Apache 2.0](https://huggingface.co/depth-anything/Depth-Anything-V2-Small) | πŸ‘ | | `inference/models/rfdetr` | [Apache 2.0](https://github.com/roboflow/rf-detr/blob/main/LICENSE) | πŸ‘ | | `inference/models/moondream2` | [Apache 2.0](https://github.com/vikhyat/moondream/blob/main/LICENSE) | πŸ‘ | diff --git a/inference/models/depth_estimation/LICENSE.txt b/inference/models/depth_estimation/LICENSE.txt new file mode 100644 index 0000000000..f1c9ac9473 --- /dev/null +++ b/inference/models/depth_estimation/LICENSE.txt @@ -0,0 +1,63 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. \ No newline at end of file diff --git a/inference/models/depth_estimation/__init__.py b/inference/models/depth_estimation/__init__.py new file mode 100644 index 0000000000..a37f2f92d6 --- /dev/null +++ b/inference/models/depth_estimation/__init__.py @@ -0,0 +1 @@ +from inference.models.smolvlm.smolvlm import SmolVLM diff --git a/inference/models/depth_estimation/depthestimation.py b/inference/models/depth_estimation/depthestimation.py new file mode 100644 index 0000000000..d3a8ea720d --- /dev/null +++ b/inference/models/depth_estimation/depthestimation.py @@ -0,0 +1,110 @@ +import os +import time +import warnings +from uuid import uuid4 + +import matplotlib.pyplot as plt +import numpy as np +import psutil +import torch +from PIL import Image +from transformers import ( + AutoImageProcessor, + AutoModelForDepthEstimation, + DepthProForDepthEstimation, + DepthProImageProcessorFast, +) + +# Convert numpy array to WorkflowImageData +from inference.core.workflows.execution_engine.entities.base import ( + ImageParentMetadata, + WorkflowImageData, +) +from inference.models.transformers import TransformerModel + + +class DepthEstimator(TransformerModel): + transformers_class = AutoModelForDepthEstimation + processor_class = AutoImageProcessor + load_base_from_roboflow = True + needs_hf_token = False + version_id = None + default_dtype = torch.bfloat16 + load_weights_as_transformers = True + endpoint = "depth-anything-v2/small" + task_type = "depth-estimation" + + def __init__(self, *args, **kwargs): + + try: + super().__init__(*args, **kwargs) + except Exception as e: + print(f"Error initializing depth estimation model: {str(e)}") + raise + + # Set appropriate dtype based on device + if self.model.device.type == "mps": + self.model = self.model.to(torch.float32) # MPS prefers float32 + elif self.model.device.type == "cpu": + warnings.warn( + "Running DepthPro on CPU. This may be very slow. Consider using GPU or MPS if available." + ) + + def predict(self, image_in: Image.Image, prompt="", history=None, **kwargs): + try: + # Process input image + inputs = self.processor(images=image_in, return_tensors="pt") + + # Move inputs to device + device = self.model.device + if device.type == "mps": + inputs = { + k: v.to(torch.float32).to(device) if torch.is_tensor(v) else v + for k, v in inputs.items() + } + else: + inputs = { + k: v.to(device) if torch.is_tensor(v) else v + for k, v in inputs.items() + } + + # Run model inference + with torch.inference_mode(): + outputs = self.model(**inputs) + + # Post-process depth estimation + post_processed_outputs = self.processor.post_process_depth_estimation( + outputs, target_sizes=[(image_in.height, image_in.width)] + ) + + # Extract depth map + depth_map = post_processed_outputs[0]["predicted_depth"] + depth_map = depth_map.to(torch.float32).cpu().numpy() + + # Normalize depth values + depth_min = depth_map.min() + depth_max = depth_map.max() + if depth_max == depth_min: + raise ValueError("Depth map has no variation (min equals max)") + normalized_depth = (depth_map - depth_min) / (depth_max - depth_min) + + # Create visualization + depth_for_viz = (normalized_depth * 255.0).astype(np.uint8) + cmap = plt.get_cmap("viridis") + colored_depth = (cmap(depth_for_viz)[:, :, :3] * 255).astype(np.uint8) + + # Convert numpy array to WorkflowImageData + parent_metadata = ImageParentMetadata(parent_id=f"{uuid4()}") + colored_depth_image = WorkflowImageData( + numpy_image=colored_depth, parent_metadata=parent_metadata + ) + + # Create result dictionary + result = { + "normalized_depth": normalized_depth, + "image": colored_depth_image, + } + + return (result,) + except Exception as e: + raise diff --git a/inference/models/utils.py b/inference/models/utils.py index 1d75f8f695..9823cb5f9b 100644 --- a/inference/models/utils.py +++ b/inference/models/utils.py @@ -3,6 +3,7 @@ from inference.core.env import ( API_KEY, API_KEY_ENV_NAMES, + DEPTH_ESTIMATION_ENABLED, MOONDREAM2_ENABLED, QWEN_2_5_ENABLED, SMOLVLM2_ENABLED, @@ -36,6 +37,7 @@ YOLOv11ObjectDetection, YOLOv12ObjectDetection, ) +from inference.models.depth_estimation.depthestimation import DepthEstimator from inference.models.yolov8.yolov8_keypoints_detection import YOLOv8KeypointsDetection from inference.models.yolov11.yolov11_keypoints_detection import ( YOLOv11KeypointsDetection, @@ -342,6 +344,7 @@ category=ModelDependencyMissing, ) + try: from inference.models import SegmentAnything @@ -409,6 +412,20 @@ category=ModelDependencyMissing, ) + +try: + if DEPTH_ESTIMATION_ENABLED: + from inference.models.depth_estimation.depthestimation import DepthEstimator + + ROBOFLOW_MODEL_TYPES[("depth-estimation", "small")] = DepthEstimator +except: + warnings.warn( + f"Your `inference` configuration does not support Depth Estimation." + f"Use pip install 'inference[transformers]' to install missing requirements.", + category=ModelDependencyMissing, + ) + + try: if MOONDREAM2_ENABLED: from inference.models.moondream2.moondream2 import Moondream2 diff --git a/mkdocs.yml b/mkdocs.yml index 097db334f9..e2e2c6f406 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -103,6 +103,7 @@ nav: - foundation/about.md - CLIP (Classification, Embeddings): foundation/clip.md - DocTR (OCR): foundation/doctr.md + - Depth Estimation (Depth Anything V2 Small): foundation/depth_estimation.md - Florence-2: foundation/florence2.md - TrOCR (OCR): foundation/trocr.md - Grounding DINO (Object Detection): foundation/grounding_dino.md diff --git a/tests/inference/integration_tests/conftest.py b/tests/inference/integration_tests/conftest.py index 0999d6b1cc..dfc4361124 100644 --- a/tests/inference/integration_tests/conftest.py +++ b/tests/inference/integration_tests/conftest.py @@ -12,6 +12,7 @@ port = os.environ.get("PORT", 9001) base_url = os.environ.get("BASE_URL", "http://localhost") +print(base_url, port) @pytest.fixture(scope="session", autouse=True) def server_url() -> str: diff --git a/tests/inference/integration_tests/test_depth_anything.py b/tests/inference/integration_tests/test_depth_anything.py new file mode 100644 index 0000000000..4efd0b4abe --- /dev/null +++ b/tests/inference/integration_tests/test_depth_anything.py @@ -0,0 +1,43 @@ +import os + +import pytest +import requests + +from tests.inference.integration_tests.regression_test import bool_env + + +api_key = os.environ.get("API_KEY") + + + + +@pytest.mark.skipif( + bool_env(os.getenv("SKIP_DEPTH_ESTIMATION_TEST", False)), + reason="Skipping Depth Estimation test", +) +def test_depth_estimation_inference( + server_url: str, clean_loaded_models_every_test_fixture +) -> None: + # given + payload = { + "api_key": api_key, + "image": { + "type": "url", + "value": "https://media.roboflow.com/dog.jpeg", + }, + "model_id": "depth-anything-v2/small", + } + + # when + response = requests.post( + f"{server_url}/infer/depth-estimation", + json=payload, + ) + + # then + response.raise_for_status() + data = response.json() + assert "normalized_depth" in data, "Expected normalized_depth in response" + assert "image" in data, "Expected image in response" + assert len(data["normalized_depth"]) > 0, "Expected non-empty depth map" + diff --git a/tests/inference/integration_tests/test_depth_estimation_block.py b/tests/inference/integration_tests/test_depth_estimation_block.py new file mode 100644 index 0000000000..ab456e6dc4 --- /dev/null +++ b/tests/inference/integration_tests/test_depth_estimation_block.py @@ -0,0 +1,76 @@ +import os + +import pytest +import requests +import numpy as np +from PIL import Image + +from tests.inference.integration_tests.regression_test import bool_env +from inference.core.workflows.execution_engine.entities.base import WorkflowImageData, ImageParentMetadata + +api_key = os.environ.get("API_KEY") + + +@pytest.mark.skipif( + bool_env(os.getenv("SKIP_DEPTH_ESTIMATION_TEST", False)), + reason="Skipping Depth Estimation test", +) +def test_depth_estimation_block_inference( + server_url: str, clean_loaded_models_every_test_fixture +) -> None: + # given + # Create a test image + test_image = np.zeros((224, 224, 3), dtype=np.uint8) + test_image[50:150, 50:150] = 255 # Add a white square + + # Convert numpy array to base64 string + from base64 import b64encode + import io + img = Image.fromarray(test_image) + buffered = io.BytesIO() + img.save(buffered, format="PNG") + img_str = b64encode(buffered.getvalue()).decode() + + # Create the block configuration with serializable data + block_config = { + "type": "roboflow_core/depth_estimation@v1", + "name": "depth_estimation", + "images": { + "type": "WorkflowImageData", + "value": { + "numpy_image": img_str, + "parent_metadata": { + "parent_id": "test_image" + } + } + }, + "model_version": "depth-anything-v2/small" + } + + # when + response = requests.post( + f"{server_url}/workflows/execute", + json={ + "api_key": api_key, + "blocks": [block_config] + }, + ) + + # then + response.raise_for_status() + data = response.json() + + # Verify the response structure + assert "results" in data, "Expected results in response" + assert len(data["results"]) == 1, "Expected one result" + result = data["results"][0] + + # Verify the depth estimation outputs + assert "image" in result, "Expected image in result" + assert "normalized_depth" in result, "Expected normalized_depth in result" + + # Verify the depth map is valid + depth_map = result["normalized_depth"] + assert isinstance(depth_map, list), "Expected depth map to be a list" + assert len(depth_map) > 0, "Expected non-empty depth map" + assert all(0 <= x <= 1 for x in depth_map), "Expected depth values to be normalized between 0 and 1" \ No newline at end of file diff --git a/tests/workflows/integration_tests/execution/test_workflow_with_depth_anything.py b/tests/workflows/integration_tests/execution/test_workflow_with_depth_anything.py new file mode 100644 index 0000000000..9e0db5fb22 --- /dev/null +++ b/tests/workflows/integration_tests/execution/test_workflow_with_depth_anything.py @@ -0,0 +1,83 @@ +import copy +import json +import os + +import numpy as np +import pytest + +from inference.core.env import WORKFLOWS_MAX_CONCURRENT_STEPS +from inference.core.managers.base import ModelManager +from inference.core.workflows.core_steps.common.entities import StepExecutionMode +from inference.core.workflows.execution_engine.core import ExecutionEngine +from inference.core.workflows.execution_engine.entities.base import WorkflowImageData +from tests.workflows.integration_tests.execution.conftest import bool_env +from tests.workflows.integration_tests.execution.workflows_gallery_collector.decorators import ( + add_to_workflows_gallery, +) + +DEPTH_ESTIMATION_WORKFLOW_DEFINITION = { + "version": "1.0", + "inputs": [ + {"type": "InferenceImage", "name": "image"}, + ], + "steps": [ + { + "type": "roboflow_core/depth_estimation@v1", + "name": "depth_estimation", + "images": "$inputs.image" + } + ], + "outputs": [ + { + "type": "JsonField", + "name": "model_predictions", + "coordinates_system": "own", + "selector": "$steps.depth_estimation.*", + } + ], +} + + +@add_to_workflows_gallery( + category="Workflows with Depth Estimation", + use_case_title="Depth Estimation", + use_case_description=""" +**THIS EXAMPLE CAN ONLY BE RUN LOCALLY OR USING DEDICATED DEPLOYMENT** + +Use Depth Estimation to estimate the depth of an image. + """, + workflow_definition=DEPTH_ESTIMATION_WORKFLOW_DEFINITION, + workflow_name_in_app="depth_estimation", +) +@pytest.mark.skipif( + bool_env(os.getenv("SKIP_DEPTH_ESTIMATION_TEST", True)), reason="Skipping Depth Estimation test" +) +def test_depth_estimation_inference( + model_manager: ModelManager, + dogs_image: np.ndarray, + roboflow_api_key: str, +) -> None: + # given + workflow_init_parameters = { + "workflows_core.model_manager": model_manager, + "workflows_core.api_key": roboflow_api_key, + "workflows_core.step_execution_mode": StepExecutionMode.LOCAL, + } + execution_engine = ExecutionEngine.init( + workflow_definition=DEPTH_ESTIMATION_WORKFLOW_DEFINITION, + init_parameters=workflow_init_parameters, + max_concurrent_steps=WORKFLOWS_MAX_CONCURRENT_STEPS, + ) + + # when + result = execution_engine.run( + runtime_parameters={ + "image": dogs_image, + } + ) + + assert isinstance(result, list), "Expected list to be delivered" + assert len(result) == 1, "Expected 1 element in the output for one input image" + assert set(result[0].keys()) == { + "model_predictions", + }, "Expected all declared outputs to be delivered"