# Depth Anything

Estimez la profondeur à partir d'images uniques avec Depth Anything.

{% hint style="success" %}
Tous les exemples peuvent être exécutés sur des serveurs GPU loués via [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Location sur CLORE.AI

1. Visitez [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrer par type de GPU, VRAM et prix
3. Choisir **À la demande** (tarif fixe) ou **Spot** (prix d'enchère)
4. Configurez votre commande :
   * Sélectionnez l'image Docker
   * Définissez les ports (TCP pour SSH, HTTP pour les interfaces web)
   * Ajoutez des variables d'environnement si nécessaire
   * Entrez la commande de démarrage
5. Sélectionnez le paiement : **CLORE**, **BTC**, ou **USDT/USDC**
6. Créez la commande et attendez le déploiement

### Accédez à votre serveur

* Trouvez les détails de connexion dans **Mes commandes**
* Interfaces Web : utilisez l'URL du port HTTP
* SSH : `ssh -p <port> root@<adresse-proxy>`

## Qu'est-ce que Depth Anything ?

Depth Anything fournit :

* Estimation de profondeur à la pointe
* Fonctionne sur n'importe quelle image
* Aucune caméra stéréo nécessaire
* Inférence rapide

## Variantes de modèle

| Modèle               | Taille | VRAM  | Vitesse           |
| -------------------- | ------ | ----- | ----------------- |
| Depth-Anything-Small | 25M    | 2Go   | Le plus rapide    |
| Depth-Anything-Base  | 98M    | 4 Go  | Rapide            |
| Depth-Anything-Large | 335M   | 8 Go  | Meilleure qualité |
| Depth-Anything-V2    | Divers | 4-8Go | Dernier           |

## Déploiement rapide

**Image Docker :**

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

**Ports :**

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

**Commande :**

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

## Accéder à votre service

Après le déploiement, trouvez votre `http_pub` URL dans **Mes commandes**:

1. Aller à la **Mes commandes** page
2. Cliquez sur votre commande
3. Trouvez l' `http_pub` URL (par ex., `abc123.clorecloud.net`)

Utilisez `https://VOTRE_HTTP_PUB_URL` au lieu de `localhost` dans les exemples ci-dessous.

## Installation

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

## Utilisation de base

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

# Charger le pipeline d'estimation de profondeur
pipe = pipeline(
    task="depth-estimation",
    model="LiheYoung/depth-anything-large-hf",
    device="cuda"
)

# Estimer la profondeur
image = Image.open("photo.jpg")
depth = pipe(image)

# Enregistrer la carte de profondeur
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

# Charger le modèle
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")

# Traiter l'image
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

# Interpoler à la taille d'origine
prediction = torch.nn.functional.interpolate(
    predicted_depth.unsqueeze(1),
    size=image.size[::-1],
    mode="bicubic",
    align_corners=False,
)

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

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

## Carte de profondeur colorisée

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

def colorize_depth(depth_array, colormap=cv2.COLORMAP_INFERNO):
    # Normaliser entre 0 et 255
    depth_normalized = cv2.normalize(depth_array, None, 0, 255, cv2.NORM_MINMAX)
    depth_uint8 = depth_normalized.astype(np.uint8)

    # Appliquer la palette de couleurs
    colored = cv2.applyColorMap(depth_uint8, colormap)

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

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

## Traitement par lots

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

        # Obtenir la profondeur
        depth = pipe(image)

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

## Interface 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):
    # Obtenir la profondeur
    result = pipe(image)
    depth = np.array(result["depth"])

    # Coloriser
    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="Image d'entrée"),
        gr.Dropdown(
            ["Inferno", "Viridis", "Plasma", "Magma", "Jet"],
            value="Inferno",
            label="Palette de couleurs"
        )
    ],
    outputs=[
        gr.Image(label="Carte de profondeur (Niveaux de gris)"),
        gr.Image(label="Carte de profondeur (Colorisée)")
    ],
    title="Depth Anything - Estimation de profondeur"
)

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

