> 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-de/gesicht-and-identitat/instantid.md).

# InstantID

Generiere Bilder mit jeder Gesichtsidentität aus einem Referenzfoto

Erzeugen Sie Bilder mit jeder beliebigen Gesichtsidentität – nur mit einem Referenzfoto.

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

## Mieten auf CLORE.AI

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

### Greife auf deinen Server zu

* Verbindungsdetails finden in **Meine Bestellungen**
* Web-Oberflächen: Verwende die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist InstantID?

InstantID bewahrt die Gesichtsidentität:

* Beliebiges Referenzgesicht verwenden
* Zero-Shot – kein Training erforderlich
* Funktioniert mit jedem Stil/jedem Prompt
* Besser als LoRA-Training

## Anforderungen

| Modus         | VRAM  | Empfohlen |
| ------------- | ----- | --------- |
| Einfach       | 12 GB | RTX 4080  |
| Hohe Qualität | 16 GB | RTX 4090  |
| Mit Pose      | 16GB+ | RTX 4090  |

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

```bash
pip install diffusers transformers accelerate opencv-python insightface onnxruntime-gpu && \\
huggingface-cli download InstantX/InstantID --local-dir ./checkpoints && \\
python instantid_app.py
```

## Auf deinen Dienst zugreifen

Nach der Bereitstellung findest du deine `http_pub` URL in **Meine Bestellungen**:

1. Gehe zu **Meine Bestellungen** Seite
2. Klicke auf deine Bestellung
3. Finde die `http_pub` URL (z. B. `abc123.clorecloud.net`)

Verwende `https://YOUR_HTTP_PUB_URL` anstelle von `localhost` in den folgenden Beispielen.

## Installation

```bash
pip install diffusers transformers accelerate
pip install opencv-python insightface onnxruntime-gpu
pip install huggingface_hub

# Modelle herunterladen
huggingface-cli download InstantX/InstantID --local-dir ./checkpoints
```

## Grundlegende Verwendung

```python
import torch
import cv2
import numpy as np
from PIL import Image
from diffusers import StableDiffusionXLPipeline, DDIMScheduler
from insightface.app import FaceAnalysis

# Gesichtsanalysator initialisieren
app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))

# Pipeline laden
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16
).to("cuda")

# InstantID-Komponenten laden
from diffusers import ControlNetModel

controlnet = ControlNetModel.from_pretrained(
    "./checkpoints/ControlNetModel",
    torch_dtype=torch.float16
)

# IP-Adapter für das Gesicht laden
pipe.load_ip_adapter(
    "./checkpoints",
    subfolder="",
    weight_name="ip-adapter.bin"
)

# Referenzgesicht verarbeiten
face_image = cv2.imread("reference_face.jpg")
faces = app.get(face_image)
face_emb = faces[0].normed_embedding

# Mit Gesichtsidentität generieren
image = pipe(
    prompt="portrait of a person as an astronaut, space background",
    negative_prompt="hässlich, verschwommen, schlechte Qualität",
    ip_adapter_image_embeds=[torch.tensor(face_emb).unsqueeze(0)],
    num_inference_steps=30,
    guidance_scale=7.5
).images[0]

image.save("output.png")
```

## Diffusers-Pipeline verwenden

```python
from diffusers import StableDiffusionXLInstantIDPipeline, DDIMScheduler
from insightface.app import FaceAnalysis
import torch
import cv2

# Gesichtsanalysator laden
app = FaceAnalysis(name='antelopev2', providers=['CUDAExecutionProvider'])
app.prepare(ctx_id=0)

# Pipeline laden
pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet="./checkpoints/ControlNetModel",
    torch_dtype=torch.float16
).to("cuda")

pipe.load_ip_adapter_instantid("./checkpoints/ip-adapter.bin")

# Face-Embedding abrufen
face_image = cv2.imread("face.jpg")
face_info = app.get(face_image)[0]

face_emb = face_info.normed_embedding
face_kps = face_info.kps

# Generieren
image = pipe(
    prompt="Aquarell-Porträtmalerei, künstlerisch",
    face_emb=face_emb,
    face_kps=face_kps,
    num_inference_steps=30
).images[0]

image.save("portrait.png")
```

## Stilbeispiele

### Professionelles Headshot

```python
prompt = "professionelles Corporate-Headshot, Studiobeleuchtung, grauer Hintergrund, Geschäftskleidung"
negative = "Cartoon, Anime, Illustration, verschwommen"
```

### Künstlerisches Porträt

```python
prompt = "Ölgemälde-Porträt im Stil von Rembrandt, dramatische Beleuchtung, Museumsqualität"
negative = "Foto, realistisch, modern"
```

### Fantasy-Charakter

```python
prompt = "Fantasy-Elfencharakter, spitze Ohren, magischer Waldhintergrund, ätherische Beleuchtung"
negative = "menschliche Ohren, moderne Kleidung, realistisch"
```

### Anime-Stil

```python
prompt = "Anime-Charakterporträt, Studio-Ghibli-Stil, detailreich, schön"
negative = "realistisch, Foto, 3D-Render"
```

## Mit Posensteuerung

```python
from diffusers.utils import load_image

# Posenreferenz laden
pose_image = load_image("pose_reference.jpg")

# Mit Gesicht UND Pose generieren
image = pipe(
    prompt="Person in Aktionspose, dynamisch, hohe Qualität",
    face_emb=face_emb,
    face_kps=face_kps,
    image=pose_image,  # Posenreferenz
    controlnet_conditioning_scale=0.8,
    num_inference_steps=30
).images[0]
```

