# LivePortrait

从单张图像创建逼真的动画肖像。

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

{% hint style="info" %}
本指南中的所有示例都可以在通过以下方式租用的 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>`

## 什么是 LivePortrait？

Kuaishou 的 LivePortrait 功能：

* 使用驱动视频为任何肖像添加动画
* 单张照片生成视频动画
* 表情与姿态迁移
* 支持实时推理

## 资源

* **GitHub：** [KwaiVGI/LivePortrait](https://github.com/KwaiVGI/LivePortrait)
* **论文：** [LivePortrait 论文](https://arxiv.org/abs/2407.03168)
* **HuggingFace：** [KwaiVGI/LivePortrait](https://huggingface.co/KwaiVGI/LivePortrait)
* **演示：** [HuggingFace Space](https://huggingface.co/spaces/KwaiVGI/LivePortrait)

## 推荐硬件

| 组件  | 最低           | 推荐            | 最佳            |
| --- | ------------ | ------------- | ------------- |
| GPU | RTX 3070 8GB | RTX 4080 16GB | RTX 4090 24GB |
| 显存  | 8GB          | 16GB          | 24GB          |
| CPU | 4 核          | 8 核           | 16 核          |
| 内存  | 16GB         | 32GB          | 64GB          |
| 存储  | 30GB SSD     | 50GB NVMe     | 100GB NVMe    |
| 网络  | 100 Mbps     | 500 Mbps      | 1 Gbps        |

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

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

**端口：**

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

**命令：**

```bash
cd /workspace && \
git clone https://github.com/KwaiVGI/LivePortrait.git && \
cd LivePortrait && \
pip install -r requirements.txt && \
python app.py
```

## 访问您的服务

部署后，在以下位置查找您的 `http_pub` URL： **我的订单**:

1. 前往 **我的订单** 页面
2. 单击您的订单
3. 查找 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 而不是 `localhost` 在下面的示例中。

## 安装

```bash
git clone https://github.com/KwaiVGI/LivePortrait.git
cd LivePortrait
pip install -r requirements.txt

# 下载预训练模型
huggingface-cli download KwaiVGI/LivePortrait --local-dir pretrained_weights
```

## 您可以创建的内容

### 虚拟头像

* AI 网红与虚拟主播
* 客服头像
* 教育演示者

### 内容创作

* 社交媒体内容
* 营销素材
* 音乐视频概念

### 娱乐

* 为历史照片添加动画
* 角色动画
* 互动体验

### 专业用途

* 视频会议头像
* 演示助理
* 训练模拟

## 基本用法

### 命令行

```bash
python inference.py \
    --source_image path/to/portrait.jpg \
    --driving_video path/to/driving.mp4 \
    --output_path output.mp4
```

### Python API

```python
from liveportrait import LivePortraitPipeline

# 初始化管道
pipeline = LivePortraitPipeline(
    device="cuda",
    model_path="./pretrained_weights"
)

# 为肖像添加动画
result = pipeline.animate(
    source_image="portrait.jpg",
    driving_video="driving.mp4"
)

result.save("animated_portrait.mp4")
```

## 带表情控制的肖像

```python
from liveportrait import LivePortraitPipeline
import cv2

pipeline = LivePortraitPipeline(device="cuda")

# 控制特定表情
expressions = {
    "smile": 0.8,
    "eyebrow_raise": 0.3,
    "head_pitch": -5,  # degrees
    "head_yaw": 10
}

result = pipeline.animate_with_expression(
    source_image="portrait.jpg",
    expressions=expressions,
    num_frames=60,
    fps=30
)

result.save("expression_controlled.mp4")
```

## "专业影棚柔光箱"

```python
批处理处理
from liveportrait import LivePortraitPipeline

pipeline = LivePortraitPipeline(device="cuda")

# 使用相同驱动视频为多个肖像添加动画
portraits = [
    "portrait1.jpg",
    "portrait2.jpg",
    "portrait3.jpg"
]

driving = "speech_driving.mp4"
output_dir = "./animated"
output_dir = "./relit"

for i, portrait in enumerate(portraits):
    print(f"Processing {i+1}/{len(portraits)}: {portrait}")

    result = pipeline.animate(
        source_image=portrait,
        driving_video=driving
    )

    result.save(f"{output_dir}/animated_{i:03d}.mp4")
```

## result.save(f"./variations/{name}.jpg")

```python
print(f"已生成：{name}")
from liveportrait import LivePortraitPipeline
import tempfile

pipeline = LivePortraitPipeline(device="cuda")

def animate(source_image, driving_video):
    with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
        result = pipeline.animate(
            source_image=source_image,
            driving_video=driving_video
        )
        result.save(f.name)
        return f.name

