depth_estimation.py 5.6 KB

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