## Serveur 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):
    # Charger l'image
    img = Image.open(io.BytesIO(await image.read()))

    # Estimer la profondeur
    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

    # Convertir en octets
    output = Image.fromarray(depth_img)
    buffer = io.BytesIO()
    output.save(buffer, format="PNG")

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

# Lancer : uvicorn server:app --host 0.0.0.0 --port 8000
```

## Génération de nuage de points 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):
    """Convertir une image RVB et une carte de profondeur en nuage de points 3D"""
    rgb = np.array(rgb_image)
    depth = np.array(depth_map)

    # Obtenir les dimensions de l'image
    height, width = depth.shape

    # Créer une grille
    u = np.arange(width)
    v = np.arange(height)
    u, v = np.meshgrid(u, v)

    # Convertir en coordonnées 3D
    z = depth.astype(float)
    x = (u - width / 2) * z / focal_length
    y = (v - height / 2) * z / focal_length

    # Empiler les coordonnées
    points = np.stack([x, y, z], axis=-1).reshape(-1, 3)
    colors = rgb.reshape(-1, 3) / 255.0

    # Créer le nuage de points
    pcd = o3d.geometry.PointCloud()
    pcd.points = o3d.utility.Vector3dVector(points)
    pcd.colors = o3d.utility.Vector3dVector(colors)

    return pcd

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

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

## Cas d'utilisation

### Effet photo 3D

```python
def create_3d_photo(image, depth, shift=20):
    """Créer un effet de parallaxe pour des photos 3D"""
    import cv2
    import numpy as np

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

    # Normaliser la profondeur
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Créer une version décalée
    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)
```

### Flou d'arrière-plan (Mode Portrait)

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

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

    # Normaliser la profondeur
    depth_norm = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min())

    # Créer un masque de flou (arrière-plan = grande profondeur = plus de flou)
    blur_mask = depth_norm

    # Appliquer le flou
    blurred = cv2.GaussianBlur(img, (blur_strength, blur_strength), 0)

    # Mélanger en fonction de la profondeur
    mask_3d = np.stack([blur_mask] * 3, axis=-1)
    result = (img * (1 - mask_3d) + blurred * mask_3d).astype(np.uint8)

    return Image.fromarray(result)
```

## Performances

| Modèle   | GPU      | Temps par image |
| -------- | -------- | --------------- |
| Faible   | RTX 3060 | \~50ms          |
| Base     | RTX 3060 | \~100ms         |
| Large    | RTX 3090 | \~150ms         |
| Large    | RTX 4090 | \~80ms          |
| V2-Large | RTX 4090 | \~100ms         |

## Dépannage

### Mauvaise qualité de profondeur

* Utiliser une variante de modèle plus grande
* Assurer une bonne qualité d'image
* Vérifier la présence de surfaces réfléchissantes

### Problèmes de mémoire

* Utiliser une variante de modèle plus petite
* Réduire la résolution de l'image
* Activer l'inférence en fp16

### Traitement lent

* Utiliser un modèle plus petit
* Traiter par lots si possible
* Utiliser l'inférence GPU

## Estimation des coûts

Tarifs typiques du marché CLORE.AI (à partir de 2024) :

| GPU       | Tarif horaire | Tarif journalier | Session de 4 heures |
| --------- | ------------- | ---------------- | ------------------- |
| 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             |

*Les prix varient selon le fournisseur et la demande. Vérifiez* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *pour les tarifs actuels.*

**Économisez de l'argent :**

* Utilisez **Spot** market pour les charges de travail flexibles (souvent 30-50 % moins cher)
* Payer avec **CLORE** jetons
* Comparer les prix entre différents fournisseurs

## Prochaines étapes

* [ControlNet](https://docs.clore.ai/guides/guides_v2-fr/traitement-dimages/controlnet-advanced) - Utiliser la profondeur pour le contrôle
* [Segmenter tout](https://docs.clore.ai/guides/guides_v2-fr/traitement-dimages/segment-anything) - Segmentation d'objets
* [Génération 3D](https://docs.clore.ai/guides/guides_v2-fr/generation-3d/triposr) - Profondeur vidéo
