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

Gesichter in Fotos mit GFPGAN wiederherstellen und verbessern.

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

GFPGAN (Generative Facial Prior GAN) spezialisiert sich auf:

* Wiederherstellung alter/beschädigter Fotos
* Verbesserung unscharfer Gesichter
* Verbesserung KI-generierter Gesichter
* Behebung von Porträts mit niedriger Auflösung

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-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 Face Restorer')
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

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

## CLI-Verwendung

### Installation

```bash
pip install gfpgan
```

### Modelle herunterladen

```bash

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

# Einzelbild 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 \              # Hochskalierungsfaktor
    --bg_upsampler realesrgan \  # Hintergrund-Upscaler
    --only_center_face  # Nur Gesicht in der Bildmitte 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
)

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

# Verarbeitung
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 (Nicht zurück einfügen)

```python

# Einzelne wiederhergestellte Gesichter erhalten
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"Failed: {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)
```

## Videogesichtswiederherstellung

```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         | Gutes Gleichgewicht |
| v1.2    | Gut       | Am schnellsten  | Legacy              |

## Anwendungsfälle

### Wiederherstellung alter Fotos

```python

# Beste Einstellungen für alte Fotos
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,  # Höhere Hochskalierung für alte Niedrigauflösungsfotos
    bg_upsampler=bg_upsampler
)
```

### KI-Kunstverbesserung

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

### 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.3s |
| 1024x1024 | 5         | RTX 3090 | \~0.8s |
| 2048x2048 | 1         | RTX 4090 | \~0.3s |

## Fehlerbehebung

### Kein Gesicht erkannt

```python

# Erkennungs-Schwelle senken
from gfpgan.utils import GFPGANer

# Oder zuerst den Gesichtsbereich manuell zuschneiden
```

### Übermäßig geglättete Ergebnisse

* Verwende CodeFormer mit geringerer Fidelity-Gewichtung
* Mit dem Original mittels Alpha-Compositing mischen

### VRAM-Probleme

```python

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

# Gesichter nacheinander verarbeiten
only_center_face=True
```

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

* [Real-ESRGAN-Upscaling](/guides/guides_v2-de/bildverarbeitung/real-esrgan-upscaling.md)
* Stable Diffusion WebUI
* [KI-Videogenerierung](/guides/guides_v2-de/video-generierung/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:

```
GET https://docs.clore.ai/guides/guides_v2-de/bildverarbeitung/gfpgan-face-restore.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.
