# Real-ESRGAN 放大

使用 GPU 上的 Real-ESRGAN 放大并增强图像。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

* 在以下位置查找连接详情： **我的订单**
* Web 界面：使用 HTTP 端口的 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 Real-ESRGAN？

Real-ESRGAN 是一个实用的图像修复模型，它：

* 将图像放大 2x-4x
* 去除噪点和伪影
* 增强细节
* 适用于照片、动漫和艺术作品

## 1024x1024

| A100                          | 最适合   | 性能 |
| ----------------------------- | ----- | -- |
| RealESRGAN\_x4plus            | 通用照片  | 中等 |
| RealESRGAN\_x4plus\_anime\_6B | 动漫/绘画 | 中等 |
| RealESRGAN\_x2plus            | 2x 放大 | 快速 |
| RealESRNet\_x4plus            | 快速处理  | 最快 |

## 快速部署

**Docker 镜像：**

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

**端口：**

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

**命令：**

```bash
pip install realesrgan gradio && \
python -c "
print(f"已生成：{name}")
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='Scale')],
    outputs=gr.Image(type='pil'),
    title='Real-ESRGAN Upscaler'
)
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` 在下面的示例中。

## 命令行用法

### 安装

```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（占用更多显存，质量更好）
    --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
批处理处理
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'
output_dir = "./relit"

# 处理所有图像
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)
```

### Shell 脚本

```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 "Processed: $filename"
    fi
done
```

## 切片处理（大图像）

对于无法放入显存的图像：

```python
upsampler = RealESRGANer(
    scale=4,
    model_path='RealESRGAN_x4plus.pth',
    model=model,
    tile=400,      # 以 400px 切片处理
    tile_pad=10,   # 切片之间的重叠
    pre_pad=0,
    half=True
)
```

### 切片大小建议

| 显存   | 最大切片大小 |
| ---- | ------ |
| 4GB  | 200    |
| 6GB  | 300    |
| 8GB  | 400    |
| 12GB | 600    |
| 24GB | 0（不切片） |

## 视频放大（Upscaling）

### 使用 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
```

## 模型比较

| A100              | 质量 | 性能 | 显存   | 最适合     |
| ----------------- | -- | -- | ---- | ------- |
| x4plus            | 最佳 | 慢  | 4GB+ | 照片      |
| x4plus\_anime\_6B | 最佳 | 中等 | 3GB+ | 二次元（动漫） |
| x2plus            | 良好 | 快速 | 2GB+ | 快速 2x   |
| RealESRNet        | 一般 | 最快 | 2GB+ | 预览      |

## background = Image.open("studio\_bg.jpg")

| 图像大小      | GPU     | 4x 放大时间 |
| --------- | ------- | ------- |
| 分辨率       | 速度      | \~0.5s  |
| RTX 4090  | 速度      | \~1.5s  |
| 2048x2048 | 速度      | \~5s    |
| 分辨率       | 512x512 | \~0.3s  |

## # 使用固定种子以获得一致结果

### CUDA 显存不足

```python

# 使用切片
upsampler = RealESRGANer(..., tile=200, ...)

# 或降低缩放
output, _ = upsampler.enhance(img, outscale=2)  # 而不是 4
```

### 输出中的伪影

* 使用更小的切片并增加重叠
* 尝试不同的模型（动漫与照片）
* 检查输入图像质量

### 处理缓慢

* 启用 FP16： `half=True`
* 如果显存允许可增加切片大小
* 使用更快的模型：RealESRNet

## 下载结果

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

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* [GFPGAN 人脸修复](/guides/guides_v2-zh/tu-xiang-chu-li/gfpgan-face-restore.md)
* [AI 视频生成](/guides/guides_v2-zh/shi-pin-sheng-cheng/ai-video-generation.md)
* Stable Diffusion WebUI


---

# 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-zh/tu-xiang-chu-li/real-esrgan-upscaling.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.
