Transformers documentation

Prompt 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.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2024-12-18에 HF papers에 게시되었으며, 2025-03-21에 Hugging Face Transformers에 기여되었습니다.

Prompt Depth Anything

개요

Prompt Depth Anything 모델은 Haotong Lin, Sida Peng, Jingxiao Chen, Songyou Peng, Jiaming Sun, Minghuan Liu, Hujun Bao, Jiashi Feng, Xiaowei Zhou, Bingyi Kang이 발표한 Prompting Depth Anything for 4K Resolution Accurate Metric Depth Estimation 논문에서 소개되었습니다.

해당 논문의 초록은 다음과 같습니다:

Prompt은 언어 및 비전 파운데이션 모델의 잠재력을 특정 작업에서 끌어내는 데 핵심적인 역할을 합니다. 본 논문에서는 깊이 파운데이션 모델에 prompting을 최초로 도입하여, Prompt Depth Anything이라 불리는 metric depth estimation의 새로운 패러다임을 제시합니다. 구체적으로, 저비용 LiDAR를 prompt로 사용하여 Depth Anything 모델이 최대 4K 해상도로 정확한 metric depth를 출력하도록 유도합니다. 제안된 접근법의 핵심은 깊이 디코더 내에서 여러 스케일로 LiDAR를 통합하는 간결한 prompt fusion 설계입니다. LiDAR 깊이와 정확한 GT 깊이를 모두 포함하는 제한된 데이터셋으로 인한 학습의 어려움을 해결하기 위해, 합성 데이터 LiDAR 시뮬레이션과 실데이터 pseudo GT 깊이 생성을 포함하는 확장 가능한 데이터 파이프라인을 제안합니다. 본 접근법은 ARKitScenes 및 ScanNet++ 데이터셋에서 새로운 state-of-the-art를 달성하며, 3D 재구성 및 범용 로봇 그랩핑을 포함한 다운스트림 애플리케이션에 이점을 제공합니다.

drawing Prompt Depth Anything overview. Taken from the original paper.

사용 예시

Transformers 라이브러리를 사용하면 몇 줄의 코드로 모델을 사용할 수 있습니다:

import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForDepthEstimation


url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/image.jpg?raw=true"
image = Image.open(requests.get(url, stream=True).raw)

image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
model = AutoModelForDepthEstimation.from_pretrained("depth-anything/prompt-depth-anything-vits-hf", device_map="auto")

prompt_depth_url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/arkit_depth.png?raw=true"
prompt_depth = Image.open(requests.get(prompt_depth_url, stream=True).raw)
# the prompt depth can be None, and the model will output a monocular relative depth.

# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt", prompt_depth=prompt_depth).to(model.device)

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 * 1000
depth = depth.detach().cpu().numpy()
depth = Image.fromarray(depth.astype("uint16")) # mm

리소스

Prompt Depth Anything를 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

여기에 포함할 리소스를 제출하고 싶으시면 Pull Request를 열어 주시면 검토하겠습니다! 리소스는 기존 리소스를 중복하는 대신 새로운 것을 시연하는 것이 이상적입니다.

PromptDepthAnythingConfig

클래스 transformers.PromptDepthAnythingConfig

< >

