depth_estimation.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from typing import Any, Union, overload
  2. from ..utils import (
  3. add_end_docstrings,
  4. is_torch_available,
  5. is_vision_available,
  6. logging,
  7. requires_backends,
  8. )
  9. from .base import Pipeline, build_pipeline_init_args
  10. if is_vision_available():
  11. from PIL import Image
  12. from ..image_utils import load_image
  13. if is_torch_available():
  14. from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES
  15. logger = logging.get_logger(__name__)
  16. @add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
  17. class DepthEstimationPipeline(Pipeline):
  18. """
  19. Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
  20. Example:
  21. ```python
  22. >>> from transformers import pipeline
  23. >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
  24. >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
  25. >>> # This is a tensor with the values being the depth expressed in meters for each pixel
  26. >>> output["predicted_depth"].shape
  27. torch.Size([1, 384, 384])
  28. ```
  29. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  30. This depth estimation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  31. `"depth-estimation"`.
  32. See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation).
  33. """
  34. _load_processor = False
  35. _load_image_processor = True
  36. _load_feature_extractor = False
  37. _load_tokenizer = False
  38. def __init__(self, *args, **kwargs):
  39. super().__init__(*args, **kwargs)
  40. requires_backends(self, "vision")
  41. self.check_model_type(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
  42. @overload
  43. def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> dict[str, Any]: ...
  44. @overload
  45. def __call__(self, inputs: list[Union[str, "Image.Image"]], **kwargs: Any) -> list[dict[str, Any]]: ...
  46. def __call__(
  47. self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any
  48. ) -> dict[str, Any] | list[dict[str, Any]]:
  49. """
  50. Predict the depth(s) of the image(s) passed as inputs.
  51. Args:
  52. inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
  53. The pipeline handles three types of images:
  54. - A string containing a http link pointing to an image
  55. - A string containing a local path to an image
  56. - An image loaded in PIL directly
  57. The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
  58. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
  59. images.
  60. parameters (`Dict`, *optional*):
  61. A dictionary of argument names to parameter values, to control pipeline behaviour.
  62. The only parameter available right now is `timeout`, which is the length of time, in seconds,
  63. that the pipeline should wait before giving up on trying to download an image.
  64. timeout (`float`, *optional*, defaults to None):
  65. The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
  66. the call may block forever.
  67. Return:
  68. A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
  69. dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
  70. the images.
  71. The dictionaries contain the following keys:
  72. - **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.
  73. - **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.
  74. """
  75. # After deprecation of this is completed, remove the default `None` value for `images`
  76. if "images" in kwargs:
  77. inputs = kwargs.pop("images")
  78. if inputs is None:
  79. raise ValueError("Cannot call the depth-estimation pipeline without an inputs argument!")
  80. return super().__call__(inputs, **kwargs)
  81. def _sanitize_parameters(self, timeout=None, parameters=None, **kwargs):
  82. preprocess_params = {}
  83. if timeout is not None:
  84. preprocess_params["timeout"] = timeout
  85. if isinstance(parameters, dict) and "timeout" in parameters:
  86. preprocess_params["timeout"] = parameters["timeout"]
  87. return preprocess_params, {}, {}
  88. def preprocess(self, image, timeout=None):
  89. image = load_image(image, timeout)
  90. model_inputs = self.image_processor(images=image, return_tensors="pt")
  91. model_inputs = model_inputs.to(self.dtype)
  92. model_inputs["target_size"] = image.size[::-1]
  93. return model_inputs
  94. def _forward(self, model_inputs):
  95. target_size = model_inputs.pop("target_size")
  96. model_outputs = self.model(**model_inputs)
  97. model_outputs["target_size"] = target_size
  98. return model_outputs
  99. def postprocess(self, model_outputs):
  100. outputs = self.image_processor.post_process_depth_estimation(
  101. model_outputs,
  102. # this acts as `source_sizes` for ZoeDepth and as `target_sizes` for the rest of the models so do *not*
  103. # replace with `target_sizes = [model_outputs["target_size"]]`
  104. [model_outputs["target_size"]],
  105. )
  106. formatted_outputs = []
  107. for output in outputs:
  108. depth = output["predicted_depth"].detach().cpu().numpy()
  109. depth = (depth - depth.min()) / (depth.max() - depth.min())
  110. depth = Image.fromarray((depth * 255).astype("uint8"))
  111. formatted_outputs.append({"predicted_depth": output["predicted_depth"], "depth": depth})
  112. return formatted_outputs[0] if len(outputs) == 1 else formatted_outputs