# Interpolación RIFE

Aumenta la frecuencia de imagen de video con interpolación AI RIFE.

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

RIFE (Estimación de Flujo Intermedio en Tiempo Real) puede:

* Aumentar FPS (24→60, 30→120)
* Crear cámara lenta suave
* Arreglar metraje entrecortado
* Procesamiento en tiempo real

## Despliegue rápido

**Imagen Docker:**

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

**Puertos:**

```
22/tcp
```

**Comando:**

```bash
pip install torch torchvision && \
git clone https://github.com/megvii-research/ECCV2022-RIFE.git && \
cd ECCV2022-RIFE && \
pip install -r requirements.txt
```

## Instalación

### Opción 1: Paquete de Python

```bash
pip install rife-ncnn-vulkan-python
```

### Opción 2: Desde el código fuente

```bash
git clone https://github.com/megvii-research/ECCV2022-RIFE.git
cd ECCV2022-RIFE
pip install -r requirements.txt
```

## Uso básico

### Duplicar la tasa de fotogramas

```bash
python inference_video.py --exp=1 --video=input.mp4

# Salida: 2x FPS
```

### 4x Tasa de fotogramas

```bash
python inference_video.py --exp=2 --video=input.mp4

# Salida: 4x FPS
```

### 8x Tasa de fotogramas

```bash
python inference_video.py --exp=3 --video=input.mp4

# Salida: 8x FPS
```

## API de Python

### Cargar modelo

```python
import torch
from model.RIFE import Model

device = torch.device("cuda")
model = Model()
model.load_model('./train_log', -1)
model.eval()
model.device()
```

### Interpolar fotograma único

```python
import cv2
import numpy as np
import torch

def interpolate_frames(frame1, frame2, model, num_frames=1):
    """Interpolar fotogramas entre dos imágenes"""
    # Preparar tensores
    img0 = torch.from_numpy(frame1).permute(2, 0, 1).float() / 255.0
    img1 = torch.from_numpy(frame2).permute(2, 0, 1).float() / 255.0

    img0 = img0.unsqueeze(0).cuda()
    img1 = img1.unsqueeze(0).cuda()

    # Interpolar
    with torch.no_grad():
        middle = model.inference(img0, img1)

    # Convertir de nuevo
    middle = (middle[0] * 255).byte().cpu().numpy().transpose(1, 2, 0)
    return middle

# Cargar fotogramas
frame1 = cv2.imread('frame1.png')
frame2 = cv2.imread('frame2.png')

# Obtener fotograma interpolado
middle_frame = interpolate_frames(frame1, frame2, model)
cv2.imwrite('interpolated.png', middle_frame)
```

### Procesar video

```python
import cv2
import torch
from model.RIFE import Model

model = Model()
model.load_model('./train_log', -1)
model.eval()
model.device()

def process_video(input_path, output_path, multiplier=2):
    cap = cv2.VideoCapture(input_path)
    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))

    out = cv2.VideoWriter(
        output_path,
        cv2.VideoWriter_fourcc(*'mp4v'),
        fps * multiplier,
        (width, height)
    )

    ret, prev_frame = cap.read()
    if not ret:
        return

    out.write(prev_frame)

    while True:
        ret, curr_frame = cap.read()
        if not ret:
            break

        # Preparar tensores
        img0 = torch.from_numpy(prev_frame).permute(2, 0, 1).float() / 255.0
        img1 = torch.from_numpy(curr_frame).permute(2, 0, 1).float() / 255.0

        img0 = img0.unsqueeze(0).cuda()
        img1 = img1.unsqueeze(0).cuda()

        # Generar fotogramas intermedios
        for i in range(multiplier - 1):
            t = (i + 1) / multiplier
            with torch.no_grad():
                middle = model.inference(img0, img1, timestep=t)
            middle = (middle[0] * 255).byte().cpu().numpy().transpose(1, 2, 0)
            out.write(middle)

        out.write(curr_frame)
        prev_frame = curr_frame

    cap.release()
    out.release()

process_video('input.mp4', 'output_60fps.mp4', multiplier=2)
```

## Usando rife-ncnn-vulkan

Implementación NCNN más rápida:

```python
from rife_ncnn_vulkan import Rife

rife = Rife(gpu_id=0)

# Interpolar
frame1 = Image.open('frame1.png')
frame2 = Image.open('frame2.png')
middle = rife.process(frame1, frame2)
middle.save('interpolated.png')
```

### Procesamiento de video

```python
from rife_ncnn_vulkan import Rife
import cv2
from PIL import Image

rife = Rife(gpu_id=0, num_threads=4)

def interpolate_video(input_path, output_path, factor=2):
    cap = cv2.VideoCapture(input_path)
    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))

    out = cv2.VideoWriter(
        output_path,
        cv2.VideoWriter_fourcc(*'mp4v'),
        fps * factor,
        (width, height)
    )

    ret, prev = cap.read()
    out.write(prev)

    while True:
        ret, curr = cap.read()
        if not ret:
            break

        # Convertir a PIL
        prev_pil = Image.fromarray(cv2.cvtColor(prev, cv2.COLOR_BGR2RGB))
        curr_pil = Image.fromarray(cv2.cvtColor(curr, cv2.COLOR_BGR2RGB))

        # Interpolar
        for i in range(factor - 1):
            t = (i + 1) / factor
            mid = rife.process(prev_pil, curr_pil, timestep=t)
            mid_cv = cv2.cvtColor(np.array(mid), cv2.COLOR_RGB2BGR)
            out.write(mid_cv)

        out.write(curr)
        prev = curr

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

## Cámara lenta

Crear cámara lenta suave:

```python

