Transformers documentation

Depth Anything

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2024-01-19에 HF papers에 게시되었으며, 2024-01-25에 Hugging Face Transformers에 기여되었습니다.

Depth Anything

Depth Anything는 단안 깊이 추정(MDE)을 위한 파운데이션 모델로 설계되었습니다. 레이블이 있는 이미지와 ~62M개의 레이블이 없는 이미지를 함께 학습하여 데이터셋을 강화합니다. 이미지에 대한 풍부한 기존 의미론적 선행 지식을 상속받기 위해 사전 학습된 DINOv2 모델을 이미지 인코더로 사용하고, DPT를 디코더로 사용합니다. 레이블이 없는 이미지에서 교사 모델을 학습시켜 의사 레이블을 생성합니다. 학생 모델은 의사 레이블과 레이블이 있는 이미지의 조합으로 학습됩니다. 학생 모델의 성능을 향상시키기 위해, 레이블이 없는 이미지에 강한 교란을 추가하여 학생 모델이 이미지에서 더 많은 시각적 지식을 학습하도록 유도합니다.

모든 Depth Anything 원본 체크포인트는 Depth Anything 컬렉션에서 찾을 수 있습니다.

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

아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 깊이 맵을 얻는 방법을 보여줍니다.

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

The input is a single word "Notes". 참고

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

DepthAnythingConfig

class transformers.DepthAnythingConfig

< >

( 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], 선택) — backbone 모델의 설정입니다.
  • 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 map을 투영할 hidden size입니다.
  • fusion_hidden_size (int, 선택 사항, 기본값 64) — 퓨전 이전의 채널 수입니다.
  • head_in_index (int, 선택 사항, 기본값 -1) — 깊이 추정 헤드에서 사용할 특징의 인덱스입니다.
  • head_hidden_size (int, 선택 사항, 기본값 32) — 깊이 추정 헤드(second convolution)의 두 번째 컨볼루션에서 출력 채널의 수입니다.
  • depth_estimation_type (str, 선택 사항, 기본값 "relative") — 사용할 깊이 추정 유형입니다. ["relative", "metric"] 중 하나를 지정할 수 있습니다.
  • max_depth (float, 선택) — “metric” 깊이 추정 헤드에 사용할 최대 깊이입니다. 실내 모델에는 20, 실외 모델에는 80을 사용해야 합니다. “relative” 깊이 추정의 경우 이 값은 무시됩니다.

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

Configuration 객체는 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.config

DepthAnythingForDepthEstimation

class transformers.DepthAnythingForDepthEstimation

< >

( config: DepthAnythingConfig )

매개변수

  • config (DepthAnythingConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

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

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → DepthEstimatorOutput or tuple(torch.FloatTensor)

매개변수

  • pixel_values (torch.FloatTensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 DPTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 DPTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 DPTImageProcessor를 사용합니다).
  • labels (torch.LongTensor, shape (batch_size, height, width), 선택 사항) — 손실을 계산하기 위한 ground truth depth estimation map입니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

DepthEstimatorOutput 또는 tuple(torch.FloatTensor)

torch.FloatTensor의 튜플 또는 DepthEstimatorOutput(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(DepthAnythingConfig)과 입력에 따라 다양한 요소를 포함합니다.

DepthAnythingForDepthEstimation의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.FloatTensor, shape (1,), 선택 사항, labels가 제공될 때 반환됨) — 분류(또는 config.num_labels==1인 경우 회귀) 손실.

  • predicted_depth (torch.FloatTensor, shape (batch_size, height, width)) — 각 픽셀에 대한 예측된 깊이.

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력용 1개 + 각 레이어의 출력용 1개)로, 모양은 (batch_size, num_channels, height, width)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.FloatTensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.FloatTensor의 튜플로, 모양은 (batch_size, num_heads, patch_size, sequence_length)입니다.

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

예:

>>> 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"))
Update on GitHub