> 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/gfpgan-face-restore.md).

# Восстановление лица GFPGAN

Восстанавливайте и улучшайте лица на фотографиях с помощью GFPGAN.

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

## Что такое GFPGAN?

GFPGAN (Generative Facial Prior GAN) специализируется на:

* Восстановлении старых/поврежденных фотографий
* Улучшении размытых лиц
* Улучшении сгенерированных ИИ лиц
* Исправлении портретов с низким разрешением

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

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

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

**Порты:**

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

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

```bash
pip install gfpgan gradio && \\
python -c "
import gradio as gr
from gfpgan import GFPGANer
import cv2
import numpy as np

restorer = GFPGANer(
    model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=None
)

def restore(image):
    img = np.array(image)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    _, _, output = restorer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
    output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
    return output

demo = gr.Interface(fn=restore, inputs=gr.Image(), outputs=gr.Image(), title='Восстановитель лиц GFPGAN')
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 gfpgan
```

### Скачать модели

```bash

# Скачать модель восстановления лиц
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth -P ./models

# Скачать модель обнаружения
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/detection_Resnet50_Final.pth -P ./models

# Скачать модель парсинга
wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/parsing_parsenet.pth -P ./models
```

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

```bash

# Восстановить одно изображение
python inference_gfpgan.py -i input.jpg -o results -v 1.4 -s 2

# Восстановить папку
python inference_gfpgan.py -i ./inputs -o ./results -v 1.4 -s 2
```

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

```bash
python inference_gfpgan.py \\
    -i input.jpg \\      # Входное изображение/папка
    -o results \\        # Папка вывода
    -v 1.4 \\            # Версия GFPGAN (1.2, 1.3, 1.4)
    -s 2 \\              # Коэффициент масштабирования
    --bg_upsampler realesrgan \\  # Масштабирование фона
    --only_center_face  # Восстанавливать только центральное лицо
```

## Python API

### Базовое восстановление лица

```python
from gfpgan import GFPGANer
import cv2

# Инициализация
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=None
)

# Загрузить изображение
img = cv2.imread('photo.jpg')

# Восстановить лица
cropped_faces, restored_faces, restored_img = restorer.enhance(
    img,
    has_aligned=False,
    only_center_face=False,
    paste_back=True
)

# Сохранить результат
cv2.imwrite('restored.jpg', restored_img)
```

### С улучшением фона

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

# Настроить масштабировщик фона
bg_model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
bg_upsampler = RealESRGANer(
    scale=2,
    model_path='RealESRGAN_x2plus.pth',
    model=bg_model,
    half=True
)

# Настроить восстановитель лиц с улучшением фона
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2,
    bg_upsampler=bg_upsampler
)

# Обработка
img = cv2.imread('old_photo.jpg')
_, _, output = restorer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
cv2.imwrite('enhanced.jpg', output)
```

### Обработка только лиц (без возврата на исходное изображение)

```python

# Получить восстановленные отдельные лица
cropped_faces, restored_faces, _ = restorer.enhance(
    img,
    has_aligned=False,
    only_center_face=False,
    paste_back=False
)

# Сохранить каждое лицо отдельно
for i, face in enumerate(restored_faces):
    cv2.imwrite(f'face_{i}.jpg', face)
```

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

```python
import os
from gfpgan import GFPGANer
import cv2
from tqdm import tqdm

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2
)

input_dir = './old_photos'
output_dir = './restored'
os.makedirs(output_dir, exist_ok=True)

for filename in tqdm(os.listdir(input_dir)):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        img = cv2.imread(os.path.join(input_dir, filename))

        try:
            _, _, output = restorer.enhance(
                img,
                has_aligned=False,
                only_center_face=False,
                paste_back=True
            )
            cv2.imwrite(os.path.join(output_dir, filename), output)
        except Exception as e:
            print(f"Не удалось: {filename} - {e}")
