namifusion 图片换脸

namifusion/faceswap-image

NamiFusion 换脸模型 轻松实现单人或多人换脸。兼容多种 model_style 风格,可直接输出真实效果或一键美颜优化结果,换脸自然又好看!

示例

namifusion 图片换脸 example 1

参数

名称类型默认约束说明
source_url *源人脸image_upload0–1 items输入人脸的文件URL
target_url *目标人脸image_upload0–1 items要被替换的人脸的文件URL
single_face_mode是否单人换脸boolean是否按照单人换脸执行任务
model_style模型风格selectrealisticrealistic | beautify | lossless换脸风格。Realistic:自然真实的肤色与质感。Beautify:磨皮提亮美颜优化。Lossless:完全保留原始面部细节,最高保真度。
face_enhance人脸增强boolean是否开启人脸增强, 开启后人脸会更加高清
face_mapping人脸映射array<object>[]多人换脸必传参数。每项定义一组源人脸到目标人脸的映射关系。通过人脸检测API获取人脸信息后组装成此数组。`source_face_info.face_url`为要换入的新脸,`target_face_info.face_url`为要被替换的目标脸。
source_face_index输入人脸的索引number≥ 0
target_face_index目标人脸的索引number≥ 0
source_face_info源输入人脸信息object
target_face_info目标人脸信息object

输出字段

字段类型说明
videosarray<string>Image FaceSwap Pro result image URL

API

通过统一 REST API 调用本模型;在 API Keys 页获取密钥。

cURL
# 1) Submit — returns { "task_uuid": "..." }
curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-image" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "input": {
    "source_url": [
      "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
    ],
    "target_url": [
      "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-02-24/94a3eefdb397.png"
    ],
    "single_face_mode": true,
    "model_style": "realistic",
    "face_enhance": false,
    "face_mapping": []
  }
}'

# 2) Poll until status is "completed", then read the output URLs
curl "https://www.namifusion.com/api/v1/marketplace/run/tasks/TASK_UUID" \
  -H "Authorization: Bearer YOUR_API_KEY"
Python
import time, requests

API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 1) Submit
resp = requests.post(
    "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-image",
    headers=HEADERS,
    json={
        "input": {
            "source_url": [
                "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
            ],
            "target_url": [
                "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-02-24/94a3eefdb397.png"
            ],
            "single_face_mode": True,
            "model_style": "realistic",
            "face_enhance": False,
            "face_mapping": []
        }
    },
)
resp.raise_for_status()  # 401/402/429/5xx stop here instead of polling a bad task
task = resp.json()

# 2) Poll until a terminal state (completed / failed / cancelled).
#    This model is allowed up to 300s server-side.
deadline = time.time() + 360
while task.get("status") not in ("completed", "failed", "cancelled"):
    if time.time() > deadline:
        raise TimeoutError(f"still {task.get('status')} — keep the task_uuid and poll later")
    time.sleep(3)
    poll = requests.get(f"https://www.namifusion.com/api/v1/marketplace/run/tasks/{task['task_uuid']}", headers=HEADERS)
    poll.raise_for_status()
    task = poll.json()

print(task["status"], task.get("output"))
JavaScript
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };

// 1) Submit
const resp = await fetch("https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-image", {
  method: "POST",
  headers: { ...HEADERS, "Content-Type": "application/json" },
  body: JSON.stringify({
    "input": {
      "source_url": [
        "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
      ],
      "target_url": [
        "https://kaito-1328216764.cos.ap-tokyo.myqcloud.com/marketplace/thumbnails/2026-02-24/94a3eefdb397.png"
      ],
      "single_face_mode": true,
      "model_style": "realistic",
      "face_enhance": false,
      "face_mapping": []
    }
  }),
});
if (!resp.ok) throw new Error(`submit failed: ${resp.status} ${await resp.text()}`);
let task = await resp.json();

// 2) Poll until a terminal state (completed / failed / cancelled).
//    This model is allowed up to 300s server-side.
const deadline = Date.now() + 360 * 1000;
while (!["completed", "failed", "cancelled"].includes(task.status)) {
  if (Date.now() > deadline) throw new Error(`still ${task.status} — keep the task_uuid and poll later`);
  await new Promise((r) => setTimeout(r, 3000));
  const poll = await fetch(`https://www.namifusion.com/api/v1/marketplace/run/tasks/${task.task_uuid}`, { headers: HEADERS });
  if (!poll.ok) throw new Error(`poll failed: ${poll.status}`);
  task = await poll.json();
}

console.log(task.status, task.output);

文档

NamiFusion Image FaceSwap

