Transformers documentation

단안 깊이 추정

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

단안 깊이 추정

Monocular depth estimation은 단일 이미지로부터 장면의 깊이 정보를 예측하는 컴퓨터 비전 작업입니다. 다시 말해, 단일 카메라 관점에서 장면 내 객체까지의 거리를 추정하는 과정입니다.

Monocular depth estimation은 3D 재구성, 증강 현실, 자율 주행, 로봇공학 등 다양한 분야에 적용됩니다. 장면 내 객체와 해당 깊이 정보 사이의 복잡한 관계를 모델이 이해해야 하므로 어려운 작업이며, 조명 조건, 가림(occlusion), 질감 등의 요인에 영향을 받을 수 있습니다.

주요 깊이 추정 범주는 두 가지입니다:

  • 절대 깊이 추정: 이 작업 변형은 카메라로부터 정확한 깊이 측정을 제공하는 것을 목표로 합니다. 이 용어는 미터 또는 피트와 같은 정확한 단위로 깊이를 제공하는 metric depth estimation과 상호 교환적으로 사용됩니다. 절대 깊이 추정 모델은 실제 거리를 나타내는 수치 값을 가진 깊이 맵을 출력합니다.

  • 상대적 깊이 추정: 상대적 깊이 추정은 정확한 측정을 제공하지 않고 장면 내 객체나 점의 깊이 순서를 예측하는 것을 목표로 합니다. 이러한 모델은 A와 B에 대한 실제 거리 없이 장면의 어떤 부분이 서로 상대적으로 더 가깝거나 먼지를 나타내는 깊이 맵을 출력합니다.

이 가이드에서는 최첨단 제로샷 상대 깊이 추정 모델인 Depth Anything V2와 절대 깊이 추정 모델인 ZoeDepth를 사용하여 추론을 수행하는 방법을 살펴봅니다.

호환되는 아키텍처와 체크포인트를 모두 확인하려면 Depth Estimation 작업 페이지를 참조하세요.

시작하기 전에, 최신 버전의 Transformers를 설치해야 합니다:

pip install -q -U transformers

Depth estimation pipeline

깊이 추정을 지원하는 모델로 추론을 시도하는 가장 간단한 방법은 해당 pipeline()을 사용하는 것입니다. Hugging Face Hub의 체크포인트에서 파이프라인을 인스턴스화합니다:

>>> from transformers import pipeline
from accelerate import Accelerator
>>> import torch
>>> device = Accelerator().device
>>> checkpoint = "depth-anything/Depth-Anything-V2-base-hf"
>>> pipe = pipeline("depth-estimation", model=checkpoint, device=device)

다음으로, 분석할 이미지를 선택합니다:

>>> from PIL import Image
>>> import requests

>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image
Photo of a bee

이미지를 파이프라인에 전달합니다.

>>> predictions = pipe(image)

pipeline은 두 개의 항목을 가진 딕셔너리를 반환합니다. 첫 번째 항목인 predicted_depth는 각 픽셀에 대한 깊이를 미터 단위로 표현한 값이 포함된 텐서입니다. 두 번째 항목인 depth는 깊이 추정 결과를 시각화한 PIL 이미지입니다.

시각화된 결과를 살펴보겠습니다:

>>> predictions["depth"]
Depth estimation visualization

수동으로 Depth estimation 추론 수행

이제 depth estimation 파이프라인 사용법을 확인했으니, 동일한 결과를 수동으로 재현하는 방법을 살펴보겠습니다.

Hugging Face Hub의 체크포인트에서 모델과 관련 프로세서를 로드하는 것으로 시작합니다. 여기서는 이전과 동일한 체크포인트를 사용합니다:

>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation

>>> checkpoint = "Intel/zoedepth-nyu-kitti"

>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = AutoModelForDepthEstimation.from_pretrained(checkpoint).to(device)

image_processor를 사용하여 모델에 전달할 이미지 입력을 준비합니다. image_processor는 리사이징과 정규화 등 필요한 이미지 변환을 처리합니다:

>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values.to(device)

준비된 입력을 모델에 전달합니다:

>>> import torch

>>> with torch.no_grad():
...     outputs = model(pixel_values)

결과를 후처리하여 패딩을 제거하고, 깊이 맵을 원래 이미지 크기에 맞게 리사이즈해 보겠습니다. post_process_depth_estimation은 "predicted_depth"를 포함하는 dict 목록을 출력합니다.

>>> # ZoeDepth dynamically pads the input image. Thus we pass the original image size as argument
>>> # to `post_process_depth_estimation` to remove the padding and resize to original dimensions.
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     source_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
>>> depth = Image.fromarray(depth.astype("uint8"))

원래 구현에서 ZoeDepth 모델은 원본 이미지와 뒤집힌 이미지 모두에 대해 추론을 수행한 후 결과를 평균화합니다. post_process_depth_estimation 함수는 뒤집힌 출력 결과를 선택적 outputs_flipped 인수로 전달함으로써 이 작업을 처리해 줍니다:

>>> with torch.no_grad():
...     outputs = model(pixel_values)
...     outputs_flipped = model(pixel_values=torch.flip(inputs.pixel_values, dims=[3]))
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     source_sizes=[(image.height, image.width)],
...     outputs_flipped=outputs_flipped,
... )
Depth estimation visualization
Update on GitHub