> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-ru/obrabotka-izobrazhenii/depth-anything.md).

# Depth Anything

Оценивайте глубину по одиночным изображениям с Depth Anything.

{% hint style="success" %}
Все примеры можно запускать на GPU-серверах, арендованных через [маркетплейс CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## Аренда на CLORE.AI

1. Перейдите на [маркетплейс CLORE.AI](https://clore.ai/marketplace)
2. Отфильтруйте по типу GPU, объёму VRAM и цене
3. Выберите **On-Demand** (фиксированная ставка) или **Spot** (цена ставки)
4. Настройте свой заказ:
   * Выберите Docker-образ
   * Установите порты (TCP для SSH, HTTP для веб-интерфейсов)
   * При необходимости добавьте переменные окружения
   * Введите команду запуска
5. Выберите способ оплаты: **CLORE**, **BTC**, или **USDT/USDC**
6. Создайте заказ и дождитесь развертывания

### Получите доступ к своему серверу

* Найдите данные для подключения в **Мои заказы**
* Веб-интерфейсы: используйте URL HTTP-порта
* SSH: `ssh -p <port> root@<proxy-address>`

## Что такое Depth Anything?

Depth Anything предоставляет:

* Современная оценка глубины
* Работает на любом изображении
* Не требуется стереокамера
* Быстрый инференс

## Варианты модели

| Модель               | Размер  | VRAM   | Скорость        |
| -------------------- | ------- | ------ | --------------- |
| Depth-Anything-Small | 25 млн  | 2 ГБ   | Самый быстрый   |
| Depth-Anything-Base  | 98 млн  | 4 ГБ   | Быстро          |
| Depth-Anything-Large | 335 млн | 8 ГБ   | Лучшее качество |
| Depth-Anything-V2    | Разные  | 4–8 ГБ | Последняя       |

## Быстрое развёртывание

**Docker-образ:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**Порты:**

```
22/tcp
7860/http
```

**Команда:**

```bash
pip install transformers torch gradio && \\
python depth_anything_app.py
```

## Доступ к вашему сервису

После развертывания найдите свой `http_pub` URL в **Мои заказы**:

1. Перейдите на **Мои заказы** страницу
2. Нажмите на свой заказ
3. Найдите `http_pub` URL (например, `abc123.clorecloud.net`)

Используйте `https://YOUR_HTTP_PUB_URL` вместо `localhost` в примерах ниже.

## Установка

```bash
pip install transformers torch
pip install opencv-python pillow
```

## Базовое использование

```python
from transformers import pipeline
from PIL import Image

# Загрузить конвейер оценки глубины
pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

# Оценить глубину
image = Image.open("photo.jpg")
depth = pipe(image)

# Сохранить карту глубины
depth["depth"].save("depth_map.png")
```

## Depth Anything V2

```python
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
import torch
from PIL import Image
import numpy as np

# Загрузить модель
processor = AutoImageProcessor.from_pretrained("depth-anything/Depth-Anything-V2-Large-hf")
model = AutoModelForDepthEstimation.from_pretrained("depth-anything/Depth-Anything-V2-Large-hf")
model.to("cuda")

# Обработать изображение
image = Image.open("photo.jpg")
inputs = processor(images=image, return_tensors="pt").to("cuda")

with torch.no_grad():
    outputs = model(**inputs)
    predicted_depth = outputs.predicted_depth

# Интерполировать до исходного размера
prediction = torch.nn.functional.interpolate(
    predicted_depth.unsqueeze(1),
    size=image.size[::-1],
    mode="bicubic",
    align_corners=False,
)

# Преобразовать в numpy
depth = prediction.squeeze().cpu().numpy()
depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255
depth = depth.astype(np.uint8)

# Сохранить
Image.fromarray(depth).save("depth.png")
```

## Цветная карта глубины

```python
import cv2
import numpy as np
from PIL import Image

def colorize_depth(depth_array, colormap=cv2.COLORMAP_INFERNO):
    # Нормализовать до 0–255
    depth_normalized = cv2.normalize(depth_array, None, 0, 255, cv2.NORM_MINMAX)
    depth_uint8 = depth_normalized.astype(np.uint8)

    # Применить цветовую карту
    colored = cv2.applyColorMap(depth_uint8, colormap)

    return Image.fromarray(cv2.cvtColor(colored, cv2.COLOR_BGR2RGB))

# Использование
depth_colored = colorize_depth(depth)
depth_colored.save("depth_colored.png")
```

## Пакетная обработка

```python
from transformers import pipeline
from PIL import Image
import os

pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

input_dir = "./images"
output_dir = "./depth_maps"
os.makedirs(output_dir, exist_ok=True)

for filename in os.listdir(input_dir):
    if filename.endswith(('.jpg', '.png', '.jpeg')):
        image_path = os.path.join(input_dir, filename)
        image = Image.open(image_path)

        # Получить глубину
        depth = pipe(image)

        # Сохранить
        output_path = os.path.join(output_dir, f"depth_{filename}")
        depth["depth"].save(output_path)
        print(f"Processed: {filename}")
```

## Интерфейс Gradio

```python
import gradio as gr
from transformers import pipeline
import cv2
import numpy as np

pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

def estimate_depth(image, colormap):
    # Получить глубину
    result = pipe(image)
    depth = np.array(result["depth"])

    # Раскрасить
    depth_normalized = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)

    colormaps = {
        "Inferno": cv2.COLORMAP_INFERNO,
        "Viridis": cv2.COLORMAP_VIRIDIS,
        "Plasma": cv2.COLORMAP_PLASMA,
        "Magma": cv2.COLORMAP_MAGMA,
        "Jet": cv2.COLORMAP_JET
    }

    colored = cv2.applyColorMap(depth_normalized, colormaps[colormap])
    colored = cv2.cvtColor(colored, cv2.COLOR_BGR2RGB)

    return result["depth"], colored

demo = gr.Interface(
    fn=estimate_depth,
    inputs=[
        gr.Image(type="pil", label="Входное изображение"),
        gr.Dropdown(
            ["Inferno", "Viridis", "Plasma", "Magma", "Jet"],
            value="Inferno",
            label="Цветовая карта"
        )
    ],
    outputs=[
        gr.Image(label="Карта глубины (градации серого)"),
        gr.Image(label="Карта глубины (цветная)")
    ],
    title="Depth Anything — оценка глубины"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## API-сервер

```python
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import Response
from transformers import pipeline
from PIL import Image
import io
import numpy as np
import cv2

app = FastAPI()

pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

@app.post("/depth")
async def estimate_depth(image: UploadFile = File(...), colored: bool = True):
    # Загрузить изображение
    img = Image.open(io.BytesIO(await image.read()))

    # Оценить глубину
    result = pipe(img)
    depth = np.array(result["depth"])

    if colored:
        depth_normalized = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
        depth_img = cv2.applyColorMap(depth_normalized, cv2.COLORMAP_INFERNO)
        depth_img = cv2.cvtColor(depth_img, cv2.COLOR_BGR2RGB)
    else:
        depth_img = depth

    # Преобразовать в байты
    output = Image.fromarray(depth_img)
    buffer = io.BytesIO()
    output.save(buffer, format="PNG")

    return Response(content=buffer.getvalue(), media_type="image/png")

# Запуск: uvicorn server:app --host 0.0.0.0 --port 8000
```

## Генерация 3D-облака точек

```python
import numpy as np
import open3d as o3d
from PIL import Image

def depth_to_pointcloud(rgb_image, depth_map, focal_length=500):
    """Преобразовать RGB-изображение и карту глубины в 3D-облако точек"""
    rgb = np.array(rgb_image)
    depth = np.array(depth_map)

    # Получить размеры изображения
    height, width = depth.shape

    # Создать сетку
    u = np.arange(width)
    v = np.arange(height)
    u, v = np.meshgrid(u, v)

    # Преобразовать в 3D-координаты
    z = depth.astype(float)
    x = (u - width / 2) * z / focal_length
    y = (v - height / 2) * z / focal_length

    # Собрать координаты
    points = np.stack([x, y, z], axis=-1).reshape(-1, 3)
    colors = rgb.reshape(-1, 3) / 255.0

    # Создать облако точек
    pcd = o3d.geometry.PointCloud()
    pcd.points = o3d.utility.Vector3dVector(points)
    pcd.colors = o3d.utility.Vector3dVector(colors)

    return pcd

# Использование
rgb = Image.open("photo.jpg")
depth = pipe(rgb)["depth"]

pcd = depth_to_pointcloud(rgb, depth)
o3d.io.write_point_cloud("output.ply", pcd)
```

## Сценарии использования

### Эффект 3D-фото

```python
def create_3d_photo(image, depth, shift=20):
    """Создать эффект параллакса для 3D-фотографий"""
    import cv2
    import numpy as np

    img = np.array(image)
    depth_arr = np.array(depth)

    # Нормализовать глубину
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Создать сдвинутую версию
    shifted = np.zeros_like(img)
    for y in range(img.shape[0]):
        for x in range(img.shape[1]):
            offset = int(shift * depth_norm[y, x])
            new_x = min(x + offset, img.shape[1] - 1)
            shifted[y, new_x] = img[y, x]

    return Image.fromarray(shifted)
```

### Размытие фона (портретный режим)

```python
def portrait_mode(image, depth, blur_strength=25):
    import cv2
    import numpy as np

    img = np.array(image)
    depth_arr = np.array(depth)

    # Нормализовать глубину
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Создать маску размытия (фон = большая глубина = большее размытие)
    blur_mask = depth_norm

    # Применить размытие
    blurred = cv2.GaussianBlur(img, (blur_strength, blur_strength), 0)

    # Смешать на основе глубины
    mask_3d = np.stack([blur_mask] * 3, axis=-1)
    result = (img * (1 - mask_3d) + blurred * mask_3d).astype(np.uint8)

    return Image.fromarray(result)
```

## Производительность

| Модель    | GPU      | Время на изображение |
| --------- | -------- | -------------------- |
| Маленькая | RTX 3060 | \~50 мс              |
| Базовая   | RTX 3060 | \~100 мс             |
| Large     | RTX 3090 | \~150 мс             |
| Large     | RTX 4090 | \~80 мс              |
| V2-Large  | RTX 4090 | \~100 мс             |

## Устранение неполадок

### Плохое качество глубины

* Используйте более крупный вариант модели
* Убедитесь в хорошем качестве изображения
* Проверьте наличие отражающих поверхностей

### Проблемы с памятью

* Используйте более компактную версию модели
* Уменьшите разрешение изображения
* Включите инференс fp16

### Медленная обработка

* Используйте более маленькую модель
* По возможности выполняйте пакетную обработку
* Используйте инференс на GPU

## Оценка стоимости

Типичные цены на маркетплейсе CLORE.AI (по состоянию на 2024 год):

| GPU        | Почасовая ставка | Дневная ставка | 4-часовая сессия |
| ---------- | ---------------- | -------------- | ---------------- |
| RTX 3060   | \~$0.03          | \~$0.70        | \~$0.12          |
| RTX 3090   | \~$0.06          | \~$1.50        | \~$0.25          |
| RTX 4090   | \~$0.10          | \~$2.30        | \~$0.40          |
| A100 40 ГБ | \~$0.17          | \~$4.00        | \~$0.70          |
| A100 80 ГБ | \~$0.25          | \~$6.00        | \~$1.00          |

*Цены зависят от провайдера и спроса. Проверьте* [*маркетплейс CLORE.AI*](https://clore.ai/marketplace) *актуальные тарифы.*

**Сэкономьте деньги:**

* Используйте **Spot** рынок для прерываемых задач — примерно треть серверов оценивает spot-цены ниже on-demand (медиана \~13% скидки), остальные совпадают с ними
* Платите **CLORE** токенами
* Сравните цены у разных провайдеров

## Дальнейшие шаги

* [ControlNet](/guides/guides_v2-ru/obrabotka-izobrazhenii/controlnet-advanced.md) - Используйте глубину для управления
* [Segment Anything](/guides/guides_v2-ru/obrabotka-izobrazhenii/segment-anything.md) - Сегментация объектов
* [3D-генерация](/guides/guides_v2-ru/generaciya-3d/triposr.md) - Глубина видео


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-ru/obrabotka-izobrazhenii/depth-anything.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
