> 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-fr/traitement-video/rife-interpolation.md).

# Interpolation RIFE

Augmenter la fréquence d'images vidéo avec l'interpolation RIFE AI.

{% hint style="success" %}
Tous les exemples peuvent être exécutés sur des serveurs GPU loués via [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Location sur CLORE.AI

1. Visitez [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrer par type de GPU, VRAM et prix
3. Choisir **À la demande** (tarif fixe) ou **Spot** (prix d'enchère)
4. Configurez votre commande :
   * Sélectionnez l'image Docker
   * Définissez les ports (TCP pour SSH, HTTP pour les interfaces web)
   * Ajoutez des variables d'environnement si nécessaire
   * Entrez la commande de démarrage
5. Sélectionnez le paiement : **CLORE**, **BTC**, ou **USDT/USDC**
6. Créez la commande et attendez le déploiement

### Accédez à votre serveur

* Trouvez les détails de connexion dans **Mes commandes**
* Interfaces Web : utilisez l'URL du port HTTP
* SSH : `ssh -p <port> root@<adresse-proxy>`

## Qu'est-ce que RIFE ?

RIFE (Real-Time Intermediate Flow Estimation) peut :

* Augmenter les FPS (24→60, 30→120)
* Créer un ralenti fluide
* Corriger des séquences saccadées
* Traitement en temps réel

## Déploiement rapide

**Image Docker :**

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

**Ports :**

```
22/tcp
```

**Commande :**

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

## Installation

### Option 1 : paquet Python

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

### Option 2 : depuis les sources

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

## Utilisation de base

### Doublement de la fréquence d'images

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

# Sortie : 2x FPS
```

### Fréquence d'images 4x

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

# Sortie : 4x FPS
```

### Fréquence d'images 8x

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

# Sortie : 8x FPS
```

## API Python

### Charger le modèle

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

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

### Interpoler une seule image

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

def interpolate_frames(frame1, frame2, model, num_frames=1):
    """Interpoler des images entre deux images"""
    # Préparer les tenseurs
    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()

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

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

# Charger les images
frame1 = cv2.imread('frame1.png')
frame2 = cv2.imread('frame2.png')

# Obtenir l'image interpolée
middle_frame = interpolate_frames(frame1, frame2, model)
cv2.imwrite('interpolated.png', middle_frame)
```

### Traiter la vidéo

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

        # Préparer les tenseurs
        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()

        # Générer des images intermédiaires
        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)
```

## Utilisation de rife-ncnn-vulkan

Implémentation NCNN plus rapide :

```python
from rife_ncnn_vulkan import Rife

rife = Rife(gpu_id=0)

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

### Traitement vidéo

```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 en PIL
        prev_pil = Image.fromarray(cv2.cvtColor(prev, cv2.COLOR_BGR2RGB))
        curr_pil = Image.fromarray(cv2.cvtColor(curr, cv2.COLOR_BGR2RGB))

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

## Ralenti

Créer un ralenti fluide :

```python

# Original : 30 ips, 10 secondes = 300 images

# Interpolation 8x : 2400 images

# Lecture à 30 ips : 80 secondes (8x plus lent)

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

# Cela crée des images 8x, lire à la FPS d'origine pour le ralenti
```

### Script de ralenti

```python
def create_slow_motion(input_path, output_path, slowdown_factor=4):
    """Créer une vidéo en ralenti"""
    cap = cv2.VideoCapture(input_path)
    original_fps = cap.get(cv2.CAP_PROP_FPS)

    # Interpoler pour obtenir plus d'images
    exp = int(np.log2(slowdown_factor))
    interpolate_video(input_path, 'temp_interpolated.mp4', factor=slowdown_factor)

    # Réencoder à la FPS d'origine
    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,  # Conserver la FPS d'origine
        (width, height)
    )

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

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

## Traitement par lots

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

## Paramètres de qualité

### Versions du modèle

| Modèle    | Qualité   | Vitesse        |
| --------- | --------- | -------------- |
| RIFE v4.6 | Meilleur  | Lent           |
| RIFE v4.0 | Excellent | Moyen          |
| RIFE-NCNN | Bon       | Le plus rapide |

### Mode UHD

Pour les vidéos 4K et plus :

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

## Optimisation de la mémoire

### Pour VRAM limitée

```python

# Traiter par tuiles
from model.RIFE import Model

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

# Définir la taille des tuiles pour les grandes images

# model.inference gère le tiling en interne
```

### Réduire la mémoire

```bash

# Utiliser la version NCNN (plus économe en mémoire)
pip install rife-ncnn-vulkan-python
```

## Performances

| Résolution | GPU      | Interpolation 2x FPS |
| ---------- | -------- | -------------------- |
| 1080p      | RTX 3090 | \~60 ips             |
| 1080p      | RTX 4090 | \~100 ips            |
| 4K         | RTX 3090 | \~15 ips             |
| 4K         | RTX 4090 | \~30 ips             |

## Dépannage

### Artefacts/Images fantômes

* Utiliser la détection de scène pour ignorer les coupures
* Réduire le facteur d'interpolation
* Vérifier les mouvements rapides

### Mémoire insuffisante

* Utiliser la version NCNN
* Traiter à une résolution inférieure, agrandir ensuite
* Réduire la taille de batch

### Traitement lent

* Utiliser la version NCNN-Vulkan
* Activer l'accélération GPU
* Utiliser un modèle plus petit

## Détection de scène

Ignorer l'interpolation lors des coupures de scène :

```python
from scenedetect import detect, ContentDetector

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

# Ne pas interpoler entre les scènes
for scene in scenes:
    print(f"Scene: {scene[0].get_frames()} - {scene[1].get_frames()}")
```

## Estimation des coûts

Tarifs typiques du marché CLORE.AI (à partir de 2024) :

| GPU       | Tarif horaire | Tarif journalier | Session de 4 heures |
| --------- | ------------- | ---------------- | ------------------- |
| 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             |

*Les prix varient selon le fournisseur et la demande. Vérifiez* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *pour les tarifs actuels.*

**Économisez de l'argent :**

* Utilisez **Spot** market pour les charges de travail flexibles (souvent 30-50 % moins cher)
* Payer avec **CLORE** jetons
* Comparer les prix entre différents fournisseurs

## Prochaines étapes

* [FFmpeg NVENC](/guides/guides_v2-fr/traitement-video/ffmpeg-nvenc.md) - Encoder la sortie
* [Real-ESRGAN](/guides/guides_v2-fr/traitement-dimages/real-esrgan-upscaling.md) - Suréchantillonner la vidéo
* [Génération vidéo IA](/guides/guides_v2-fr/generation-video/ai-video-generation.md) - Générer des vidéos


---

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

```
GET https://docs.clore.ai/guides/guides_v2-fr/traitement-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.
