# InstantID

Erzeuge Bilder mit jeder Gesichtsidentität nur anhand eines Referenzfotos.

{% 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 InstantID?

InstantID bewahrt die Gesichtsidentität:

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

## Anforderungen

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

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-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
```

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

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

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

# Lade InstantID-Komponenten
from diffusers import ControlNetModel

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

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

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

# Erzeuge mit Gesichtsidentität
image = pipe(
    prompt="portrait of a person as an astronaut, space background",
    negative_prompt="ugly, blurry, low quality",
    ip_adapter_image_embeds=[torch.tensor(face_emb).unsqueeze(0)],
    num_inference_steps=30,
    guidance_scale=7.5
).images[0]

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

## Verwendung der Diffusers-Pipeline

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

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

# Lade Pipeline
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")

# Erhalte Gesichts-Embedding
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="watercolor portrait painting, artistic",
    face_emb=face_emb,
    face_kps=face_kps,
    num_inference_steps=30
).images[0]

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

## Stilbeispiele

### Professionelles Bewerbungsfoto

```python
prompt = "professional corporate headshot, studio lighting, gray background, business attire"
negative = "cartoon, anime, illustration, blurry"
```

### Künstlerisches Porträt

```python
prompt = "oil painting portrait in the style of Rembrandt, dramatic lighting, museum quality"
negative = "photo, realistic, modern"
```

### Fantasy-Charakter

```python
prompt = "fantasy elf character, pointed ears, magical forest background, ethereal lighting"
negative = "human ears, modern clothing, realistic"
```

### Anime-Stil

```python
prompt = "anime character portrait, studio ghibli style, detailed, beautiful"
negative = "realistic, photo, 3d render"
```

## Mit Pose-Kontrolle

```python
from diffusers.utils import load_image

# Lade Pose-Referenz
pose_image = load_image("pose_reference.jpg")

# Erzeuge mit Gesicht UND Pose
image = pipe(
    prompt="person in action pose, dynamic, high quality",
    face_emb=face_emb,
    face_kps=face_kps,
    image=pose_image,  # Pose-Referenz
    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):
    # Konvertiere ins cv2-Format
    face_cv = cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR)

    # Erhalte Gesichtsinfos
    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, "Erfolg!"

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Image(type="pil", label="Referenzgesicht"),
        gr.Textbox(label="Prompt", value="professional portrait"),
        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 - Identity Preserving Generation"
)

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):
    # Lade Gesicht
    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"Erzeuge {i+1}/{len(prompts)}: {prompt[:50]}...")

        image = pipe(
            prompt=prompt,
            negative_prompt="ugly, blurry, deformed",
            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 in space suit, Earth background",
    "medieval knight in armor",
    "scientist in laboratory",
    "chef in restaurant kitchen",
    "athlete on sports field"
]

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

## Kontrolle der Identitätsstärke

```python

# Niedrige 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

# Aktivieren von Optimierungen
pipe.enable_model_cpu_offload()
pipe.enable_vae_slicing()

# Oder verwende sequentielles Offload für sehr wenig VRAM
pipe.enable_sequential_cpu_offload()
```

## Leistung

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

## Fehlerbehebung

### Kein Gesicht erkannt

* Stelle sicher, dass das Gesicht deutlich sichtbar ist
* Gute Beleuchtung im Referenzbild
* Das Gesicht sollte frontal ausgerichtet sein

### Identität nicht bewahrt

* Erhöhen Sie ip\_adapter\_scale
* Verwende ein klareres Referenzfoto
* Vermeide extreme Winkel

### Stil nicht angewendet

* Verringern Sie ip\_adapter\_scale
* Beschreibenderer Prompt
* Erhöhe guidance\_scale

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

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


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-de/gesicht-and-identitat/instantid.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
