# Depth Anything

[Depth Anything](https://huggingface.co/papers/2401.10891)는 단안 깊이 추정(MDE)을 위한 파운데이션 모델로 설계되었습니다. 데이터셋을 강화하기 위해 라벨이 있는 이미지와 약 6,200만 장의 라벨이 없는 이미지로 함께 학습됩니다. 이미지에 풍부한 기존 의미론적 선행 지식을 상속받기 위해 사전 학습된 [DINOv2](./dinov2) 모델을 이미지 인코더로 사용하고, [DPT](./dpt)를 디코더로 사용합니다. 라벨이 없는 이미지로_teacher 모델을 학습시켜 의사 라벨을 생성합니다. 학생 모델은 의사 라벨과 라벨이 있는 이미지의 조합으로 학습됩니다. 학생 모델의 성능을 향상시키기 위해, 라벨이 없는 이미지에 강한 교란을 추가하여 학생 모델이 이미지에서 더 많은 시각적 지식을 학습하도록 유도합니다.

모든 Depth Anything 원본 체크포인트는 [Depth Anything](https://huggingface.co/collections/LiheYoung/depth-anything-release-65b317de04eec72abf6b55aa) 컬렉션에서 찾을 수 있습니다.

> [!TIP]
> 오른쪽 사이드바의 Depth Anything 모델에 클릭하여 Depth Anything을 다양한 비전 작업에 적용하는 방법에 대한 추가 예제를 확인하세요.

아래 예제는 [Pipeline](/docs/transformers/v5.23.0/ko/main_classes/pipelines#transformers.Pipeline) 또는 [AutoModel](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoModel) 클래스를 사용하여 깊이 맵을 얻는 방법을 보여줍니다.

```python
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"]
```

```python
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"))
```

## The input is a single word "Notes".

참고

- 2024년 6월에 출시된 [DepthAnythingV2](./depth_anything_v2)는 Depth Anything과 동일한 아키텍처를 사용하며 모든 코드 예제 및 기존 워크플로우와 호환됩니다. 합성 데이터와 더 큰 용량의 teacher 모델을 활용하여 훨씬 더 정밀하고 견고한 깊이 예측을 수행합니다.

## DepthAnythingConfig[[transformers.DepthAnythingConfig]]

#### transformers.DepthAnythingConfig[[transformers.DepthAnythingConfig]]

```python
transformers.DepthAnythingConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, patch_size: int | list[int] | tuple[int, int] = 14, initializer_range: float = 0.02, reassemble_hidden_size: int = 384, reassemble_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 = 64, head_in_index: int = -1, head_hidden_size: int = 32, depth_estimation_type: str = 'relative', max_depth: int | None = 1)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/configuration_depth_anything.py#L25)

**매개변수:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 백본 모델의 구성입니다.

patch_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `14`) : 각 패치의 크기(해상도).

initializer_range (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

reassemble_hidden_size (`int`, *선택 사항*, 기본값 384) : reassemble 레이어의 입력 채널 수입니다.

reassemble_factors (`list[int]`, *선택 사항*, 기본값 `[4, 2, 1, 0.5]`) : reassemble 레이어의 업/다운샘플링 계수입니다.

neck_hidden_sizes (`list[str]`, *선택 사항*, 기본값 `[48, 96, 192, 384]`) : 백본의 feature maps를 투영할 hidden sizes입니다.

fusion_hidden_size (`int`, *선택 사항*, 기본값 64) : 퓨전 전의 채널 수입니다.

head_in_index (`int`, *선택 사항*, 기본값 -1) : 깊이 추정 헤드에서 사용할 기능의 인덱스입니다.

head_hidden_size (`int`, *선택 사항*, 기본값 32) : 깊이 추정 헤드(depth estimation head)의 두 번째 컨볼루션의 출력 채널 수입니다.

depth_estimation_type (`str`, *선택 사항*, 기본값 `"relative"`) : 사용할 깊이 추정 유형입니다. `["relative", "metric"]` 중 하나여야 합니다.

max_depth (`float`, *선택 사항*) : "metric" 깊이 추정 헤드에 사용할 최대 깊이입니다. 실내 모델에는 20, 야외 모델에는 80을 사용해야 합니다. "relative" 깊이 추정의 경우 이 값은 무시됩니다.

이것은 Depth AnythingModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Depth Anything 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:

```python
>>> 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.config
```

## DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

#### transformers.DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

```python
transformers.DepthAnythingForDepthEstimation(config: DepthAnythingConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/modeling_depth_anything.py#L316)

**매개변수:**

config ([DepthAnythingConfig](/docs/transformers/v5.23.0/ko/model_doc/depth_anything#transformers.DepthAnythingConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

KITTI, NYUv2 등에 사용되는, 상단에 깊이 추정 헤드(3개의 합성곱 계층으로 구성)가 있는 Depth Anything Model

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.DepthAnythingForDepthEstimation.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/modeling_depth_anything.py#L327)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서입니다. [DPTImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/dpt#transformers.DPTImageProcessor)를 사용하여 픽셀 값을 얻을 수 있습니다. 자세한 내용은 [DPTImageProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지를 처리하는 데 [DPTImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/dpt#transformers.DPTImageProcessor)를 사용합니다).

labels (`torch.LongTensor`, shape `(batch_size, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground truth depth estimation 맵.

output_attentions (`bool`, *선택 사항*) : 모든 어텐션 레이어의 어텐션 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 `attentions`를 참조하세요.

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** [DepthEstimatorOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 또는 `tuple(torch.Tensor)`

[DepthEstimatorOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`이 전달되었거나 `config.return_dict=False`인 경우)로, 구성([DepthAnythingConfig](/docs/transformers/v5.23.0/ko/model_doc/depth_anything#transformers.DepthAnythingConfig)) 및 입력에 따라 다양한 요소를 포함합니다.

[DepthAnythingForDepthEstimation](/docs/transformers/v5.23.0/ko/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **predicted_depth** (shape가 `(batch_size, height, width)`인 `torch.Tensor`) -- 각 픽셀에 대한 예측된 깊이.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다.

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, patch_size, sequence_length)`인 `torch.Tensor`의 튜플.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

예:
```python
>>> 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"))
```

