# 단안 깊이 추정

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

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

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

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

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

이 가이드에서는 최첨단 제로샷 상대 깊이 추정 모델인 [Depth Anything V2](https://huggingface.co/depth-anything/Depth-Anything-V2-Large)와 절대 깊이 추정 모델인 [ZoeDepth](../model_doc/zoedepth)를 사용하여 추론을 수행하는 방법을 살펴봅니다.

호환되는 아키텍처와 체크포인트를 모두 확인하려면 [Depth Estimation](https://huggingface.co/tasks/depth-estimation) 작업 페이지를 참조하세요.

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

```bash
pip install -q -U transformers
```

## Depth estimation pipeline

깊이 추정을 지원하는 모델로 추론을 시도하는 가장 간단한 방법은 해당 [pipeline()](/docs/transformers/v5.23.0/ko/main_classes/pipelines#transformers.pipeline)을 사용하는 것입니다. [Hugging Face Hub의 체크포인트](https://huggingface.co/models?pipeline_tag=depth-estimation&sort=downloads)에서 파이프라인을 인스턴스화합니다:

```py
>>> 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)
```

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

```py
>>> 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
```

     

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

```py
>>> predictions = pipe(image)
```

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

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

```py
>>> predictions["depth"]
```

     

## 수동으로 Depth estimation 추론 수행

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

[Hugging Face Hub의 체크포인트](https://huggingface.co/models?pipeline_tag=depth-estimation&sort=downloads)에서 모델과 관련 프로세서를 로드하는 것으로 시작합니다. 여기서는 이전과 동일한 체크포인트를 사용합니다:

```py
>>> 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`를 사용하여 리사이징 및 정규화와 같은 필요한 이미지 변환을 처리하도록 모델의 이미지 입력을 준비합니다:

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

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

```py
>>> import torch

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

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

```py
>>> # 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 인수에 뒤집힌 출력을 전달함으로써 이 작업을 처리할 수 있습니다: &gt;&gt;&gt; with torch.no_grad(): ...     outputs = model(pixel_values) ...     outputs_flipped = model(pixel_values=torch.flip(inputs.pixel_values, dims=[3])) &gt;&gt;&gt; post_processed_output = image_processor.post_process_depth_estimation( ...     outputs, ...     source_sizes=[(image.height, image.width)], ...     outputs_flipped=outputs_flipped, ... )

     