AI 图片换脸:支持单人自动换脸与多人精确映射,搭配人脸检测实现完整换脸工作流。

NamiFusion Image FaceSwap 是一个高质量 AI 图片换脸服务,支持将源人脸替换到目标图片中。它提供单人换脸(自动模式)和多人换脸(精确映射模式)两种用法,并可搭配 NamiFusion Detect Faces 实现从人脸检测到换脸的完整工作流。


核心特性

  • 单人换脸: 开启 single_face_mode 即可自动完成换脸,无需任何额外配置。
  • 多人精确映射: 通过 face_mapping 精确指定源人脸与目标人脸的对应关系,支持一对一、多对多映射。
  • 面部优化: 可选的高级美颜功能,自动磨皮并消除脸部瑕疵,提升换脸后的面部质量。
  • 异步任务: 提交后返回 task_uuid,通过轮询或 Webhook 获取结果。

技术规格

参数详情
模型 IDnamifusion/faceswap-image
请求方式异步 POST(提交任务 + 轮询/Webhook 获取结果)
输入源人脸图片 URL + 目标图片 URL
输出换脸后的图片 URL
处理时间通常 5~15 秒

快速开始

API 端点

端点方法说明
/api/v1/marketplace/run/namifusion/faceswap-imagePOST提交换脸任务
/api/v1/marketplace/run/tasks/{task_uuid}GET查询任务状态与结果

认证

在请求 Header 中携带您的 API Key:

X-API-Key: sk-your-api-key

场景一:单人换脸(最简用法)

适用于源图片和目标图片中都只有一张人脸的场景。开启 single_face_mode 后无需配置 face_mapping,服务会自动完成换脸。

第 1 步:提交换脸任务

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-image" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "source_url": "https://example.com/source_face.jpg",
      "target_url": "https://example.com/target_photo.jpg",
      "single_face_mode": true
    }
  }'

响应示例:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "pending",
  "cost_credits": 10
}

第 2 步:轮询任务状态

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "X-API-Key: sk-your-api-key"

处理中:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "processing"
}

完成:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "model_id": "namifusion/faceswap-image",
  "status": "completed",
  "output": {
    "videos": ["https://cdn.namifusion.com/result/faceswap_abc123.jpg"]
  },
  "cost_credits": 10,
  "created_at": "2026-02-27T10:00:00Z",
  "completed_at": "2026-02-27T10:00:12Z"
}

输出字段名为 videos,但图片换脸时返回的是图片 URL。该字段统一用于存放换脸结果文件。


场景二:多人换脸

当目标图片中有多个人脸,且需要精确控制"用哪张源脸替换哪张目标脸"时,需要先调用 Detect Faces 获取人脸信息,再构建 face_mapping 提交换脸任务。

第 1 步:检测目标图片中的人脸

调用 NamiFusion Detect Faces(POST /api/v1/marketplace/run/namifusion/detect_faces)提交检测任务,然后轮询获取结果。

提交检测任务:

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/detect_faces" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "url": "https://example.com/group_photo.jpg",
      "return_face_url": true
    }
  }'

轮询任务结果:

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/{task_uuid}" \
  -H "X-API-Key: sk-your-api-key"

完成响应(假设检测到 3 个人脸):

{
  "task_uuid": "...",
  "status": "completed",
  "output": {
    "error_code": 0,
    "error_msg": "SUCCESS",
    "faces_obj": {
      "0": {
        "region": [[50, 80, 150, 200], [250, 70, 350, 190], [450, 90, 550, 210]],
        "face_urls": [
          "https://s3.amazonaws.com/faces/target_face_0.jpg",
          "https://s3.amazonaws.com/faces/target_face_1.jpg",
          "https://s3.amazonaws.com/faces/target_face_2.jpg"
        ],
        "landmarks": [[[...]], [[...]], [[...]]],
        "frame_time": null,
        "crop_region": [[...], [...], [...]],
        "landmarks_str": ["...", "...", "..."],
        "crop_landmarks": ["...", "...", "..."]
      }
    }
  }
}

此时你已知道目标图片中有 3 个人脸(faces_obj["0"].region 长度为 3),以及他们的 face_urls

第 2 步:检测源人脸图片

同样调用 Detect Faces 提交检测任务并轮询结果(如果你有多张源脸图片,或需要精确传递人脸坐标信息)。

提交检测任务:

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/detect_faces" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "url": "https://example.com/source_face.jpg",
      "return_face_url": true
    }
  }'

完成响应:

