> 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/bildverarbeitung/gfpgan-face-restore.md).

# GFPGAN-Gesichtsrestaurierung

Stelle Gesichter in Fotos mit GFPGAN auf Clore.ai wieder her und verbessere sie

Gesichter in Fotos mit GFPGAN wiederherstellen und verbessern.

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

GFPGAN (Generative Facial Prior GAN) ist spezialisiert auf:

* Alte/beschädigte Fotos wiederherstellen
* Unscharfe Gesichter verbessern
* KI-generierte Gesichter verbessern
* Porträts mit niedriger Auflösung korrigieren

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

```bash
pip install gfpgan gradio && \
python -c "
import gradio as gr
from gfpgan import GFPGANer
import cv2
import numpy as np

restorer = GFPGANer(
    model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=None
)

def restore(image):
    img = np.array(image)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    _, _, output = restorer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
    output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
    return output

demo = gr.Interface(fn=restore, inputs=gr.Image(), outputs=gr.Image(), title='GFPGAN-Gesichtswiederhersteller')
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

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

## CLI-Verwendung

### Installation

```bash
pip install gfpgan
```

### Modelle herunterladen

```bash

# Modell zur Gesichtswiederherstellung herunterladen
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth -P ./models

# Erkennungsmodell herunterladen
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/detection_Resnet50_Final.pth -P ./models

# Parsing-Modell herunterladen
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/parsing_parsenet.pth -P ./models
```

### Grundlegende Verwendung

```bash

# Einzelnes Bild wiederherstellen
python inference_gfpgan.py -i input.jpg -o results -v 1.4 -s 2

# Ordner wiederherstellen
python inference_gfpgan.py -i ./inputs -o ./results -v 1.4 -s 2
```

### Optionen

```bash
python inference_gfpgan.py \
    -i input.jpg \      # Eingabebild/-ordner
    -o results \        # Ausgabeordner
    -v 1.4 \            # GFPGAN-Version (1.2, 1.3, 1.4)
    -s 2 \              # Vergrößerungsfaktor
    --bg_upsampler realesrgan \  # Hintergrund-Upscaler
    --only_center_face  # Nur das zentrale Gesicht wiederherstellen
```

## Python-API

### Grundlegende Gesichtswiederherstellung

```python
from gfpgan import GFPGANer
import cv2

# Initialisieren
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=None
)

# Bild laden
img = cv2.imread('photo.jpg')

# Gesichter wiederherstellen
cropped_faces, restored_faces, restored_img = restorer.enhance(
    img,
    has_aligned=False,
    only_center_face=False,
    paste_back=True
)

# Ergebnis speichern
cv2.imwrite('restored.jpg', restored_img)
```

### Mit Hintergrundverbesserung

```python
from gfpgan import GFPGANer
from realesrgan import RealESRGANer
from basicsr.archs.rrdbnet_arch import RRDBNet
import cv2

# Hintergrund-Upscaler einrichten
bg_model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
bg_upsampler = RealESRGANer(
    scale=2,
    model_path='RealESRGAN_x2plus.pth',
    model=bg_model,
    half=True
)

# Gesichtswiederhersteller mit Hintergrundverbesserung einrichten
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=bg_upsampler
)

# Verarbeiten
img = cv2.imread('old_photo.jpg')
_, _, output = restorer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
cv2.imwrite('enhanced.jpg', output)
```

### Nur Gesichter verarbeiten (kein Zurückeinfügen)

```python

# Einzelne wiederhergestellte Gesichter abrufen
cropped_faces, restored_faces, _ = restorer.enhance(
    img,
    has_aligned=False,
    only_center_face=False,
    paste_back=False
)

# Jedes Gesicht separat speichern
for i, face in enumerate(restored_faces):
    cv2.imwrite(f'face_{i}.jpg', face)
```

## Batch-Verarbeitung

```python
import os
from gfpgan import GFPGANer
import cv2
from tqdm import tqdm

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2
)

input_dir = './old_photos'
output_dir = './restored'
os.makedirs(output_dir, exist_ok=True)

