# GFPGAN 人脸修复

使用 GFPGAN 恢复并增强照片中的人脸。

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

## 什么是 GFPGAN？

GFPGAN（Generative Facial Prior GAN）专注于：

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

## 快速部署

**Docker 镜像：**

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

**端口：**

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

**命令：**

```bash
pip install gfpgan gradio && \
python -c "
print(f"已生成：{name}")
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 Face Restorer')
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 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
批处理处理
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'
output_dir = "./relit"

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"Failed: {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  # 处理所有人脸
)
```

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

| 图像大小      | 人脸 | GPU     | 时间     |
| --------- | -- | ------- | ------ |
| 分辨率       | 1  | 速度      | \~0.2s |
| RTX 4090  | 1  | 速度      | \~0.3s |
| RTX 4090  | 5  | 速度      | \~0.8s |
| 2048x2048 | 1  | 512x512 | \~0.3s |

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

### 未检测到人脸

```python

# 降低检测阈值
from gfpgan.utils import GFPGANer

# 或先手动裁剪人脸区域
```

### 过度平滑的结果

* 使用具有较低保真度权重的 CodeFormer
* 使用 alpha 合成与原图混合

### 显存问题

```python

# 使用 CPU 进行人脸检测
import torch
torch.cuda.empty_cache()

# 每次只处理一张人脸
only_center_face=True
```

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

检查文件完整性

| 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%）

## 使用以下方式支付

* [Real-ESRGAN 放大](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-chu-li/real-esrgan-upscaling)
* Stable Diffusion WebUI
* [AI 视频生成](https://docs.clore.ai/guides/guides_v2-zh/shi-pin-sheng-cheng/ai-video-generation)


---

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