> 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-es/procesamiento-de-imagenes/gfpgan-face-restore.md).

# Restauración de rostros con GFPGAN

Restaura y mejora rostros en fotos usando GFPGAN en Clore.ai

Restaura y mejora rostros en fotos usando GFPGAN.

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

## Alquilar en CLORE.AI

1. Visita [Marketplace de CLORE.AI](https://clore.ai/marketplace)
2. Filtra por tipo de GPU, VRAM y precio
3. Elige **Bajo demanda** (tarifa fija) o **Spot** (precio ofertado)
4. Configura tu pedido:
   * Selecciona la imagen de Docker
   * Configura los puertos (TCP para SSH, HTTP para interfaces web)
   * Añade variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona el método de pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera al 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/dañadas
* Mejorar rostros borrosos
* Mejorar rostros generados por IA
* Corregir retratos de baja resolución

## Despliegue rápido

**Imagen de Docker:**

```
pytorch/pytorch:2.11.0-cuda12.8-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='Restaurador de rostros GFPGAN')
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. Ve a **Mis pedidos** página
2. Haz clic en tu pedido
3. Encuentra la `http_pub` URL (p. ej., `abc123.clorecloud.net`)

Usa `https://YOUR_HTTP_PUB_URL` en lugar de `localhost` en los ejemplos a continuación.

## Uso de CLI

### Instalación

```bash
pip install gfpgan
```

### Descargar modelos

```bash

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

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

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

### Uso básico

```bash

# Restaurar una sola imagen
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 escalado
    --bg_upsampler realesrgan \\  # Mejorador del fondo
    --only_center_face  # Solo restaurar 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 del fondo

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

# Configurar el mejorador del 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 el restaurador de rostros con mejora del 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 vuelta)

```python

# Obtener los rostros restaurados individuales
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"Falló: {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 el 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 el original si falla la restauración

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    | Excelente | Rápido        | Buen equilibrio |
| v1.2    | Bueno     | El más rápido | Heredado        |

## Casos de uso

### Restauración de fotos antiguas

```python

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

### Mejora de arte con IA

```python

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

### Fotos de grupo

```python

# Procesar todos los rostros en la 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ó ningún rostro

```python

# Disminuir el umbral de detección
from gfpgan.utils import GFPGANer

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

### Resultados demasiado suavizados

* Usar CodeFormer con un peso de fidelidad más bajo
* 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 por uno
only_center_face=True
```

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a partir 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* [*Marketplace de CLORE.AI*](https://clore.ai/marketplace) *las tarifas actuales.*

**Ahorra dinero:**

* Usa el **Spot** mercado para trabajo interrumpible — alrededor de un tercio de los servidores fija el precio spot por debajo del precio bajo demanda (mediana de \~13% de descuento), el resto lo iguala
* Paga con **CLORE** tokens
* Compara precios entre distintos proveedores

## Siguientes pasos

* [Escalado con Real-ESRGAN](/guides/guides_v2-es/procesamiento-de-imagenes/real-esrgan-upscaling.md)
* Interfaz web de Stable Diffusion
* [Generación de video con IA](/guides/guides_v2-es/generacion-de-video/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-es/procesamiento-de-imagenes/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.
