> 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

Augmentez la fréquence d'images vidéo avec l'interpolation IA RIFE sur Clore.ai

Augmentez la fréquence d'images vidéo avec l'interpolation IA RIFE.

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

## Louer sur CLORE.AI

1. Visitez [la place de marché CLORE.AI](https://clore.ai/marketplace)
2. Filtrez par type de GPU, VRAM et prix
3. Choisissez **À 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@<proxy-address>`

## 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 les vidéos saccadées
* Traitement en temps réel

## Déploiement rapide

**Image Docker :**

```
pytorch/pytorch:2.11.0-cuda12.8-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 le code स्रोत

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

## Utilisation de base

### Doubler la fréquence d'images

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

# Sortie : 2x FPS
```

### Fréquence d'images x4

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

# Sortie : 4x FPS
```

### Fréquence d'images x8

```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 photos"""
    # 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 обратно
    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 fps, 10 secondes = 300 images

# Interpolation x8 : 2400 images

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

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

# Cela crée 8x d'images, lecture à la fréquence d'images 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 au 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 fréquence d'images 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 le 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"Terminé : {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+ :

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

## Optimisation de la mémoire

### Pour VRAM limitée

```python

# Traiter en 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 découpage en tuiles 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      | FPS interpolés x2 |
| ---------- | -------- | ----------------- |
| 1080p      | RTX 3090 | \~60 fps          |
| 1080p      | RTX 4090 | \~100 fps         |
| 4K         | RTX 3090 | \~15 fps          |
| 4K         | RTX 4090 | \~30 fps          |

## Dépannage

### Artefacts/Effet fantôme

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

### Mémoire insuffisante

* Utiliser la version NCNN
* Traiter à une résolution inférieure, puis mettre à l'échelle ensuite
* Réduire la taille du lot

### Traitement lent

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

## Détection de scènes

Ignorer l'interpolation aux coupes 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"Scène : {scene[0].get_frames()} - {scene[1].get_frames()}")
```

## Estimation des coûts

Tarifs typiques du marché CLORE.AI (en 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 40 Go | \~$0.17       | \~$4.00          | \~$0.70             |
| A100 80 Go | \~$0.25       | \~$6.00          | \~$1.00             |

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

**Économisez de l'argent :**

* Utilisez le **Spot** marché pour les travaux interrompables — environ un tiers des serveurs ont un prix spot inférieur au tarif à la demande (médiane \~13 % de remise), les autres s'alignent dessus
* Payez avec **CLORE** jetons
* Comparez les prix entre différents fournisseurs

## Étapes suivantes

* [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) - Mettre la vidéo à l'échelle supérieure
* [Génération vidéo par 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, and the optional `goal` query parameter:

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