for filename in tqdm(os.listdir(input_dir)):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        img = cv2.imread(os.path.join(input_dir, filename))

        try:
            _, _, output = restorer.enhance(
                img,
                has_aligned=False,
                only_center_face=False,
                paste_back=True
            )
            cv2.imwrite(os.path.join(output_dir, filename), output)
        except Exception as e:
            print(f"Fehlgeschlagen: {filename} - {e}")
```

## CodeFormer (Alternative)

CodeFormer ist ein weiterer ausgezeichneter Gesichtswiederhersteller:

```python

# Installation
pip install codeformer-pip

# Verwendung
from codeformer import CodeFormer
import cv2

restorer = CodeFormer()
img = cv2.imread('blurry_face.jpg')
result = restorer.restore(img)
cv2.imwrite('restored.jpg', result)
```

## Gesichtswiederherstellung für Videos

```python
import cv2
from gfpgan import GFPGANer
from tqdm import tqdm

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Originalgröße für Video beibehalten
    arch='clean',
    channel_multiplier=2
)

cap = cv2.VideoCapture('video.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

out = cv2.VideoWriter('restored_video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))

for _ in tqdm(range(total)):
    ret, frame = cap.read()
    if not ret:
        break

    try:
        _, _, restored = restorer.enhance(frame, paste_back=True)
        out.write(restored)
    except:
        out.write(frame)  # Original beibehalten, falls die Wiederherstellung fehlschlägt

cap.release()
out.release()
```

## API-Server

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
from gfpgan import GFPGANer
import cv2
import numpy as np

app = FastAPI()

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2
)

@app.post("/restore")
async def restore_face(file: UploadFile, upscale: int = 2):
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    _, _, output = restorer.enhance(img, paste_back=True)

    _, encoded = cv2.imencode('.jpg', output)
    return Response(content=encoded.tobytes(), media_type="image/jpeg")

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

## Modellversionen

| Version | Qualität  | Geschwindigkeit | Hinweise         |
| ------- | --------- | --------------- | ---------------- |
| v1.4    | Am besten | Mittel          | Empfohlen        |
| v1.3    | Großartig | Schnell         | Guter Kompromiss |
| v1.2    | Gut       | Am schnellsten  | Veraltet         |

## Anwendungsfälle

### Wiederherstellung alter Fotos

```python

# Beste Einstellungen für alte Fotos
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,  # Höherer Vergrößerungsfaktor für alte Bilder mit niedriger Auflösung
    bg_upsampler=bg_upsampler
)
```

### Verbesserung von KI-Kunst

```python

# Für KI-generierte Bilder mit Gesichtsartefakten
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Originalgröße beibehalten
    only_center_face=True  # Auf das Hauptgesicht fokussieren
)
```

### Gruppenfotos

```python

# Alle Gesichter im Gruppenfoto verarbeiten
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    only_center_face=False  # ALLE Gesichter verarbeiten
)
```

## Leistung

| Bildgröße | Gesichter | GPU      | Zeit    |
| --------- | --------- | -------- | ------- |
| 512x512   | 1         | RTX 3090 | \~0.2s  |
| 1024x1024 | 1         | RTX 3090 | \~0,3 s |
| 1024x1024 | 5         | RTX 3090 | \~0.8s  |
| 2048x2048 | 1         | RTX 4090 | \~0,3 s |

## Fehlerbehebung

### Kein Gesicht erkannt

```python

# Erkennungsschwelle senken
from gfpgan.utils import GFPGANer

# Oder zuerst den Gesichtsbereich manuell zuschneiden
```

### Zu stark geglättete Ergebnisse

* CodeFormer mit niedrigerem Fidelity-Gewicht verwenden
* Mit Original per Alpha-Compositing mischen

### VRAM-Probleme

```python

# CPU für die Gesichtserkennung verwenden
import torch
torch.cuda.empty_cache()

# Gesichter nacheinander verarbeiten
only_center_face=True
```

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

* [Real-ESRGAN-Hochskalierung](/guides/guides_v2-de/bildverarbeitung/real-esrgan-upscaling.md)
* Stable Diffusion WebUI
* [KI-Videogenerierung](/guides/guides_v2-de/videogenerierung/ai-video-generation.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-de/bildverarbeitung/gfpgan-face-restore.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.