## Gradio-Oberfläche

```python
import gradio as gr
import torch
import cv2
import numpy as np
from diffusers import StableDiffusionXLInstantIDPipeline
from insightface.app import FaceAnalysis

app = FaceAnalysis(name='antelopev2', providers=['CUDAExecutionProvider'])
app.prepare(ctx_id=0)

pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet="./checkpoints/ControlNetModel",
    torch_dtype=torch.float16
).to("cuda")

pipe.load_ip_adapter_instantid("./checkpoints/ip-adapter.bin")

def generate(face_image, prompt, negative_prompt, strength, steps):
    # In cv2-Format konvertieren
    face_cv = cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR)

    # Gesichtsinfo abrufen
    faces = app.get(face_cv)
    if len(faces) == 0:
        return None, "Kein Gesicht erkannt!"

    face_info = faces[0]
    face_emb = face_info.normed_embedding
    face_kps = face_info.kps

    # Generieren
    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        face_emb=face_emb,
        face_kps=face_kps,
        ip_adapter_scale=strength,
        num_inference_steps=steps
    ).images[0]

    return image, "Erfolgreich!"

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Image(type="pil", label="Referenzgesicht"),
        gr.Textbox(label="Prompt", value="professionelles Porträt"),
        gr.Textbox(label="Negativer Prompt", value="hässlich, verschwommen"),
        gr.Slider(0.1, 1.0, value=0.8, label="Identitätsstärke"),
        gr.Slider(10, 50, value=30, step=1, label="Schritte")
    ],
    outputs=[
        gr.Image(label="Generiertes Bild"),
        gr.Textbox(label="Status")
    ],
    title="InstantID – identitätserhaltende Generierung"
)

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

## Batch-Gesichtstausch

```python
import os
from pathlib import Path

def batch_generate(face_image_path, prompts, output_dir):
    # Gesicht laden
    face_cv = cv2.imread(face_image_path)
    face_info = app.get(face_cv)[0]
    face_emb = face_info.normed_embedding
    face_kps = face_info.kps

    os.makedirs(output_dir, exist_ok=True)

    for i, prompt in enumerate(prompts):
        print(f"Generiere {i+1}/{len(prompts)}: {prompt[:50]}...")

        image = pipe(
            prompt=prompt,
            negative_prompt="hässlich, verschwommen, deformiert",
            face_emb=face_emb,
            face_kps=face_kps,
            num_inference_steps=30
        ).images[0]

        image.save(f"{output_dir}/output_{i:03d}.png")

# Verwendung
prompts = [
    "Astronaut im Raumanzug, Erde im Hintergrund",
    "mittelalterlicher Ritter in Rüstung",
    "Wissenschaftler im Labor",
    "Koch in der Restaurantküche",
    "Sportler auf dem Sportplatz"
]

batch_generate("my_face.jpg", prompts, "./outputs")
```

## Steuerung der Identitätsstärke

```python

# Geringe Stärke – mehr Stil, weniger Identität
image_stylized = pipe(
    prompt=prompt,
    face_emb=face_emb,
    ip_adapter_scale=0.4,  # Niedrig
    num_inference_steps=30
).images[0]

# Hohe Stärke – mehr Identität, weniger Stil
image_faithful = pipe(
    prompt=prompt,
    face_emb=face_emb,
    ip_adapter_scale=0.9,  # Hoch
    num_inference_steps=30
).images[0]
```

## Speicheroptimierung

```python

# Optimierungen aktivieren
pipe.enable_model_cpu_offload()
pipe.enable_vae_slicing()

# Oder Sequential Offload für sehr wenig VRAM verwenden
pipe.enable_sequential_cpu_offload()
```

## Leistung

| Modus    | GPU      | Zeit pro Bild |
| -------- | -------- | ------------- |
| Einfach  | RTX 4090 | \~8s          |
| Mit Pose | RTX 4090 | \~12 s        |
| Einfach  | RTX 3090 | \~15 s        |
| Einfach  | A100     | \~5 s         |

## Fehlerbehebung

### Kein Gesicht erkannt

* Stellen Sie sicher, dass das Gesicht klar sichtbar ist
* Gute Beleuchtung im Referenzbild
* Das Gesicht sollte frontal ausgerichtet sein

### Identität nicht beibehalten

* ip\_adapter\_scale erhöhen
* Verwenden Sie ein klareres Referenzfoto
* Extreme Winkel vermeiden

### Stil nicht angewendet

* ip\_adapter\_scale verringern
* Beschreibenderer Prompt
* guidance\_scale erhöhen

## Kostenschätzung

Übliche CLORE.AI-Marktplatzpreise (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           |

*Die Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI-Marktplatz*](https://clore.ai/marketplace) *für aktuelle Preise.*

**Geld sparen:**

* Nutzen Sie den **Spot** Markt für unterbrechbare Arbeit — etwa ein Drittel der Server bietet Spot-Preise unter dem On-Demand-Preis (Median ca. 13 % Rabatt), der Rest ist gleichauf
* Bezahlen Sie mit **CLORE** Tokens
* Vergleichen Sie Preise zwischen verschiedenen Anbietern

## Nächste Schritte

* [IP-Adapter](/guides/guides_v2-de/gesicht-and-identitat/ip-adapter.md) - Bild-Prompting
* Stable Diffusion WebUI - InstantID-Erweiterung
* [ControlNet](/guides/guides_v2-de/bildverarbeitung/controlnet-advanced.md) - Posensteuerung


---

# 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-de/gesicht-and-identitat/instantid.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.
