Transformers documentation
DepthPro
이 모델은 2024-10-02에 HF papers에 게시되었으며, 2025-02-10에 Hugging Face Transformers에 기여되었습니다.
DepthPro
개요
DepthPro 모델은 Aleksei Bochkovskii, Amaël Delaunoy, Hugo Germain, Marcel Santos, Yichao Zhou, Stephan R. Richter, Vladlen Koltun이 Depth Pro: Sharp Monocular Metric Depth in Less Than a Second에서 제안했습니다.
DepthPro는 제로샷 메트릭 단안 깊이 추정을 위한 파운데이션 모델로, 뛰어난 선명도와 세밀한 디테일을 갖춘 고해상도 깊이 맵을 생성하도록 설계되었습니다. 다중 스케일 Vision Transformer(ViT) 기반 아키텍처를 활용하며, 이미지는 다운샘플링된 후 패치로 분할되고 공유된 Dinov2 인코더를 통해 처리됩니다. 추출된 패치 수준 특징은 병합되고 업샘플링되며, DPT 유사한 퓨전 단계를 통해 정제되어 정밀한 깊이 추정을 가능하게 합니다.
해당 논문의 초록은 다음과 같습니다:
제로샷 메트릭 단안 깊이 추정을 위한 파운데이션 모델을 제시합니다. Depth Pro는 비교할 수 없는 선명도와 고주파 세부 정보를 갖춘 고해상도 깊이 맵을 생성합니다. 예측은 카메라 내부 파라미터와 같은 메타데이터의 가용성에 의존하지 않고 절대 스케일을 갖는 메트릭 값입니다. 또한 이 모델은 빠르며, 표준 GPU에서 0.3초 만에 2.25메가픽셀 깊이 맵을 생성합니다. 이러한 특징은 밀집 예측을 위한 효율적인 멀티스케일 비전 트랜스포머, 정밀한 경계 추적을 유지하면서 높은 메트릭 정확도를 달성하기 위해 실데이터와 합성 데이터를 결합한 학습 프로토콜, 추정된 깊이 맵의 경계 정확도를 위한 전용 평가 지표, 단일 이미지로부터의 최첨단 초점 거리 추정 등 여러 기술적 기여에 의해 가능해졌습니다. 광범위한 실험은 구체적인 설계 선택을 분석하고, Depth Pro가 기존 연구보다 여러 측면에서 우수한 성능을 보임을 입증합니다.
DepthPro Outputs. Taken from the official code. 이 모델은 geetu040님이 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.
사용 팁
DepthPro 모델은 입력 이미지를 여러 스케일로 다운샘플링한 후 각 스케일 버전을 패치로 분할하여 처리합니다. 이러한 패치는 공유되는 Vision Transformer(ViT) 기반 Dinov2 패치 인코더를 통해 인코딩되며, 전체 이미지는 별도의 이미지 인코더로 처리됩니다. 추출된 패치 특징은 특징 맵으로 병합되고 업샘플링된 후, DPT 유사한 디코더를 사용하여 융합되어 최종 깊이 추정치를 생성합니다. 활성화된 경우, 추가적인 시야각(FOV) 인코더가 이미지의 시야각을 추정하기 위해 이미지를 처리하여 깊이 정확도를 높이는 데 기여합니다.
import requests
import torch
from PIL import Image
from transformers import DepthProForDepthEstimation, DepthProImageProcessor
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
image_processor = DepthProImageProcessor.from_pretrained("apple/DepthPro-hf")
model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", device_map="auto")
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)],
)
field_of_view = post_processed_output[0]["field_of_view"]
focal_length = post_processed_output[0]["focal_length"]
depth = post_processed_output[0]["predicted_depth"]
depth = (depth - depth.min()) / depth.max()
depth = depth * 255.
depth = depth.detach().cpu().numpy()
depth = Image.fromarray(depth.astype("uint8"))아키텍처 및 구성
DepthPro architecture. Taken from the original paper. DepthProForDepthEstimation 모델은 입력 이미지를 인코딩하기 위해 DepthProEncoder를 사용하고, 인코더에서 출력된 특징을 융합하기 위해 FeatureFusionStage를 사용합니다.
DepthProEncoder는 두 개의 인코더를 추가로 사용합니다:
patch_encoder- 입력 이미지는
scaled_images_ratios설정에 따라 여러 비율로 스케일링됩니다. - 각 스케일된 이미지는
scaled_images_overlap_ratios로 결정되는 겹침 영역을 포함하여patch_size크기의 더 작은 패치로 분할됩니다. - 이러한 패치는
patch_encoder에 의해 처리됩니다.
- 입력 이미지는
image_encoder- 입력 이미지도
patch_size로 다시 스케일링된 후image_encoder로 처리됩니다.
- 입력 이미지도
이 두 인코더는 각각 patch_model_config와 image_model_config를 통해 설정할 수 있으며, 기본적으로 둘 다 별도의 Dinov2Model입니다.
두 인코더의 출력(last_hidden_state)과 patch_encoder에서 선택된 중간 상태(hidden_states)는 깊이 추정을 위해 DPT 기반 FeatureFusionStage에 의해 융합됩니다.
시야(FOV) 예측
네트워크에는 초점 거리 추정 헤드가 추가됩니다. 작은 컨볼루션 헤드는 깊이 추정 네트워크의 동결된 특징과 별도의 ViT 이미지 인코더의 작업별 특징을 입력받아 수평 각도 시야각을 예측합니다.
DepthProConfig의 use_fov_model 매개변수는 FOV 예측을 활성화할지 여부를 제어합니다. 기본적으로 메모리와 계산 자원을 절약하기 위해 False로 설정되어 있습니다. 활성화되면 fov_model_config 매개변수에 기반하여 FOV 인코더가 생성되며, 이 매개변수의 기본값은 Dinov2Model입니다. use_fov_model 매개변수는 DepthProForDepthEstimation 모델을 초기화할 때 전달할 수도 있습니다.
apple/DepthPro-hf 체크포인트의 사전 학습된 모델은 FOV 인코더를 사용합니다. FOV 인코더 없이 사전 학습된 모델을 사용하려면, 모델을 로드할 때 use_fov_model=False를 설정하여 계산량을 줄일 수 있습니다.
from transformers import DepthProForDepthEstimation
model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", use_fov_model=False, device_map="auto")FOV 인코더를 사용하여 새 모델을 인스턴스화하려면, 설정에서 use_fov_model=True를 설정하세요.
from transformers import DepthProConfig, DepthProForDepthEstimation
config = DepthProConfig(use_fov_model=True)
model = DepthProForDepthEstimation(config)모델 초기화 시 use_fov_model=True를 설정하면 config의 값을 덮어씁니다.
from transformers import DepthProConfig, DepthProForDepthEstimation
config = DepthProConfig()
model = DepthProForDepthEstimation(config, use_fov_model=True)Scaled Dot Product Attention(SDPA) 사용
PyTorch에는 torch.nn.functional의 일부로 네이티브 scaled dot-product attention(SDPA) 연산자가 포함되어 있습니다. 이 함수는 입력과 사용 중인 하드웨어에 따라 적용할 수 있는 여러 구현 방식을 포함합니다. 자세한 내용은 공식 문서 또는 GPU Inference 페이지를 참고하세요.
구현이 사용 가능한 경우 torch>=2.1.1에서는 기본적으로 SDPA가 사용되지만, from_pretrained()에서 attn_implementation="sdpa"를 설정하여 SDPA 사용을 명시적으로 요청할 수도 있습니다.
from transformers import DepthProForDepthEstimation
model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", attn_implementation="sdpa", device_map="auto")최고의 속도 향상을 위해 모델은 반정밀(half-precision, 예: torch.float16 또는 torch.bfloat16)로 로드하는 것을 권장합니다.
로컬 벤치마크(A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04)에서 float32와 google/vit-base-patch16-224 모델을 사용하여 추론 시 다음과 같은 속도 향상을 확인했습니다.
| 배치 크기 | 평균 추론 시간(ms), eager 모드 | 평균 추론 시간(ms), sdpa 모델 | 속도 향상, Sdpa / Eager (x) |
|---|---|---|---|
| 1 | 7 | 6 | 1.17 |
| 2 | 8 | 6 | 1.33 |
| 4 | 8 | 6 | 1.33 |
| 8 | 8 | 6 | 1.33 |
리소스
DepthPro를 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다:
- 연구 논문: Depth Pro: Sharp Monocular Metric Depth in Less Than a Second
- 공식 구현: apple/ml-depth-pro
- DepthPro 추론 노트북: DepthPro 추론
- Super Resolution 및 Image Segmentation을 위한 DepthPro
- Medium 블로그 읽기: Depth Pro: Beyond Depth
- Github 코드: geetu040/depthpro-beyond-depth
여기에 포함할 리소스를 제출하고 싶으시면 Pull Request를 열어 주시면 검토하겠습니다! 기존 리소스와 중복되지 않고 새로운 것을 보여주는 것이 이상적입니다.
DepthProConfig
class transformers.DepthProConfig
< 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 = Nonefusion_hidden_size: int = 256patch_size: int | list[int] | tuple[int, int] = 384initializer_range: float = 0.02intermediate_hook_ids: list[int] | tuple[int, ...] = (11, 5)intermediate_feature_dims: list[int] | tuple[int, ...] = (256, 256)scaled_images_ratios: list[int | float] | tuple[int | float, ...] = (0.25, 0.5, 1)scaled_images_overlap_ratios: list[float] | tuple[float, ...] = (0.0, 0.5, 0.25)scaled_images_feature_dims: list[int] | tuple[int, ...] = (1024, 1024, 512)merge_padding_value: int = 3use_batch_norm_in_fusion_residual: bool = Falseuse_bias_in_fusion_residual: bool = Trueuse_fov_model: bool = Falsenum_fov_head_layers: int = 2image_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepatch_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefov_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )
매개변수
- fusion_hidden_size (
int, 선택 사항, 기본값 256) — 퓨전 이전의 채널 수입니다. - patch_size (
Union[int, list[int], tuple[int, int]], 선택 사항, 기본값384) — 각 패치의 크기(해상도)입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - intermediate_hook_ids (
list[int], 선택 사항, 기본값[11, 5]) — 퓨전에 사용할 패치 인코더의 중간 히든 상태 인덱스입니다. - intermediate_feature_dims (
list[int], 선택 사항, 기본값[256, 256]) —intermediate_hook_ids의 각 중간 hidden state에 대해 업샘플링 시 사용되는 hidden state 차원입니다. - scaled_images_ratios (
list[float], 선택 사항, 기본값[0.25, 0.5, 1]) — 패치 인코더가 사용할 스케일된 이미지의 비율입니다. - scaled_images_overlap_ratios (
list[float], 선택 사항, 기본값[0.0, 0.5, 0.25]) —scaled_images_ratios의 각 스케일된 이미지에서 패치 간 겹침 비율입니다. - scaled_images_feature_dims (
list[int], 선택 사항, 기본값[1024, 1024, 512]) —scaled_images_ratios의 각 스케일된 이미지에 대해 업샘플링 시 사용되는 히든 상태 차원입니다. - merge_padding_value (
int, 선택 사항, 기본값 3) — 작은 패치를 이미지 크기로 다시 병합할 때, 이 크기의 겹치는 부분이 제거됩니다. - use_batch_norm_in_fusion_residual (
bool, 선택 사항, 기본값False) — fusion 블록의 pre-activate residual unit에서 batch normalization을 사용할지 여부입니다. - use_bias_in_fusion_residual (
bool, 선택 사항, 기본값True) — fusion 블록의 pre-activate residual unit에서 bias를 사용할지 여부입니다. - use_fov_model (
bool, 선택 사항, 기본값False) — 시야를 생성할 때DepthProFovModel을 사용할지 여부입니다. - num_fov_head_layers (
int, 선택 사항, 기본값 2) —DepthProFovModel의 헤드에 있는 컨볼루션 레이어의 수입니다. - image_model_config (
Union[dict[str, Any], PreTrainedConfig], 선택) — AutoModel API를 사용하여 로드되는 이미지 인코더 모델의 설정입니다. 기본적으로 Dinov2 모델이 백본으로 사용됩니다. - patch_model_config (
Union[dict[str, Any], PreTrainedConfig], 선택) — AutoModel API를 사용하여 로드되는 패치 인코더 모델의 설정입니다. 기본적으로 Dinov2 모델이 백본으로 사용됩니다. - fov_model_config (
Union[dict[str, Any], PreTrainedConfig], 선택) — AutoModel API를 사용하여 로드되는 fov 인코더 모델의 설정입니다. 기본적으로 Dinov2 모델이 백본으로 사용됩니다.
이것은 DepthProModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Depth Pro 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 초기화하면 apple/DepthPro와 유사한 구성이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
예:
>>> from transformers import DepthProConfig, DepthProModel
>>> # Initializing a DepthPro apple/DepthPro style configuration
>>> configuration = DepthProConfig()
>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
>>> model = DepthProModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configDepthProImageProcessor
class transformers.DepthProImageProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )
매개변수
- 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' -- 1536, 'width': 1536}): 모델에 입력되는 최대 차원을 설명합니다. - 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, 기본값2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다.PILImageResamplingenum 중 하나를 사용할 수 있습니다.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, 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, 선택) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다. - disable_grouping (
bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다. - image_seq_length (
int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다. - Returns
'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다. —
DepthPro 이미지 프로세서를 생성합니다.
disable_grouping (bool, kwargs, 선택):
이미지를 크기로 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부.
None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다. image_seq_length (int, kwargs, 선택):
입력에서 각 이미지에 사용할 이미지 토큰의 수.
하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~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로 설정하세요. - image_like_kwargs (
dict[str, Any], 선택) — 추가 이미지 유사 입력을 전처리할 때 사용하는 개발자용 플래그입니다. 입력을 kwarg로 전달하는 것이 작동하지 않는 경우에만 사용하세요. 예를 들어,preprocess(images, masks=masks)가 권장되는 옵션이지만 일부 모델에서는 인자 우선순위 문제가 발생할 수 있습니다. 이러한 경우 대신preprocess(images, image_like_inputs={"masks": masks})를 사용할 수 있습니다. - 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) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는PILImageResamplingenum 중 하나일 수 있습니다.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, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
반환값
~image_processing_base.BatchFeature
- data (
dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등). - tensor_type (
Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.
이미지 또는 이미지 배치(batch)를 전처리합니다.
post_process_depth_estimation
< source >( outputs: DepthProDepthEstimatorOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None )
모델에서 생성된 원시 깊이 예측을 후처리합니다.
DepthProModel
class transformers.DepthProModel
< source >( config: DepthProConfig )
매개변수
- config (DepthProConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Depth Pro Model입니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → DepthProOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 DepthProImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 DepthProImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 DepthProImageProcessor를 사용합니다). - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
DepthProOutput 또는 tuple(torch.Tensor)
DepthProOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되거나 config.return_dict=False인 경우)로, DepthProConfig 및 입력에 따라 다양한 요소를 포함합니다.
DepthProModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
last_hidden_state (
torch.Tensor, shape(batch_size, n_patches_per_batch, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.features (
Union[torch.Tensor, List[torch.Tensor]], 선택 사항) — 인코더에서 생성된 특징. 단일 특징 또는 특징 목록일 수 있습니다.hidden_states (
tuple[torch.Tensor, ...], 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple[torch.Tensor, ...], 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, DepthProModel
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> model = DepthProModel.from_pretrained(checkpoint)
>>> # prepare image for the model
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... output = model(**inputs)
>>> output.last_hidden_state.shape
torch.Size([1, 35, 577, 1024])DepthProForDepthEstimation
class transformers.DepthProForDepthEstimation
< source >( config: DepthProConfiguse_fov_model = None )
매개변수
- config (DepthProConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
- use_fov_model (
bool, 선택 사항) — 시야각 모델을 사용할지 여부.
DepthPro 모델은 상단에 깊이 추정 헤드(3개의 합성곱 계층으로 구성)가 있습니다.
이 모델은 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 ) → DepthProDepthEstimatorOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 DepthProImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 DepthProImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 DepthProImageProcessor를 사용합니다). - 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를 반환할지 여부.
반환값
DepthProDepthEstimatorOutput 또는 tuple(torch.Tensor)
DepthProDepthEstimatorOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(DepthProConfig)과 입력에 따라 다양한 요소를 포함합니다.
DepthProForDepthEstimation의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.predicted_depth (
torch.Tensor, shape(batch_size, height, width), 선택 사항) — 각 픽셀에 대한 예측된 깊이.field_of_view (
torch.Tensor, shape(batch_size,), 선택 사항,use_fov_model이 제공될 때 반환됨) — 시야각 스케일러.hidden_states (
tuple[torch.Tensor, ...], 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple[torch.Tensor, ...], 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> from transformers import AutoImageProcessor, DepthProForDepthEstimation
>>> import torch
>>> 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()))
>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = DepthProForDepthEstimation.from_pretrained(checkpoint)
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
>>> model.to(device)
>>> # prepare image for the model
>>> inputs = processor(images=image, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # interpolate to original size
>>> post_processed_output = processor.post_process_depth_estimation(
... outputs, target_sizes=[(image.height, image.width)],
... )
>>> # get the field of view (fov) predictions
>>> field_of_view = post_processed_output[0]["field_of_view"]
>>> focal_length = post_processed_output[0]["focal_length"]
>>> # 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"))