> 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-fr/traitement-dimages/segment-anything.md).

# Segment Anything

Segmentation précise d'images avec SAM de Meta sur les GPU Clore.ai

Utilisez le SAM de Meta pour une segmentation précise des images sur GPU.

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

## Louer sur CLORE.AI

1. Visitez [la place de marché CLORE.AI](https://clore.ai/marketplace)
2. Filtrez par type de GPU, VRAM et prix
3. Choisissez **À 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@<proxy-address>`

## Qu'est-ce que SAM ?

Le Segment Anything Model (SAM) peut :

* Segmenter n'importe quel objet dans les images
* Fonctionner avec des invites (points, boîtes, texte)
* Générer des masques automatiques
* Gérer n'importe quel type d'image

## Variantes de modèle

| Modèle         | VRAM | Qualité   | Vitesse |
| -------------- | ---- | --------- | ------- |
| SAM-H (énorme) | 8 Go | Meilleur  | Lent    |
| SAM-L (grand)  | 6 Go | Excellent | Moyen   |
| SAM-B (base)   | 4 Go | Bon       | Rapide  |
| SAM2           | 8GB+ | Meilleur  | Moyen   |

## Déploiement rapide

**Image Docker :**

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

**Ports :**

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

**Commande :**

```bash
pip install segment-anything gradio opencv-python && \
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth && \
python -c "
import gradio as gr
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
import cv2

sam = sam_model_registry['vit_h'](checkpoint='sam_vit_h_4b8939.pth').cuda()
predictor = SamPredictor(sam)

def segment(image, evt: gr.SelectData):
    predictor.set_image(image)
    point = np.array([[evt.index[0], evt.index[1]]])
    masks, _, _ = predictor.predict(point_coords=point, point_labels=np.array([1]))
    mask = masks[0]
    colored = np.zeros_like(image)
    colored[mask] = [255, 0, 0]
    result = cv2.addWeighted(image, 0.7, colored, 0.3, 0)
    return result

demo = gr.Interface(fn=segment, inputs=gr.Image(), outputs=gr.Image(), title='Cliquez pour segmenter')
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

## Accéder à votre service

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

1. Accédez à **Mes commandes** la page
2. Cliquez sur votre commande
3. Trouvez le `http_pub` URL (par ex., `abc123.clorecloud.net`)

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

## Installation

```bash
pip install segment-anything opencv-python
```

### Télécharger les modèles

```bash

# SAM-H (meilleure qualité)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth

# SAM-L (équilibré)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth

# SAM-B (rapide)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
```

## API Python

### Segmentation de base avec des points

```python
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np

# Charger le modèle
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

predictor = SamPredictor(sam)

# Charger l’image
image = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Définir l'image
predictor.set_image(image_rgb)

# Segmenter avec une invite de point
input_point = np.array([[500, 375]])  # coordonnées x, y
input_label = np.array([1])  # 1 = premier plan, 0 = arrière-plan

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True
)

# Obtenir le meilleur masque
best_mask = masks[np.argmax(scores)]

# Enregistrer le masque
cv2.imwrite("mask.png", best_mask.astype(np.uint8) * 255)
```

### Invite par boîte

```python

# Segmenter avec une boîte englobante
input_box = np.array([100, 100, 400, 400])  # x1, y1, x2, y2

masks, scores, _ = predictor.predict(
    box=input_box,
    multimask_output=False
)
```

### Points multiples

```python

# Plusieurs points de premier plan/arrière-plan
input_points = np.array([
    [500, 375],   # Point 1
    [550, 400],   # Point 2
    [100, 100],   # Point d'arrière-plan
])
input_labels = np.array([1, 1, 0])  # 1=premier plan, 0=arrière-plan

masks, scores, _ = predictor.predict(
    point_coords=input_points,
    point_labels=input_labels,
    multimask_output=True
)
```

### Boîte + point combinés

```python
masks, scores, _ = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    box=input_box,
    multimask_output=False
)
```

## Génération automatique de masques

Générez tous les masques possibles :

```python
from segment_anything import SamAutomaticMaskGenerator
import cv2

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

mask_generator = SamAutomaticMaskGenerator(
    model=sam,
    points_per_side=32,
    pred_iou_thresh=0.86,
    stability_score_thresh=0.92,
    crop_n_layers=1,
    crop_n_points_downscale_factor=2,
    min_mask_region_area=100
)

image = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

masks = mask_generator.generate(image_rgb)

# Chaque masque contient :

# - 'segmentation' : masque binaire

# - 'area' : surface du masque en pixels

# - 'bbox' : boîte englobante

# - 'predicted_iou' : score de qualité

# - 'stability_score' : score de stabilité

print(f"{len(masks)} masques trouvés")
```

### Visualiser tous les masques

```python
import matplotlib.pyplot as plt

def show_masks(image, masks):
    plt.figure(figsize=(20, 20))
    plt.imshow(image)

    sorted_masks = sorted(masks, key=lambda x: x['area'], reverse=True)

    for mask in sorted_masks:
        m = mask['segmentation']
        color = np.random.random(3)
        colored = np.zeros((*m.shape, 4))
        colored[m] = [*color, 0.5]
        plt.imshow(colored)

    plt.axis('off')
    plt.savefig('all_masks.png')

show_masks(image_rgb, masks)
```

## SAM 2 (dernière version)

```bash
pip install sam2
```

```python
from sam2.sam2_image_predictor import SAM2ImagePredictor

predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

with torch.inference_mode():
    predictor.set_image(image)
    masks, scores, _ = predictor.predict(
        point_coords=points,
        point_labels=labels
    )
```

## Supprimer l'arrière-plan

```python
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")
predictor = SamPredictor(sam)

def remove_background(image_path, point):
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([point]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    # Créer une image RGBA
    result = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = best_mask.astype(np.uint8) * 255

    return result

# Cliquez sur l'objet à conserver
result = remove_background("photo.jpg", [400, 300])
cv2.imwrite("no_background.png", result)
```

## Extraire l'objet

```python
def extract_object(image_path, point):
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([point]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    # Obtenir la boîte englobante
    rows = np.any(best_mask, axis=1)
    cols = np.any(best_mask, axis=0)
    y1, y2 = np.where(rows)[0][[0, -1]]
    x1, x2 = np.where(cols)[0][[0, -1]]

    # Rogner
    cropped = image[y1:y2+1, x1:x2+1]
    mask_cropped = best_mask[y1:y2+1, x1:x2+1]

    # Appliquer le masque
    result = cv2.cvtColor(cropped, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = mask_cropped.astype(np.uint8) * 255

    return result
```

## Traitement par lots

```python
import os
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
import cv2
import json

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

mask_generator = SamAutomaticMaskGenerator(sam)

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

for filename in os.listdir(input_dir):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        image = cv2.imread(os.path.join(input_dir, filename))
        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        masks = mask_generator.generate(image_rgb)

        # Enregistrer les masques au format JSON
        mask_data = []
        for i, mask in enumerate(masks):
            mask_data.append({
                'id': i,
                'area': int(mask['area']),
                'bbox': mask['bbox'],
                'score': float(mask['predicted_iou'])
            })

            # Enregistrer le masque individuel
            cv2.imwrite(
                os.path.join(output_dir, f"{filename}_mask_{i}.png"),
                mask['segmentation'].astype(np.uint8) * 255
            )

        with open(os.path.join(output_dir, f"{filename}_masks.json"), 'w') as f:
            json.dump(mask_data, f)
```

## Serveur API

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np
import json

app = FastAPI()

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")
predictor = SamPredictor(sam)

@app.post("/segment")
async def segment(file: UploadFile, x: int, y: int):
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([[x, y]]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    _, encoded = cv2.imencode('.png', best_mask.astype(np.uint8) * 255)
    return Response(content=encoded.tobytes(), media_type="image/png")
```

## Intégration avec Stable Diffusion

Utilisez les masques SAM pour l'inpainting :

```python

# Générer un masque avec SAM
predictor.set_image(image)
masks, scores, _ = predictor.predict(point_coords=point, point_labels=label)
mask = masks[np.argmax(scores)]

# Utiliser dans l'inpainting SD
from diffusers import StableDiffusionInpaintPipeline

pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting")
pipe.to("cuda")

result = pipe(
    prompt="une voiture de sport rouge",
    image=image,
    mask_image=mask
).images[0]
```

## Performances

| Modèle | Taille de l'image | GPU      | Temps   |
| ------ | ----------------- | -------- | ------- |
| SAM-H  | 1024x1024         | RTX 3090 | \~0.5s  |
| SAM-L  | 1024x1024         | RTX 3090 | \~0.3s  |
| SAM-B  | 1024x1024         | RTX 3090 | \~0,2 s |
| SAM2   | 1024x1024         | RTX 4090 | \~0.3s  |

## Optimisation de la mémoire

```python

# Pour une VRAM limitée
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")  # Utiliser un modèle plus petit

# Ou réduisez le nombre de points de génération automatique
mask_generator = SamAutomaticMaskGenerator(
    model=sam,
    points_per_side=16,  # Réduire de 32
)
```

## Dépannage

### Mémoire CUDA insuffisante

* Utilisez SAM-B au lieu de SAM-H
* Réduisez la taille de l'image avant le traitement
* Vider le cache : `torch.cuda.empty_cache()`

### Segmentation médiocre

* Ajoutez plus de points (premier plan + arrière-plan)
* Utilisez une invite par boîte pour une meilleure guidance
* Essayez multimask\_output=True et choisissez le meilleur

## Estimation des coûts

Tarifs typiques du marché CLORE.AI (en 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 40 Go | \~$0.17       | \~$4.00          | \~$0.70             |
| A100 80 Go | \~$0.25       | \~$6.00          | \~$1.00             |

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

**Économisez de l'argent :**

* Utilisez le **Spot** marché pour les travaux interrompables — environ un tiers des serveurs ont un prix spot inférieur au tarif à la demande (médiane \~13 % de remise), les autres s'alignent dessus
* Payez avec **CLORE** jetons
* Comparez les prix entre différents fournisseurs

## Étapes suivantes

* Inpainting Stable Diffusion
* [Guide ControlNet](/guides/guides_v2-fr/traitement-dimages/controlnet-advanced.md)
* [Mise à l’échelle Real-ESRGAN](/guides/guides_v2-fr/traitement-dimages/real-esrgan-upscaling.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-fr/traitement-dimages/segment-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.