# Original: 30 fps, 10 segundos = 300 fotogramas

# Interpolación 8x: 2400 fotogramas

# Reproducir a 30 fps: 80 segundos (8x más lento)

python inference_video.py --exp=3 --video=input.mp4

# Esto crea fotogramas 8x, reproducir a FPS original para cámara lenta
```

### Script de cámara lenta

```python
def create_slow_motion(input_path, output_path, slowdown_factor=4):
    """Crear video en cámara lenta"""
    cap = cv2.VideoCapture(input_path)
    original_fps = cap.get(cv2.CAP_PROP_FPS)

    # Interpolar para obtener más fotogramas
    exp = int(np.log2(slowdown_factor))
    interpolate_video(input_path, 'temp_interpolated.mp4', factor=slowdown_factor)

    # Volver a codificar a FPS original
    cap2 = cv2.VideoCapture('temp_interpolated.mp4')
    width = int(cap2.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap2.get(cv2.CAP_PROP_FRAME_HEIGHT))

    out = cv2.VideoWriter(
        output_path,
        cv2.VideoWriter_fourcc(*'mp4v'),
        original_fps,  # Mantener FPS original
        (width, height)
    )

    while True:
        ret, frame = cap2.read()
        if not ret:
            break
        out.write(frame)

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

## Procesamiento por lotes

```python
import os
from concurrent.futures import ThreadPoolExecutor

def process_single(input_path, output_dir, factor=2):
    filename = os.path.basename(input_path)
    output_path = os.path.join(output_dir, f"interpolated_{filename}")
    interpolate_video(input_path, output_path, factor)
    return output_path

input_dir = './videos'
output_dir = './interpolated'
os.makedirs(output_dir, exist_ok=True)

videos = [os.path.join(input_dir, f) for f in os.listdir(input_dir)
          if f.endswith(('.mp4', '.mkv', '.avi'))]

for video in videos:
    result = process_single(video, output_dir, factor=2)
    print(f"Completed: {result}")
```

## Ajustes de calidad

### Versiones del modelo

| Modelo    | Calidad | Velocidad     |
| --------- | ------- | ------------- |
| RIFE v4.6 | Mejor   | Lento         |
| RIFE v4.0 | Genial  | Medio         |
| RIFE-NCNN | Bueno   | El más rápido |

### Modo UHD

Para videos 4K+:

```bash
python inference_video.py --exp=1 --video=input.mp4 --UHD
```

## Optimización de memoria

### Para VRAM limitada

```python

# Procesar en mosaicos
from model.RIFE import Model

model = Model()
model.load_model('./train_log', -1)
model.eval()

# Establecer tamaño de mosaico para fotogramas grandes

# model.inference maneja el enlosado internamente
```

### Reducir memoria

```bash

# Usar la versión NCNN (más eficiente en memoria)
pip install rife-ncnn-vulkan-python
```

## Rendimiento

| Resolución | GPU      | 2x Interpolación FPS |
| ---------- | -------- | -------------------- |
| 1080p      | RTX 3090 | \~60 fps             |
| 1080p      | RTX 4090 | \~100 fps            |
| 4K         | RTX 3090 | \~15 fps             |
| 4K         | RTX 4090 | \~30 fps             |

## Solución de problemas

### Artefactos/Fantasmeo

* Usar detección de escenas para omitir cortes
* Reducir el factor de interpolación
* Comprobar el movimiento rápido

### Memoria insuficiente

* Usar la versión NCNN
* Procesar a menor resolución y escalar después
* Reducir el tamaño del lote

### Procesamiento lento

* Usar la versión NCNN-Vulkan
* Habilitar aceleración por GPU
* Usar un modelo más pequeño

## Detección de escenas

Omitir la interpolación a través de cortes de escena:

```python
from scenedetect import detect, ContentDetector

scenes = detect('input.mp4', ContentDetector())

# No interpolar entre escenas
for scene in scenes:
    print(f"Scene: {scene[0].get_frames()} - {scene[1].get_frames()}")
```

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

* [FFmpeg NVENC](/guides/guides_v2-es/procesamiento-de-video/ffmpeg-nvenc.md) - Codificar salida
* [Real-ESRGAN](/guides/guides_v2-es/procesamiento-de-imagenes/real-esrgan-upscaling.md) - Reescalar video
* [Generación de video AI](/guides/guides_v2-es/generacion-de-video/ai-video-generation.md) - Generar videos


---

# 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-video/rife-interpolation.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.