```

## CodeFormer (Альтернатива)

CodeFormer — ещё один отличный восстановитель лиц:

```python

# Установка
pip install codeformer-pip

# Использование
from codeformer import CodeFormer
import cv2

restorer = CodeFormer()
img = cv2.imread('blurry_face.jpg')
result = restorer.restore(img)
cv2.imwrite('restored.jpg', result)
```

## Восстановление лиц в видео

```python
import cv2
from gfpgan import GFPGANer
from tqdm import tqdm

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Сохранить исходный размер для видео
    arch='clean',
    channel_multiplier=2
)

cap = cv2.VideoCapture('video.mp4')
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))
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

out = cv2.VideoWriter('restored_video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))

for _ in tqdm(range(total)):
    ret, frame = cap.read()
    if not ret:
        break

    try:
        _, _, restored = restorer.enhance(frame, paste_back=True)
        out.write(restored)
    except:
        out.write(frame)  # Сохранить оригинал, если восстановление не удалось

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

## API-сервер

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
from gfpgan import GFPGANer
import cv2
import numpy as np

app = FastAPI()

restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    arch='clean',
    channel_multiplier=2
)

@app.post("/restore")
async def restore_face(file: UploadFile, upscale: int = 2):
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    _, _, output = restorer.enhance(img, paste_back=True)

    _, encoded = cv2.imencode('.jpg', output)
    return Response(content=encoded.tobytes(), media_type="image/jpeg")

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

## Версии модели

| Версия | Качество    | Скорость      | Примечания        |
| ------ | ----------- | ------------- | ----------------- |
| v1.4   | Лучше всего | Средне        | Рекомендуется     |
| v1.3   | Отлично     | Быстро        | Хороший баланс    |
| v1.2   | Хорошо      | Самый быстрый | Устаревшая версия |

## Сценарии использования

### Восстановление старых фотографий

```python

# Лучшие настройки для старых фотографий
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=4,  # Более высокое масштабирование для старых фото с низким разрешением
    bg_upsampler=bg_upsampler
)
```

### Улучшение ИИ-арта

```python

# Для изображений, сгенерированных ИИ, с артефактами на лицах
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=1,  # Сохранить исходный размер
    only_center_face=True  # Сфокусироваться на основном лице
)
```

### Групповые фотографии

```python

# Обработать все лица на групповой фотографии
restorer = GFPGANer(
    model_path='GFPGANv1.4.pth',
    upscale=2,
    only_center_face=False  # Обработать ВСЕ лица
)
```

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

| Размер изображения | Лица | GPU      | Время   |
| ------------------ | ---- | -------- | ------- |
| 512x512            | 1    | RTX 3090 | \~0.2с  |
| 1024x1024          | 1    | RTX 3090 | \~0,3 с |
| 1024x1024          | 5    | RTX 3090 | \~0.8с  |
| 2048x2048          | 1    | RTX 4090 | \~0,3 с |

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

### Лицо не обнаружено

```python

# Понизить порог обнаружения
from gfpgan.utils import GFPGANer

# Или сначала вручную обрезать область лица
```

### Слишком сглаженные результаты

* Используйте CodeFormer с меньшим значением fidelity weight
* Смешайте с оригиналом с помощью альфа-композитинга

### Проблемы с VRAM

```python

# Использовать CPU для обнаружения лиц
import torch
torch.cuda.empty_cache()

# Обрабатывать лица по одному
only_center_face=True
```

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

Типичные цены на маркетплейсе 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** токенами
* Сравните цены у разных провайдеров

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

* [Масштабирование Real-ESRGAN](/guides/guides_v2-ru/obrabotka-izobrazhenii/real-esrgan-upscaling.md)
* Веб-интерфейс Stable Diffusion
* [Генерация видео с помощью ИИ](/guides/guides_v2-ru/generaciya-video/ai-video-generation.md)


---

# 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/gfpgan-face-restore.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.