{
  "task_uuid": "...",
  "status": "completed",
  "output": {
    "error_code": 0,
    "error_msg": "SUCCESS",
    "faces_obj": {
      "0": {
        "region": [[100, 50, 200, 180]],
        "face_urls": ["https://s3.amazonaws.com/faces/source_face_0.jpg"],
        "landmarks": [[[...]]],
        "frame_time": null,
        "crop_region": [[...]],
        "landmarks_str": ["..."],
        "crop_landmarks": ["..."]
      }
    }
  }
}

第 3 步:构建 face_mapping

根据检测结果,构建源人脸到目标人脸的映射关系。这里 source_face_info.face_urltarget_face_info.face_url 的图片中都只有一张人脸。

将 Detect Faces 返回的 face_urls 中对应的 URL 分别作为 source_face_info.face_urltarget_face_info.face_url 填入 face_mapping

"face_mapping": [
  {
    "source_face_info": {
      "face_url": "https://s3.amazonaws.com/faces/source_face_0.jpg"
    },
    "target_face_info": {
      "face_url": "https://s3.amazonaws.com/faces/target_face_1.jpg"
    }
  }
]

其中 face_url 直接使用第 1、2 步中 Detect Faces 返回的 output.faces_obj["0"].face_urls[i] 值即可。

face_mapping 中还支持 source_face_indextarget_face_indexbbox 等参数,详见后文「face_mapping 详解」章节。

第 4 步:提交多人换脸任务

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-image" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "source_url": "https://example.com/source_face.jpg",
      "target_url": "https://example.com/group_photo.jpg",
      "single_face_mode": false,
      "face_mapping": [
        {
          "source_face_info": {
            "face_url": "https://s3.amazonaws.com/faces/source_face_0.jpg"
          },
          "target_face_info": {
            "face_url": "https://s3.amazonaws.com/faces/target_face_1.jpg"
          }
        }
      ]
    }
  }'

响应:

{
  "task_uuid": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "status": "pending",
  "cost_credits": 10
}

第 5 步:获取换脸结果

轮询任务状态直到 status 变为 completed

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/b2c3d4e5-f6a7-8901-bcde-f12345678901" \
  -H "X-API-Key: sk-your-api-key"

完成响应:

{
  "task_uuid": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "model_id": "namifusion/faceswap-image",
  "status": "completed",
  "output": {
    "videos": ["https://cdn.namifusion.com/result/faceswap_def456.jpg"]
  },
  "cost_credits": 10,
  "created_at": "2026-02-27T10:05:00Z",
  "completed_at": "2026-02-27T10:05:14Z"
}

Python 完整示例:多人换脸工作流

以下示例演示了从人脸检测到多人图片换脸的完整流程:

import requests
import time

API_KEY = "sk-your-api-key"
BASE_URL = "https://www.namifusion.com/api/v1/marketplace/run"
HEADERS = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
}

source_url = "https://example.com/source_face.jpg"
target_url = "https://example.com/group_photo.jpg"


def detect_faces(image_url):
    """Submit face detection task and poll for result."""
    task = requests.post(
        f"{BASE_URL}/namifusion/detect_faces",
        headers=HEADERS,
        json={"input": {"url": image_url, "return_face_url": True}},
    ).json()

    while True:
        resp = requests.get(
            f"{BASE_URL}/tasks/{task['task_uuid']}",
            headers=HEADERS,
        ).json()

        if resp["status"] == "completed":
            return resp["output"]
        elif resp["status"] == "failed":
            raise Exception(resp.get("error_message", "Unknown error"))

        time.sleep(3)


# Step 1: detect faces in target image
target_detect = detect_faces(target_url)
target_frame = target_detect["faces_obj"]["0"]

print(f"Target has {len(target_frame['face_urls'])} faces")
for i, face_url in enumerate(target_frame["face_urls"]):
    print(f"  Face {i}: region={target_frame['region'][i]}")

# Step 2: detect faces in source image
source_detect = detect_faces(source_url)
source_frame = source_detect["faces_obj"]["0"]

# Step 3: build face_mapping (replace target face 1 with source face 0)
face_mapping = [
    {
        "source_face_info": {"face_url": source_frame["face_urls"][0]},
        "target_face_info": {"face_url": target_frame["face_urls"][1]},
    }
]

# Step 4: submit faceswap task
task_resp = requests.post(
    f"{BASE_URL}/namifusion/faceswap-image",
    headers=HEADERS,
    json={
        "input": {
            "source_url": source_url,
            "target_url": target_url,
            "single_face_mode": False,
            "face_mapping": face_mapping,
        }
    },
).json()

task_uuid = task_resp["task_uuid"]
print(f"Task submitted: {task_uuid}")

