Transformers documentation
Depth Anything
该模型于 2024-01-19 在 HF papers 上发布,并于 2024-01-25 贡献至 Hugging Face Transformers。
Depth Anything
Depth Anything 旨在成为单目深度估计(MDE)的基础模型。它在带标签数据和约 6200 万张无标签图像上联合训练,以增强数据集。该模型使用预训练的 DINOv2 模型作为图像编码器,以继承其已有的丰富语义先验,并使用 DPT 作为解码器。一个教师模型在无标签图像上进行训练以生成伪标签。学生模型则在伪标签和带标签图像的组合上进行训练。为了提升学生模型的性能,对无标签图像施加了强扰动,以促使学生模型从图像中学习更多的视觉知识。
您可以在 Depth Anything 集合中找到所有原始的 Depth Anything 检查点。
点击右侧边栏中的 Depth Anything 模型,以查看更多将 Depth Anything 应用于不同视觉任务的示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类获取深度图。
from transformers import pipeline
pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf", device=0)
pipe("http://images.cocodataset.org/val2017/000000039769.jpg")["depth"]import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-base-hf")
model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-base-hf", device_map="auto")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
post_processed_output = image_processor.post_process_depth_estimation(
outputs,
target_sizes=[(image.height, image.width)],
)
predicted_depth = post_processed_output[0]["predicted_depth"]
depth = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min())
depth = depth.detach().cpu().numpy() * 255
Image.fromarray(depth.astype("uint8"))备注
- DepthAnythingV2 于 2024 年 6 月发布,采用与 Depth Anything 相同的架构,并兼容所有代码示例和现有工作流。它利用合成数据和更大容量的教师模型,实现了更精细且鲁棒的深度预测。
DepthAnythingConfig
class transformers.DepthAnythingConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepatch_size: int | list[int] | tuple[int, int] = 14initializer_range: float = 0.02reassemble_hidden_size: int = 384reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5)neck_hidden_sizes: list[int] | tuple[int, ...] = (48, 96, 192, 384)fusion_hidden_size: int = 64head_in_index: int = -1head_hidden_size: int = 32depth_estimation_type: str = 'relative'max_depth: int | None = 1 )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为14) — 每个 patch 的大小(分辨率)。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - reassemble_hidden_size (
int, 可选,默认为 384) — 重组层的输入通道数。 - reassemble_factors (
list[int],可选,默认为[4, 2, 1, 0.5]) — 重组层的上采样/下采样因子。 - neck_hidden_sizes (
list[str],可选,默认为[48, 96, 192, 384]) — 用于将主干网络的特征图投影到的隐藏层大小。 - fusion_hidden_size (
int,可选,默认为 64) — 融合前的通道数。 - head_in_index (
int,可选,默认为 -1) — 深度估计头中要使用的特征的索引。 - head_hidden_size (
int, 可选,默认为 32) — 深度估计头中第二个卷积层的输出通道数。 - depth_estimation_type (
str,可选,默认为"relative") — 要使用的深度估计类型。可以是["relative", "metric"]之一。 - max_depth (
float, 可选) — “metric” 深度估计头所使用的最大深度。室内模型应使用 20,室外模型应使用 80。对于“relative” 深度估计,此值将被忽略。
这是用于存储 Depth AnythingModel 配置的类。它根据指定的参数实例化 Depth Anything 模型,并定义模型架构。使用默认值实例化配置将得到与 LiheYoung/depth-anything-small-hf 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation
>>> # Initializing a DepthAnything small style configuration
>>> configuration = DepthAnythingConfig()
>>> # Initializing a model from the DepthAnything small style configuration
>>> model = DepthAnythingForDepthEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configDepthAnythingForDepthEstimation
class transformers.DepthAnythingForDepthEstimation
< source >( config: DepthAnythingConfig )
参数
- config (DepthAnythingConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有深度估计头(由 3 个卷积层组成)的 Depth Anything 模型,例如用于 KITTI、NYUv2。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → DepthEstimatorOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 DPTImageProcessor 获取像素值。有关详细信息,请参阅 DPTImageProcessor.call()(processor_class使用 DPTImageProcessor 处理图像)。 - labels(形状为
(batch_size, height, width)的torch.LongTensor,可选) — 用于计算损失的真实深度估计图。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
DepthEstimatorOutput 或 tuple(torch.Tensor)
DepthEstimatorOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(DepthAnythingConfig)和输入。
DepthAnythingForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。predicted_depth(形状为
(batch_size, height, width)的torch.Tensor)— 每个像素的预测深度。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, num_channels, height, width)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
... outputs,
... target_sizes=[(image.height, image.width)],
... )
>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 255 / predicted_depth.max()
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))