generator=generator
    fn=animate,
    demo = gr.Interface(
        gr.Image(type="filepath", label="肖像图像"),
        gr.Video(label="驱动视频")
    ],
    outputs=gr.Video(label="动画肖像"),
    title="LivePortrait - 为任何肖像添加动画",
    description="上传肖像和驱动视频以创建动画视频。在 CLORE.AI GPU 服务器上运行。"
)

["example.jpg", "金色时刻的阳光从左侧照射", 25, -1],
```

## 实时网络摄像头动画

```python
import cv2
from liveportrait import LivePortraitPipeline

pipeline = LivePortraitPipeline(device="cuda")

# 加载源肖像
source = cv2.imread("portrait.jpg")
pipeline.set_source(source)

# 打开网络摄像头
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 使用当前帧作为驱动进行动画
    animated = pipeline.animate_frame(frame)

    cv2.imshow("LivePortrait", animated)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
```

## 与 TTS 集成

使用文本转语音创建会说话的头像：

```python
from liveportrait import LivePortraitPipeline
from TTS.api import TTS

# 生成语音
tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
tts.tts_to_file(
    text="Hello! Welcome to our presentation.",
    file_path="speech.wav",
    speaker_wav="reference_voice.wav",
    language="en"
)

# 从音频生成唇动驱动视频

# （使用单独的唇动同步工具或预制的驱动视频）

# 为肖像添加动画
pipeline = LivePortraitPipeline(device="cuda")
result = pipeline.animate(
    source_image="presenter.jpg",
    driving_video="lip_sync_driving.mp4"
)
result.save("talking_avatar.mp4")
```

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

| prompt="与背景匹配的影棚照明", | GPU      | FPS | 延迟   |
| -------------------- | -------- | --- | ---- |
| 256x256              | RTX 3070 | 30  | 33ms |
| 256x256              | 512x512  | 60+ | 16ms |
| 分辨率                  | 512x512  | 30  | 33ms |
| 分辨率                  | 2s       | 45  | 22ms |

## IC-Light-FBC

### 未检测到人脸

**与背景合成** "未在源图像中检测到人脸"

**光照未改变**

* 确保人脸清晰可见且面向镜头
* 在源图像中使用良好照明
* 裁剪图像以聚焦人脸
* 最小人脸尺寸：128x128 像素

### 动作不匹配

**与背景合成** 动画未跟随驱动视频

**光照未改变**

* 使用面部动作清晰的驱动视频
* 确保驱动视频的人脸朝向相似
* 尝试不同的驱动视频

### 质量问题

**与背景合成** 输出看起来模糊或失真

**光照未改变**

```python

# 使用更高质量设置
result = pipeline.animate(
    source_image=source,
    driving_video=driving,
    output_size=512,  # 更高分辨率
    enhance_face=True  # 启用人脸增强
)
```

### 实时延迟

**与背景合成** 网络摄像头动画存在延迟

**光照未改变**

* 使用更小的输出分辨率（256x256）
* 启用 TensorRT 优化
* 使用 RTX 4090 或更高以实现实时

```python
pipeline = LivePortraitPipeline(
    device="cuda",
    use_tensorrt=True  # 启用 TensorRT
)
```

### 音频同步问题

**与背景合成** 唇部动作与音频不匹配

**光照未改变**

* 使用音频到驱动视频的生成方法
* 在后处理时调整视频时序
* 使用 Wav2Lip 以获得更好的唇动同步

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

### 未检测到人脸

* 确保源图像中人脸清晰可见
* 使用正面照片
* 检查图像分辨率（建议 512+）

### 动画看起来不自然

* 源图像和驱动视频应具有相似的人脸角度
* 避免驱动视频中的极端表情
* 使用较短的驱动片段

### 输出视频损坏

* 安装 ffmpeg： `apt install ffmpeg`
* 检查输出格式兼容性
* 确保有足够的磁盘空间

### CUDA 错误

* 安装兼容的 PyTorch 版本
* 检查 CUDA 版本是否符合要求

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

检查文件完整性

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

## 使用以下方式支付

* [SadTalker](/guides/guides_v2-zh/hui-shuo-hua-de-tou-xiang/sadtalker.md) - 替代的会说话头像方案
* [Wav2Lip](/guides/guides_v2-zh/hui-shuo-hua-de-tou-xiang/wav2lip.md) - 更好的唇动同步
* [XTTS](/guides/guides_v2-zh/yin-pin-yu-yu-yin/xtts-coqui.md) - 语音生成


---

# 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/hui-shuo-hua-de-tou-xiang/liveportrait.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.
