# Escalado Real-ESRGAN

Mejorar y aumentar la resolución de imágenes usando Real-ESRGAN en GPU.

{% 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 Real-ESRGAN?

Real-ESRGAN es un modelo práctico de restauración de imágenes que:

* Aumenta la resolución de imágenes 2x-4x
* Elimina ruido y artefactos
* Mejora los detalles
* Funciona con fotos, anime y arte

## Variantes de modelo

| Modelo                        | Mejor para           | Velocidad     |
| ----------------------------- | -------------------- | ------------- |
| RealESRGAN\_x4plus            | Fotos generales      | Medio         |
| RealESRGAN\_x4plus\_anime\_6B | Anime/dibujos        | Medio         |
| RealESRGAN\_x2plus            | Aumento 2x           | Rápido        |
| RealESRNet\_x4plus            | Procesamiento rápido | El más rápido |

## Despliegue rápido

**Imagen Docker:**

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

**Puertos:**

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

**Comando:**

```bash
pip install realesrgan gradio && \
python -c "
import gradio as gr
from realesrgan import RealESRGANer
from basicsr.archs.rrdbnet_arch import RRDBNet
import numpy as np
from PIL import Image
import torch

# Cargar modelo
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
upsampler = RealESRGANer(
    scale=4,
    model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth',
    model=model,
    tile=0,
    tile_pad=10,
    pre_pad=0,
    half=True
)

def upscale(image, scale):
    img = np.array(image)
    output, _ = upsampler.enhance(img, outscale=scale)
    return Image.fromarray(output)

demo = gr.Interface(
    fn=upscale,
    inputs=[gr.Image(type='pil'), gr.Slider(2, 4, value=4, step=1, label='Scale')],
    outputs=gr.Image(type='pil'),
    title='Real-ESRGAN Upscaler'
)
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 realesrgan
```

### Aumento básico

```bash

# Aumentar una sola imagen
python -m realesrgan -i input.jpg -o output.jpg -n RealESRGAN_x4plus -s 4

# Aumentar carpeta
python -m realesrgan -i ./inputs -o ./outputs -n RealESRGAN_x4plus -s 4
```

### Opciones

```bash
python -m realesrgan \
    -i input.jpg \           # Entrada
    -o output.jpg \          # Salida
    -n RealESRGAN_x4plus \   # Nombre del modelo
    -s 4 \                   # Factor de escala
    --face_enhance \         # Habilitar mejora de rostros
    --fp32 \                 # Usar FP32 (más VRAM, mejor calidad)
    --tile 400               # Tamaño de mosaico para imágenes grandes
```

## API de Python

### Uso básico

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

# Configurar modelo
model = RRDBNet(
    num_in_ch=3,
    num_out_ch=3,
    num_feat=64,
    num_block=23,
    num_grow_ch=32,
    scale=4
)

upsampler = RealESRGANer(
    scale=4,
    model_path='RealESRGAN_x4plus.pth',
    model=model,
    tile=0,
    tile_pad=10,
    pre_pad=0,
    half=True  # Usar FP16
)

# Aumentar
img = cv2.imread('input.jpg', cv2.IMREAD_UNCHANGED)
output, _ = upsampler.enhance(img, outscale=4)
cv2.imwrite('output.jpg', output)
```

### Con mejora de rostro

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

# Modelo Real-ESRGAN
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
upsampler = RealESRGANer(scale=4, model_path='RealESRGAN_x4plus.pth', model=model, half=True)

# GFPGAN para rostros
face_enhancer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=upsampler
)

# Procesar
img = cv2.imread('portrait.jpg')
_, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
cv2.imwrite('output.jpg', output)
```

### Aumento de Anime

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

# Modelo de anime
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)

upsampler = RealESRGANer(
    scale=4,
    model_path='RealESRGAN_x4plus_anime_6B.pth',
    model=model,
    half=True
)

img = cv2.imread('anime.png')
output, _ = upsampler.enhance(img, outscale=4)
cv2.imwrite('anime_upscaled.png', output)
```

## Procesamiento por lotes

### Procesar carpeta

```python
import os
from realesrgan import RealESRGANer
from basicsr.archs.rrdbnet_arch import RRDBNet
import cv2
from tqdm import tqdm

# Configuración
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
upsampler = RealESRGANer(scale=4, model_path='RealESRGAN_x4plus.pth', model=model, half=True)

input_dir = './inputs'
output_dir = './outputs'
os.makedirs(output_dir, exist_ok=True)

# Procesar todas las imágenes
for filename in tqdm(os.listdir(input_dir)):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
        img_path = os.path.join(input_dir, filename)
        img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)

        output, _ = upsampler.enhance(img, outscale=4)

        output_path = os.path.join(output_dir, f"upscaled_{filename}")
        cv2.imwrite(output_path, output)
```

### Script de Shell

```bash
#!/bin/bash
INPUT_DIR=$1
OUTPUT_DIR=$2

