> 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/real-esrgan-upscaling.md).

# Escalado con Real-ESRGAN

Escala y mejora imágenes con Real-ESRGAN en GPUs de Clore.ai

Escala y mejora imágenes usando Real-ESRGAN en la GPU.

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

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

* Escala imágenes de 2x a 4x
* Elimina ruido y artefactos
* Mejora los detalles
* Funciona con fotos, anime y arte

## Variantes del modelo

| Modelo                        | Ideal para           | Velocidad     |
| ----------------------------- | -------------------- | ------------- |
| RealESRGAN\_x4plus            | Fotos generales      | Medio         |
| RealESRGAN\_x4plus\_anime\_6B | Anime/dibujos        | Medio         |
| RealESRGAN\_x2plus            | Escalado x2          | Rápido        |
| RealESRNet\_x4plus            | Procesamiento rápido | El más rápido |

## Despliegue rápido

**Imagen de Docker:**

```
pytorch/pytorch:2.11.0-cuda12.8-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='Escala')],
    outputs=gr.Image(type='pil'),
    title='Escalador Real-ESRGAN'
)
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 realesrgan
```

### Escalado básico

```bash

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

# Escalar 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 facial
    --fp32 \\                 # Usar FP32 (más VRAM, mejor calidad)
    --tile 400               # Tamaño de tesela 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
)

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

### Con mejora facial

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

### Escalado para 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)

# Procesa 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 en teselas (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 teselas de 400 px
    tile_pad=10,   # Superposición entre teselas
    pre_pad=0,
    half=True
)
```

### Recomendaciones de tamaño de tesela

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

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

### Pipeline de FFmpeg

```bash

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

# Escalar 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 el 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 | Ideal para         |
| ----------------- | --------- | ------------- | ---- | ------------------ |
| x4plus            | Mejor     | Lento         | 4GB+ | Fotos              |
| x4plus\_anime\_6B | Mejor     | Medio         | 3GB+ | Anime              |
| x2plus            | Bueno     | Rápido        | 2GB+ | Escalado rápido x2 |
| RealESRNet        | Aceptable | El más rápido | 2GB+ | Vistas previas     |

## Rendimiento

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

## Solución de problemas

### CUDA sin memoria

```python

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

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

### Artefactos en la salida

* Usa un tamaño de tesela más pequeño con mayor superposición
* Prueba un modelo diferente (anime vs foto)
* Comprueba la calidad de la imagen de entrada

### Procesamiento lento

* Habilitar FP16: `half=True`
* Aumenta el tamaño de tesela si la VRAM lo permite
* Usa 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 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

* [Restauración facial GFPGAN](/guides/guides_v2-es/procesamiento-de-imagenes/gfpgan-face-restore.md)
* [Generación de video con IA](/guides/guides_v2-es/generacion-de-video/ai-video-generation.md)
* Interfaz web de Stable Diffusion


---

# 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/real-esrgan-upscaling.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.