# Step 5: poll for result
while True:
    status_resp = requests.get(
        f"{BASE_URL}/tasks/{task_uuid}",
        headers=HEADERS,
    ).json()

    status = status_resp["status"]
    print(f"Status: {status}")

    if status == "completed":
        result_url = status_resp["output"]["videos"][0]
        print(f"Result: {result_url}")
        break
    elif status == "failed":
        print(f"Failed: {status_resp.get('error_message', 'Unknown error')}")
        break

    time.sleep(5)

参数与返回值详解

请求参数

请求体格式为 JSON,所有参数放在 input 对象中:

{
  "input": {
    "source_url": "https://...",
    "target_url": "https://...",
    "single_face_mode": true,
    "face_enhance": false,
    "face_mapping": [],
    "model_style": "realistic"
  }
}
参数类型必填默认值说明
source_urlstring-源人脸图片 URL(要换上去的脸)。必须可公开访问。
target_urlstring-目标图片 URL(被换脸的图片)。必须可公开访问。
single_face_modebooleantrue单人脸模式。开启时自动完成换脸,无需配置 face_mapping
face_enhancebooleanfalse是否启用面部优化。开启后自动磨皮并消除脸部瑕疵,面部质量更高,但会增加处理时间。
face_mappingarraynull人脸映射配置。仅在 single_face_mode: false 时生效。详见下方说明。
model_stylestring"realistic"换脸风格。可选值:"realistic"(写实)、"beautify"(美颜)、"lossless"(无损)。详见「参数对输出结果的影响」章节。

face_mapping 详解

face_mapping 是一个数组,每个元素定义一组源人脸到目标人脸的映射关系:

字段类型必填说明
source_face_indexinteger源图片中人脸的索引(0-based,从左到右排序)。
target_face_indexinteger目标图片中人脸的索引(0-based,从左到右排序)。
source_face_infoobject源人脸的坐标信息。传入后跳过内部重新检测,保证人脸顺序一致。
target_face_infoobject目标人脸的坐标信息。传入后提升匹配精度。

source_face_info 字段

字段类型说明
bboxnumber[]人脸边界框 [x1, y1, x2, y2]
kpsnumber[][]人脸 5 个关键点坐标。传入后后端直接使用,跳过重新检测。

target_face_info 字段

字段类型说明
bboxnumber[]目标人脸边界框 [x1, y1, x2, y2]

任务状态

提交任务后通过轮询获取状态,建议轮询间隔 5 秒:

状态说明
pending任务已创建,等待处理。
processing任务正在处理中。
completed任务已完成,可从 output.videos 获取结果 URL。
failed任务失败,查看 error_message 了解原因。

返回值结构

提交任务响应

字段类型说明
task_uuidstring任务唯一标识,用于后续查询状态。
statusstring初始状态,通常为 pending
cost_creditsnumber本次任务消耗的积分。

任务完成响应

字段类型说明
task_uuidstring任务唯一标识。
model_idstring模型 ID(namifusion/faceswap-image)。
statusstring任务状态。
output.videosstring[]换脸结果图片 URL 列表。
cost_creditsnumber消耗积分。
created_atstring任务创建时间(ISO 8601)。
completed_atstring任务完成时间(ISO 8601)。
error_messagestring错误信息(仅 failed 时返回)。

参数对输出结果的影响

参数对结果的影响
single_face_mode: true自动完成换脸,适合单人场景,无需配置 face_mapping
single_face_mode: false + face_mapping精确控制替换哪些人脸。未在 mapping 中指定的人脸保持原样不变。
face_enhance: true开启面部优化,自动磨皮并消除脸部瑕疵,面部更精致自然,但处理时间增加约 20~50%。
face_enhance: false默认模式,不做额外面部处理,处理速度更快。
model_style: "realistic"写实风格。呈现接近真实人脸的自然风格,保留生活化的肤色与质感。
model_style: "beautify"美颜风格。自动磨皮提亮,带来精致柔嫩的观感。
model_style: "lossless"无损风格。极致无损模式,完美保留原始脸部所有细节,真实度最高且几乎难以辨别。

注意事项

  1. URL 必须可公开访问source_urltarget_url 都必须是可直接下载的公开 URL。
  2. 人脸索引排序规则source_face_indextarget_face_index 都从 0 开始,按人脸 bbox 左上角的 x 坐标从左到右排序。
  3. 强烈建议传递 face_info:如果你已经调用过 Detect Faces,将检测到的 bbox 传入 face_mapping,可以避免换脸服务内部重新检测导致的索引不一致问题。
  4. 轮询间隔:建议每 5 秒轮询一次任务状态。图片换脸通常 5~15 秒完成。
  5. 结果字段名:输出字段名为 output.videos,但图片换脸返回的是图片 URL,这是接口的统一命名。