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

# Real-ESRGAN 放大

在 Clore.ai GPU 上使用 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 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

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

## 什么是 Real-ESRGAN？

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

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

## 模型变体

| 模型                            | 最适合   | 速度 |
| ----------------------------- | ----- | -- |
| RealESRGAN\_x4plus            | 普通照片  | 中等 |
| RealESRGAN\_x4plus\_anime\_6B | 动漫/绘图 | 中等 |
| RealESRGAN\_x2plus            | 2x 放大 | 快  |
| 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（更多显存，更高质量）
    --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)
```

### 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 "已处理：$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（不分块） |

## 视频超分辨率放大

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

## 模型对比

| 模型                | 质量 | 速度 | 显存   | 最适合   |
| ----------------- | -- | -- | ---- | ----- |
| x4plus            | 最佳 | 慢  | 4GB+ | 照片    |
| x4plus\_anime\_6B | 最佳 | 中等 | 3GB+ | 动漫    |
| x2plus            | 好  | 快  | 2GB+ | 快速 2x |
| RealESRNet        | 一般 | 最快 | 2GB+ | 预览    |

## 性能

| 图像尺寸      | GPU      | 4x 放大耗时 |
| --------- | -------- | ------- |
| 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`
* 如果显存允许，增大块大小
* 使用更快的模型：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 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* [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
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-zh/tu-xiang-chu-li/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.
