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

# GFPGAN 人脸修复

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

### 访问你的服务器

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

## 什么是 GFPGAN？

GFPGAN（生成式人脸先验 GAN）专注于：

* 修复旧照片/受损照片
* 增强模糊的人脸
* 改进 AI 生成的人脸
* 修复低分辨率肖像

## 快速部署

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

### AI 艺术增强

```python

# 适用于带有人脸瑕疵的 AI 生成图像
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
* 使用 alpha 合成与原图融合

### 显存问题

```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 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

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

**节省费用：**

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

## 下一步

* [Real-ESRGAN 超分辨率放大](/guides/guides_v2-zh/tu-xiang-chu-li/real-esrgan-upscaling.md)
* Stable Diffusion WebUI
* [AI 视频生成](/guides/guides_v2-zh/shi-pin-sheng-cheng/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-zh/tu-xiang-chu-li/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.