mkdir -p $OUTPUT_DIR

for file in $INPUT_DIR/*.{jpg,png,jpeg}; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        python -m realesrgan -i "$file" -o "$OUTPUT_DIR/upscaled_$filename" -n RealESRGAN_x4plus -s 4
        echo "Procesado: $filename"
    fi
done
```

## Procesamiento por baldosas (Imágenes grandes)

Para imágenes que no caben en la VRAM:

```python
upsampler = RealESRGANer(
    scale=4,
    model_path='RealESRGAN_x4plus.pth',
    model=model,
    tile=400,      # Procesar en baldosas de 400px
    tile_pad=10,   # Superposición entre baldosas
    pre_pad=0,
    half=True
)
```

### Recomendaciones de tamaño de baldosa

| VRAM | Tamaño máximo de baldosa |
| ---- | ------------------------ |
| 4GB  | 200                      |
| 6GB  | 300                      |
| 8GB  | 400                      |
| 12GB | 600                      |
| 24GB | 0 (sin baldosado)        |

## Escalado de video

### Usando Real-ESRGAN

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

# Configurar modelo
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
upsampler = RealESRGANer(scale=4, model_path='RealESRGAN_x4plus.pth', model=model, tile=400, half=True)

# Abrir video
cap = cv2.VideoCapture('input.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) * 4
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) * 4
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

# Salida
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

# Procesar fotogramas
for _ in tqdm(range(total_frames)):
    ret, frame = cap.read()
    if not ret:
        break

    output, _ = upsampler.enhance(frame, outscale=4)
    out.write(output)

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

### Canalización FFmpeg

```bash

# Extraer fotogramas
ffmpeg -i input.mp4 -qscale:v 1 frames/frame_%06d.png

# Aumentar fotogramas
python -m realesrgan -i frames -o upscaled -n RealESRGAN_x4plus -s 4

# Reensamblar video
ffmpeg -framerate 30 -i upscaled/frame_%06d.png -c:v libx264 -pix_fmt yuv420p output.mp4

# Volver a añadir audio
ffmpeg -i output.mp4 -i input.mp4 -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 final.mp4
```

## Servidor API

### Servidor FastAPI

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
from realesrgan import RealESRGANer
from basicsr.archs.rrdbnet_arch import RRDBNet
import cv2
import numpy as np
import io

app = FastAPI()

# Cargar modelo
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
upsampler = RealESRGANer(scale=4, model_path='RealESRGAN_x4plus.pth', model=model, tile=400, half=True)

@app.post("/upscale")
async def upscale(file: UploadFile, scale: int = 4):
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)

    output, _ = upsampler.enhance(img, outscale=scale)

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

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

### Uso

```bash
curl -X POST "http://localhost:8000/upscale?scale=4" \
    -F "file=@input.jpg" \
    --output upscaled.png
```

## Comparación de modelos

| Modelo            | Calidad | Velocidad     | VRAM | Mejor para         |
| ----------------- | ------- | ------------- | ---- | ------------------ |
| x4plus            | Mejor   | Lento         | 4GB+ | Fotos              |
| x4plus\_anime\_6B | Mejor   | Medio         | 3GB+ | Anime              |
| x2plus            | Bueno   | Rápido        | 2GB+ | Rápido 2x          |
| RealESRNet        | OK      | El más rápido | 2GB+ | Previsualizaciones |

## Rendimiento

| Tamaño de imagen | GPU      | Tiempo de aumento 4x |
| ---------------- | -------- | -------------------- |
| 512x512          | RTX 3090 | \~0.5s               |
| 1024x1024        | RTX 3090 | \~1.5s               |
| 2048x2048        | RTX 3090 | \~5s                 |
| 512x512          | RTX 4090 | \~0.3s               |

## Solución de problemas

### CUDA: fuera de memoria

```python

# Usar baldosado
upsampler = RealESRGANer(..., tile=200, ...)

# O reducir la escala
output, _ = upsampler.enhance(img, outscale=2)  # En lugar de 4
```

### Artefactos en la salida

* Usar un tamaño de baldosa más pequeño con más solapamiento
* Probar un modelo diferente (anime vs foto)
* Comprobar la calidad de la imagen de entrada

### Procesamiento lento

* Habilitar FP16: `half=True`
* Aumentar el tamaño de baldosa si la VRAM lo permite
* Usar un modelo más rápido: RealESRNet

## Descargar resultados

```bash
scp -P <port> -r root@<proxy>:/workspace/outputs/ ./upscaled_images/
```

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

* [Restauración de rostros con GFPGAN](https://docs.clore.ai/guides/guides_v2-es/procesamiento-de-imagenes/gfpgan-face-restore)
* [Generación de video AI](https://docs.clore.ai/guides/guides_v2-es/generacion-de-video/ai-video-generation)
* Stable Diffusion WebUI