( 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” 깊이 추정의 경우 이 값은 무시됩니다.

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

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import PromptDepthAnythingConfig, PromptDepthAnythingForDepthEstimation

>>> # Initializing a PromptDepthAnything small style configuration
>>> configuration = PromptDepthAnythingConfig()

>>> # Initializing a model from the PromptDepthAnything small style configuration
>>> model = PromptDepthAnythingForDepthEstimation(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

PromptDepthAnythingForDepthEstimation

class transformers.PromptDepthAnythingForDepthEstimation

< >

( config: PromptDepthAnythingConfig )

매개변수

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

KITTI, NYUv2와 같은 데이터셋을 위해 Depth Anything Model 위에 깊이 추정 헤드(3개의 합성곱 계층으로 구성)를 추가하여 프롬프트합니다.

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

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

forward

< >

( pixel_values: Tensorprompt_depth: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DepthEstimatorOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 PromptDepthAnythingImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 PromptDepthAnythingImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 PromptDepthAnythingImageProcessor를 사용합니다).
  • prompt_depth (torch.Tensor, shape (batch_size, 1, height, width), 선택) — Prompt depth는 다중 뷰 기하학(multi-view geometry) 또는 저해상도 깊이 센서에서 얻은 희소(sparse)하거나 저해상도의 깊이입니다. 일반적으로 (height, width) 형태를 가지며, 이때 height와 width는 이미지의 그것보다 작을 수 있습니다. 이 인자는 선택 사항이며, None을 지정하면 prompt depth를 사용하지 않습니다. None인 경우 출력은 단안(monocular) 상대 깊이가 됩니다. 값은 미터(meter) 단위로 권장되지만, 필수 사항은 아닙니다.
  • labels (torch.LongTensor, shape (batch_size, height, width), 선택 사항) — 손실을 계산하기 위한 ground truth depth estimation map입니다.

반환값

DepthEstimatorOutput 또는 tuple(torch.Tensor)

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

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

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

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

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

  • 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인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (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 = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/image.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")

>>> prompt_depth_url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/arkit_depth.png?raw=true"
>>> with httpx.stream("GET", prompt_depth_url) as response:
...     prompt_depth = Image.open(BytesIO(response.read()))

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt", prompt_depth=prompt_depth)

>>> 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 * 1000.
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint16")) # mm

PromptDepthAnythingImageProcessor

class transformers.PromptDepthAnythingImageProcessor

< >

( **kwargs: *<class 'transformers.models.prompt_depth_anything.image_processing_prompt_depth_anything.PromptDepthAnythingImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'height' -- 384, 'width': 384}): 모델에 입력되는 최대 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 True) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부입니다.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 3) — 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택, 기본값 True) — 이미지를 다시 스케일링할지 여부.
  • rescale_factor (float, kwargs, 선택 사항, 기본값 0.00392156862745098) — do_rescale이 True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다.
  • do_normalize (bool, kwargs, 선택, 기본값 True) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, 선택, 기본값 False) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • keep_aspect_ratio (bool, kwargs, 선택) — True인 경우, 종횡비를 유지하면서 이미지를 가능한 가장 큰 크기로 리사이즈합니다.
  • ensure_multiple_of (int, kwargs, 선택) — do_resize가 True인 경우, 이미지는 이 값의 배수가 되는 크기로 리사이즈됩니다.
  • size_divisor (int, kwargs, 선택) — do_pad이 True인 경우, 이미지 차원을 이 값으로 나누어 떨어지도록 패딩을 적용합니다.
  • prompt_scale_to_meter (float, kwargs, 선택) — 프롬프트 깊이를 미터로 변환하는 스케일 팩터입니다.

PromptDepthAnythingImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]prompt_depth: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.prompt_depth_anything.image_processing_prompt_depth_anything.PromptDepthAnythingImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • prompt_depth (ImageInput, 선택 사항) — 전처리할 프롬프트 깊이입니다.
  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택 사항) — 이미지를 다시 스케일링할지 여부입니다.
  • rescale_factor (float, kwargs, optional) — do_rescale이 True로 설정된 경우 이미지를 리스케일하기 위한 리스케일 팩터입니다.
  • do_normalize (bool, kwargs, optional) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • keep_aspect_ratio (bool, kwargs, 선택) — True인 경우, 종횡비를 유지하면서 이미지를 가능한 가장 큰 크기로 리사이즈합니다.
  • ensure_multiple_of (int, kwargs, 선택) — do_resize가 True인 경우, 이미지는 이 값의 배수가 되는 크기로 리사이즈됩니다.
  • size_divisor (int, kwargs, 선택) — do_pad이 True인 경우, 이미지 차원을 이 값으로 나누어 떨어지도록 패딩을 적용합니다.
  • prompt_scale_to_meter (float, kwargs, 선택) — 프롬프트 깊이를 미터로 변환하는 스케일 팩터입니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

post_process_depth_estimation

< >

( outputs: DepthEstimatorOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None ) → list[dict[str, TensorType]]

매개변수

  • outputs (DepthEstimatorOutput) — 모델의 원시 출력입니다.
  • target_sizes (TensorType 또는 list[tuple[int, int]], 선택 사항) — 배치 내 각 이미지의 대상 크기(높이, 너비)를 포함하는 (batch_size, 2) 형태의 Tensor 또는 튜플(tuple[int, int]) 목록입니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

반환값

list[dict[str, TensorType]]

처리된 깊이 예측을 나타내는 텐서 딕셔너리의 목록입니다.

DepthEstimatorOutput의 원시 출력을 최종 깊이 예측값과 깊이 PIL 이미지로 변환합니다. PyTorch만 지원합니다.

PromptDepthAnythingImageProcessorPil

클래스 transformers.PromptDepthAnythingImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.prompt_depth_anything.image_processing_pil_prompt_depth_anything.PromptDepthAnythingImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'height' -- 384, 'width': 384}): 모델에 입력되는 최대 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 True) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부입니다.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 3) — 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택, 기본값 True) — 이미지를 다시 스케일링할지 여부.
  • rescale_factor (float, kwargs, 선택 사항, 기본값 0.00392156862745098) — do_rescale이 True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다.
  • do_normalize (bool, kwargs, 선택, 기본값 True) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, 선택, 기본값 False) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • keep_aspect_ratio (bool, kwargs, 선택) — True인 경우, 종횡비를 유지하면서 이미지를 가능한 가장 큰 크기로 리사이즈합니다.
  • ensure_multiple_of (int, kwargs, 선택) — do_resize가 True인 경우, 이미지는 이 값의 배수가 되는 크기로 리사이즈됩니다.
  • size_divisor (int, kwargs, 선택) — do_pad이 True인 경우, 이미지 차원을 이 값으로 나누어 떨어지도록 패딩을 적용합니다.
  • prompt_scale_to_meter (float, kwargs, 선택) — 프롬프트 깊이를 미터로 변환하는 스케일 팩터입니다.

PromptDepthAnythingImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]prompt_depth: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.prompt_depth_anything.image_processing_pil_prompt_depth_anything.PromptDepthAnythingImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • prompt_depth (ImageInput, 선택 사항) — 전처리할 프롬프트 깊이입니다.
  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택 사항) — 이미지를 다시 스케일링할지 여부입니다.
  • rescale_factor (float, kwargs, optional) — do_rescale이 True로 설정된 경우 이미지를 리스케일하기 위한 리스케일 팩터입니다.
  • do_normalize (bool, kwargs, optional) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • keep_aspect_ratio (bool, kwargs, 선택) — True인 경우, 종횡비를 유지하면서 이미지를 가능한 가장 큰 크기로 리사이즈합니다.
  • ensure_multiple_of (int, kwargs, 선택) — do_resize가 True인 경우, 이미지는 이 값의 배수가 되는 크기로 리사이즈됩니다.
  • size_divisor (int, kwargs, 선택) — do_pad이 True인 경우, 이미지 차원을 이 값으로 나누어 떨어지도록 패딩을 적용합니다.
  • prompt_scale_to_meter (float, kwargs, 선택) — 프롬프트 깊이를 미터로 변환하는 스케일 팩터입니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

post_process_depth_estimation

< >

( outputs: DepthEstimatorOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None ) → list[dict[str, TensorType]]

매개변수

  • outputs (DepthEstimatorOutput) — 모델의 원시 출력입니다.
  • target_sizes (TensorType 또는 list[tuple[int, int]], 선택 사항) — 배치 내 각 이미지의 대상 크기(높이, 너비)를 포함하는 (batch_size, 2) 형태의 Tensor 또는 튜플(tuple[int, int]) 목록입니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

반환값

list[dict[str, TensorType]]

처리된 깊이 예측을 나타내는 텐서 딕셔너리의 목록입니다.

DepthEstimatorOutput의 원시 출력을 최종 깊이 예측값과 깊이 PIL 이미지로 변환합니다. PyTorch만 지원합니다.

Update on GitHub