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

# Масштабирование Real-ESRGAN

Увеличивайте разрешение и улучшайте изображения с помощью Real-ESRGAN на GPU Clore.ai

Увеличивайте и улучшайте изображения с помощью Real-ESRGAN на GPU.

{% hint style="success" %}
Все примеры можно запускать на GPU-серверах, арендованных через [маркетплейс CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## Аренда на CLORE.AI

1. Перейдите на [маркетплейс CLORE.AI](https://clore.ai/marketplace)
2. Отфильтруйте по типу GPU, объёму VRAM и цене
3. Выберите **On-Demand** (фиксированная ставка) или **Spot** (цена ставки)
4. Настройте свой заказ:
   * Выберите Docker-образ
   * Установите порты (TCP для SSH, HTTP для веб-интерфейсов)
   * При необходимости добавьте переменные окружения
   * Введите команду запуска
5. Выберите способ оплаты: **CLORE**, **BTC**, или **USDT/USDC**
6. Создайте заказ и дождитесь развертывания

### Получите доступ к своему серверу

* Найдите данные для подключения в **Мои заказы**
* Веб-интерфейсы: используйте URL HTTP-порта
* SSH: `ssh -p <port> root@<proxy-address>`

## Что такое Real-ESRGAN?

Real-ESRGAN — это практическая модель восстановления изображений, которая:

* Увеличивает изображения в 2–4 раза
* Удаляет шум и артефакты
* Улучшает детали
* Работает с фотографиями, аниме и рисунками

## Варианты модели

| Модель                        | Лучше всего для     | Скорость      |
| ----------------------------- | ------------------- | ------------- |
| RealESRGAN\_x4plus            | Обычные фотографии  | Средне        |
| RealESRGAN\_x4plus\_anime\_6B | Аниме/рисунки       | Средне        |
| RealESRGAN\_x2plus            | Увеличение в 2 раза | Быстро        |
| RealESRNet\_x4plus            | Быстрая обработка   | Самый быстрый |

## Быстрое развёртывание

**Docker-образ:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**Порты:**

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

**Команда:**

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

# Загрузить модель
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='Масштаб')],
    outputs=gr.Image(type='pil'),
    title='Масштабирование Real-ESRGAN'
)
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

## Доступ к вашему сервису

После развертывания найдите свой `http_pub` URL в **Мои заказы**:

1. Перейдите на **Мои заказы** страницу
2. Нажмите на свой заказ
3. Найдите `http_pub` URL (например, `abc123.clorecloud.net`)

Используйте `https://YOUR_HTTP_PUB_URL` вместо `localhost` в примерах ниже.

## Использование CLI

### Установка

```bash
pip install realesrgan
```

### Базовое масштабирование

```bash

# Увеличение одного изображения
python -m realesrgan -i input.jpg -o output.jpg -n RealESRGAN_x4plus -s 4

# Увеличение папки
python -m realesrgan -i ./inputs -o ./outputs -n RealESRGAN_x4plus -s 4
```

### Параметры

```bash
python -m realesrgan \\
    -i input.jpg \\           # Вход
    -o output.jpg \\          # Выход
    -n RealESRGAN_x4plus \\   # Имя модели
    -s 4 \\                   # Коэффициент масштабирования
    --face_enhance \\         # Включить улучшение лиц
    --fp32 \\                 # Использовать FP32 (больше VRAM, лучше качество)
    --tile 400               # Размер тайла для больших изображений
```

## Python API

### Базовое использование

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

# Настройка модели
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  # Использовать FP16
)

# Увеличение
img = cv2.imread('input.jpg', cv2.IMREAD_UNCHANGED)
output, _ = upsampler.enhance(img, outscale=4)
cv2.imwrite('output.jpg', output)
```

### С улучшением лица

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

# Модель 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 для лиц
face_enhancer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=upsampler
)

# Обработка
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)
```

### Масштабирование аниме

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

# Модель для аниме
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)
```

## Пакетная обработка

### Обработка папки

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

# Настройка
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)

# Обработать все изображения
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)
```

### Скрипт оболочки

```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 "Обработано: $filename"
    fi
done
```

## Обработка тайлами (большие изображения)

Для изображений, не помещающихся в VRAM:

```python
upsampler = RealESRGANer(
    scale=4,
    model_path='RealESRGAN_x4plus.pth',
    model=model,
    tile=400,      # Обрабатывать тайлами по 400 px
    tile_pad=10,   # Перекрытие между тайлами
    pre_pad=0,
    half=True
)
```

### Рекомендации по размеру тайла

| VRAM  | Максимальный размер тайла |
| ----- | ------------------------- |
| 4 ГБ  | 200                       |
| 6 ГБ  | 300                       |
| 8 ГБ  | 400                       |
| 12GB  | 600                       |
| 24 ГБ | 0 (без тайлинга)          |

## Увеличение масштаба видео

### Использование Real-ESRGAN

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

# Настройка модели
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)

# Открыть видео
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))

# Вывод
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

# Обработка кадров
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()
```

### Конвейер FFmpeg

```bash

# Извлечь кадры
ffmpeg -i input.mp4 -qscale:v 1 frames/frame_%06d.png

# Увеличить кадры
python -m realesrgan -i frames -o upscaled -n RealESRGAN_x4plus -s 4

# Собрать видео
ffmpeg -framerate 30 -i upscaled/frame_%06d.png -c:v libx264 -pix_fmt yuv420p output.mp4

# Вернуть звук
ffmpeg -i output.mp4 -i input.mp4 -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 final.mp4
```

## API-сервер

### Сервер 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()

# Загрузить модель
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")

# Запуск: uvicorn server:app --host 0.0.0.0 --port 8000
```

### Использование

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

## Сравнение моделей

| Модель            | Качество    | Скорость      | VRAM  | Лучше всего для             |
| ----------------- | ----------- | ------------- | ----- | --------------------------- |
| x4plus            | Лучше всего | Медленно      | 4 ГБ+ | Фотографии                  |
| x4plus\_anime\_6B | Лучше всего | Средне        | 3 ГБ+ | Аниме                       |
| x2plus            | Хорошо      | Быстро        | 2 ГБ+ | Быстрое увеличение в 2 раза |
| RealESRNet        | Нормально   | Самый быстрый | 2 ГБ+ | Предпросмотр                |

## Производительность

| Размер изображения | GPU      | Время увеличения в 4 раза |
| ------------------ | -------- | ------------------------- |
| 512x512            | RTX 3090 | \~0,5 с                   |
| 1024x1024          | RTX 3090 | \~1,5 с                   |
| 2048x2048          | RTX 3090 | \~5 с                     |
| 512x512            | RTX 4090 | \~0,3 с                   |

## Устранение неполадок

### Недостаточно памяти CUDA

```python

# Используйте тайлинг
upsampler = RealESRGANer(..., tile=200, ...)

# Или уменьшите масштаб
output, _ = upsampler.enhance(img, outscale=2)  # Вместо 4
```

### Артефакты на выходе

* Используйте меньший размер тайла с большим перекрытием
* Попробуйте другую модель (аниме или фото)
* Проверьте качество входного изображения

### Медленная обработка

* Включите FP16: `half=True`
* Увеличьте размер тайла, если позволяет VRAM
* Используйте более быструю модель: RealESRNet

## Скачать результаты

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

## Оценка стоимости

Типичные цены на маркетплейсе CLORE.AI (по состоянию на 2024 год):

| GPU        | Почасовая ставка | Дневная ставка | 4-часовая сессия |
| ---------- | ---------------- | -------------- | ---------------- |
| 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 ГБ | \~$0.17          | \~$4.00        | \~$0.70          |
| A100 80 ГБ | \~$0.25          | \~$6.00        | \~$1.00          |

*Цены зависят от провайдера и спроса. Проверьте* [*маркетплейс CLORE.AI*](https://clore.ai/marketplace) *актуальные тарифы.*

**Сэкономьте деньги:**

* Используйте **Spot** рынок для прерываемых задач — примерно треть серверов оценивает spot-цены ниже on-demand (медиана \~13% скидки), остальные совпадают с ними
* Платите **CLORE** токенами
* Сравните цены у разных провайдеров

## Дальнейшие шаги

* [Восстановление лиц GFPGAN](/guides/guides_v2-ru/obrabotka-izobrazhenii/gfpgan-face-restore.md)
* [Генерация видео с помощью ИИ](/guides/guides_v2-ru/generaciya-video/ai-video-generation.md)
* Веб-интерфейс 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-ru/obrabotka-izobrazhenii/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.
