# Depth Anything

Schätzen Sie Tiefe aus einzelnen Bildern mit Depth Anything.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die über [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Mieten auf CLORE.AI

1. Besuchen Sie [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Nach GPU-Typ, VRAM und Preis filtern
3. Wählen **On-Demand** (Festpreis) oder **Spot** (Gebotspreis)
4. Konfigurieren Sie Ihre Bestellung:
   * Docker-Image auswählen
   * Ports festlegen (TCP für SSH, HTTP für Web-UIs)
   * Umgebungsvariablen bei Bedarf hinzufügen
   * Startbefehl eingeben
5. Zahlung auswählen: **CLORE**, **BTC**, oder **USDT/USDC**
6. Bestellung erstellen und auf Bereitstellung warten

### Zugriff auf Ihren Server

* Verbindungsdetails finden Sie in **Meine Bestellungen**
* Webschnittstellen: Verwenden Sie die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist Depth Anything?

Depth Anything bietet:

* Aktuelle Zustand-der-Technik Tiefenschätzung
* Funktioniert mit jedem Bild
* Keine Stereo-Kamera erforderlich
* Schnelle Inferenz

## Modellvarianten

| Modell               | Größe        | VRAM  | Geschwindigkeit |
| -------------------- | ------------ | ----- | --------------- |
| Depth-Anything-Small | 25M          | 2GB   | Am schnellsten  |
| Depth-Anything-Base  | 98M          | 4GB   | Schnell         |
| Depth-Anything-Large | 335M         | 8GB   | Beste Qualität  |
| Depth-Anything-V2    | Verschiedene | 4-8GB | Neueste         |

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
```

**Ports:**

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

**Befehl:**

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

## Zugriff auf Ihren Dienst

Nach der Bereitstellung finden Sie Ihre `http_pub` URL in **Meine Bestellungen**:

1. Gehen Sie zur **Meine Bestellungen** Seite
2. Klicken Sie auf Ihre Bestellung
3. Finden Sie die `http_pub` URL (z. B., `abc123.clorecloud.net`)

Verwenden Sie `https://IHRE_HTTP_PUB_URL` anstelle von `localhost` in den Beispielen unten.

## Installation

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

## Grundlegende Verwendung

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

# Lade Tiefenschätzungs-Pipeline
pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

# Schätze Tiefe
image = Image.open("photo.jpg")
depth = pipe(image)

# Speichere Tiefenkarte
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

# Modell laden
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")

# Verarbeite Bild
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

# Interpoliere auf Originalgröße
prediction = torch.nn.functional.interpolate(
    predicted_depth.unsqueeze(1),
    size=image.size[::-1],
    mode="bicubic",
    align_corners=False,
)

# Konvertiere zu numpy
depth = prediction.squeeze().cpu().numpy()
depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255
depth = depth.astype(np.uint8)

# Speichern
Image.fromarray(depth).save("depth.png")
```

## Farbige Tiefenkarte

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

def colorize_depth(depth_array, colormap=cv2.COLORMAP_INFERNO):
    # Normalisiere auf 0-255
    depth_normalized = cv2.normalize(depth_array, None, 0, 255, cv2.NORM_MINMAX)
    depth_uint8 = depth_normalized.astype(np.uint8)

    # Wende Colormap an
    colored = cv2.applyColorMap(depth_uint8, colormap)

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

# Verwendung
depth_colored = colorize_depth(depth)
depth_colored.save("depth_colored.png")
```

## Batch-Verarbeitung

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

        # Hole Tiefe
        depth = pipe(image)

        # Speichern
        output_path = os.path.join(output_dir, f"depth_{filename}")
        depth["depth"].save(output_path)
        print(f"Processed: {filename}")
```

## Gradio-Oberfläche

```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):
    # Hole Tiefe
    result = pipe(image)
    depth = np.array(result["depth"])

    # Kolorieren
    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="Eingabebild"),
        gr.Dropdown(
            ["Inferno", "Viridis", "Plasma", "Magma", "Jet"],
            value="Inferno",
            label="Farbkarte"
        )
    ],
    outputs=[
        gr.Image(label="Tiefenkarte (Graustufen)"),
        gr.Image(label="Tiefenkarte (Farbig)")
    ],
    title="Depth Anything - Tiefenschätzung"
)

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

## API-Server

