# Restauración facial GFPGAN

Restaurar y mejorar rostros en fotos usando GFPGAN.

{% hint style="success" %}
Todos los ejemplos se pueden ejecutar en servidores GPU alquilados a través de [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Alquilar en CLORE.AI

1. Visita [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrar por tipo de GPU, VRAM y precio
3. Elegir **Bajo demanda** (tarifa fija) o **Spot** (precio de puja)
4. Configura tu pedido:
   * Selecciona imagen Docker
   * Establece puertos (TCP para SSH, HTTP para interfaces web)
   * Agrega variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera el despliegue

### Accede a tu servidor

* Encuentra los detalles de conexión en **Mis Pedidos**
* Interfaces web: Usa la URL del puerto HTTP
* SSH: `ssh -p <port> root@<proxy-address>`

## ¿Qué es GFPGAN?

GFPGAN (Generative Facial Prior GAN) se especializa en:

* Restaurar fotos antiguas/danadas
* Mejorar rostros borrosos
* Mejorar rostros generados por IA
* Arreglar retratos de baja resolución

## Despliegue rápido

**Imagen Docker:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
```

**Puertos:**

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

**Comando:**

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

## Accediendo a tu servicio

Después del despliegue, encuentra tu `http_pub` URL en **Mis Pedidos**:

1. Ir a **Mis Pedidos** página
2. Haz clic en tu pedido
3. Encuentra la `http_pub` URL (por ejemplo, `abc123.clorecloud.net`)

Usa `https://TU_HTTP_PUB_URL` en lugar de `localhost` en los ejemplos abajo.

## Uso CLI

### Instalación

```bash
pip install gfpgan
```

### Descargar modelos

```bash

# Descargar modelo de restauración de rostros
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth -P ./models

# Descargar modelo de detección
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/detection_Resnet50_Final.pth -P ./models

# Descargar modelo de parsing
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/parsing_parsenet.pth -P ./models
```

### Uso básico

```bash

# Restaurar imagen individual
python inference_gfpgan.py -i input.jpg -o results -v 1.4 -s 2

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

### Opciones

```bash
python inference_gfpgan.py \
    -i input.jpg \      # Imagen/carpeta de entrada
    -o results \        # Carpeta de salida
    -v 1.4 \            # Versión de GFPGAN (1.2, 1.3, 1.4)
    -s 2 \              # Factor de aumento
    --bg_upsampler realesrgan \  # Upscaler de fondo
    --only_center_face  # Restaurar solo el rostro central
```

## API de Python

### Restauración básica de rostros

```python
from gfpgan import GFPGANer
import cv2

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

# Cargar imagen
img = cv2.imread('photo.jpg')

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

# Guardar resultado
cv2.imwrite('restored.jpg', restored_img)
```

### Con mejora de fondo

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

# Configurar upscaler de fondo
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
)

# Configurar restaurador de rostros con mejora de fondo
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=bg_upsampler
)

# Procesar
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)
```

### Procesar solo rostros (sin pegar de nuevo)

```python

# Obtener rostros restaurados individualmente
cropped_faces, restored_faces, _ = restorer.enhance(
    img,
    has_aligned=False,
    only_center_face=False,
    paste_back=False
)

# Guardar cada rostro por separado
for i, face in enumerate(restored_faces):
    cv2.imwrite(f'face_{i}.jpg', face)
```

## Procesamiento por lotes

```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 (Alternativa)

CodeFormer es otro excelente restaurador de rostros:

```python

# Instalación
pip install codeformer-pip

# Uso
from codeformer import CodeFormer
import cv2

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

## Restauración de rostros en video

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

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Mantener tamaño original para video
    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)  # Mantener original si la restauración falla

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

## Servidor API

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

# Ejecutar: uvicorn server:app --host 0.0.0.0 --port 8000
```

## Versiones del modelo

| Versión | Calidad | Velocidad     | Notas           |
| ------- | ------- | ------------- | --------------- |
| v1.4    | Mejor   | Medio         | Recomendado     |
| v1.3    | Genial  | Rápido        | Buen equilibrio |
| v1.2    | Bueno   | El más rápido | Legado          |

## Casos de uso

### Restauración de fotos antiguas

```python

# Mejores ajustes para fotos antiguas
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,  # Mayor aumento para fotos antiguas de baja resolución
    bg_upsampler=bg_upsampler
)
```

### Mejora de arte IA

```python

# Para imágenes generadas por IA con artefactos en rostros
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Mantener tamaño original
    only_center_face=True  # Enfocarse en el rostro principal
)
```

### Fotos de grupo

```python

# Procesar todos los rostros en foto de grupo
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    only_center_face=False  # Procesar TODOS los rostros
)
```

## Rendimiento

| Tamaño de imagen | Rostros | GPU      | Tiempo |
| ---------------- | ------- | -------- | ------ |
| 512x512          | 1       | RTX 3090 | \~0.2s |
| 1024x1024        | 1       | RTX 3090 | \~0.3s |
| 1024x1024        | 5       | RTX 3090 | \~0.8s |
| 2048x2048        | 1       | RTX 4090 | \~0.3s |

## Solución de problemas

### No se detectó rostro

```python

# Umbral de detección más bajo
from gfpgan.utils import GFPGANer

# O recortar manualmente el área del rostro primero
```

### Resultados sobre-suavizados

* Usar CodeFormer con menor peso de fidelidad
* Mezclar con el original usando composición alfa

### Problemas de VRAM

```python

# Usar CPU para la detección de rostros
import torch
torch.cuda.empty_cache()

# Procesar los rostros uno a la vez
only_center_face=True
```

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a fecha de 2024):

| GPU       | Tarifa por hora | Tarifa diaria | Sesión de 4 horas |
| --------- | --------------- | ------------- | ----------------- |
| 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           |

*Los precios varían según el proveedor y la demanda. Consulta* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *para las tarifas actuales.*

**Ahorra dinero:**

* Usa **Spot** market para cargas de trabajo flexibles (a menudo 30-50% más barato)
* Paga con **CLORE** tokens
* Compara precios entre diferentes proveedores

## Próximos pasos

* [Escalado Real-ESRGAN](/guides/guides_v2-es/procesamiento-de-imagenes/real-esrgan-upscaling.md)
* Stable Diffusion WebUI
* [Generación de video AI](/guides/guides_v2-es/generacion-de-video/ai-video-generation.md)


---

# 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-es/procesamiento-de-imagenes/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.