```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):
    # Bild laden
    img = Image.open(io.BytesIO(await image.read()))

    # Schätze Tiefe
    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

    # Konvertiere zu Bytes
    output = Image.fromarray(depth_img)
    buffer = io.BytesIO()
    output.save(buffer, format="PNG")

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

# Ausführen: uvicorn server:app --host 0.0.0.0 --port 8000
```

## Erzeugung von 3D-Punktwolken

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

def depth_to_pointcloud(rgb_image, depth_map, focal_length=500):
    """Konvertiere RGB-Bild und Tiefenkarte in eine 3D-Punktwolke"""
    rgb = np.array(rgb_image)
    depth = np.array(depth_map)

    # Hole Bilddimensionen
    height, width = depth.shape

    # Erstelle Meshgrid
    u = np.arange(width)
    v = np.arange(height)
    u, v = np.meshgrid(u, v)

    # Konvertiere zu 3D-Koordinaten
    z = depth.astype(float)
    x = (u - width / 2) * z / focal_length
    y = (v - height / 2) * z / focal_length

    # Staple Koordinaten
    points = np.stack([x, y, z], axis=-1).reshape(-1, 3)
    colors = rgb.reshape(-1, 3) / 255.0

    # Erstelle Punktwolke
    pcd = o3d.geometry.PointCloud()
    pcd.points = o3d.utility.Vector3dVector(points)
    pcd.colors = o3d.utility.Vector3dVector(colors)

    return pcd

# Verwendung
rgb = Image.open("photo.jpg")
depth = pipe(rgb)["depth"]

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

## Anwendungsfälle

### 3D-Foto-Effekt

```python
def create_3d_photo(image, depth, shift=20):
    """Erzeuge Parallaxeeffekt für 3D-Fotos"""
    import cv2
    import numpy as np

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

    # Normalisiere Tiefe
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Erstelle verschobene Version
    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)
```

### Hintergrundunschärfe (Porträtmodus)

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

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

    # Normalisiere Tiefe
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Erstelle Unschärfemaske (Hintergrund = hohe Tiefe = mehr Unschärfe)
    blur_mask = depth_norm

    # Wende Unschärfe an
    blurred = cv2.GaussianBlur(img, (blur_strength, blur_strength), 0)

    # Mische basierend auf Tiefe
    mask_3d = np.stack([blur_mask] * 3, axis=-1)
    result = (img * (1 - mask_3d) + blurred * mask_3d).astype(np.uint8)

    return Image.fromarray(result)
```

## Leistung

| Modell   | GPU      | Zeit pro Bild |
| -------- | -------- | ------------- |
| Klein    | RTX 3060 | \~50ms        |
| Basis    | RTX 3060 | \~100ms       |
| Large    | RTX 3090 | \~150ms       |
| Large    | RTX 4090 | \~80ms        |
| V2-Large | RTX 4090 | \~100ms       |

## Fehlerbehebung

### Schlechte Tiefenqualität

* Verwende größere Modellvariante
* Sichere gute Bildqualität
* Prüfe auf reflektierende Flächen

### Speicherprobleme

* Verwende kleinere Modellvariante
* Reduziere Bildauflösung
* Aktiviere fp16-Inferenz

### Langsame Verarbeitung

* Kleineres Modell verwenden
* Verarbeite im Batch, wenn möglich
* Verwende GPU-Inferenz

## Kostenabschätzung

Typische CLORE.AI-Marktplatztarife (Stand 2024):

| GPU       | Stundensatz | Tagessatz | 4-Stunden-Sitzung |
| --------- | ----------- | --------- | ----------------- |
| 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 40GB | \~$0.17     | \~$4.00   | \~$0.70           |
| A100 80GB | \~$0.25     | \~$6.00   | \~$1.00           |

*Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *auf aktuelle Preise.*

**Geld sparen:**

* Verwenden Sie **Spot** Markt für flexible Workloads (oft 30–50% günstiger)
* Bezahlen mit **CLORE** Token
* Preise bei verschiedenen Anbietern vergleichen

## Nächste Schritte

* [ControlNet](https://docs.clore.ai/guides/guides_v2-de/bildverarbeitung/controlnet-advanced) - Verwende Tiefe zur Kontrolle
* [Segmentiere alles](https://docs.clore.ai/guides/guides_v2-de/bildverarbeitung/segment-anything) - Objektsegmentierung
* [3D-Generierung](https://docs.clore.ai/guides/guides_v2-de/3d-generierung/triposr) - Video-Tiefe
