跳到主要内容

图像编辑:人脸迁移

功能描述

人脸迁移指的是在图像模型的生图功能基础上,将特定的人脸迁移到生成图像上。用户给定一张带有人物面部的图像,模型会提取该图像人物面部,并在依据提示词在生成图像的过程中,将该面部嵌入到生成图像中。

支持人脸迁移的模型

使用接口调用

以下将说明如何通过代码使用人脸迁移接口。

步骤一:输入API Key并定义请求函数

首先获取您的 访问令牌,然后可定义请求函数如下:

python
import requests
import base64
from PIL import Image
from io import BytesIO

API_URL = "https://ai.gitee.com/v1/images/face-migration"
headers = {
"Authorization": "Bearer <add your token>"
}

def query(payload):
files = {
"image": (payload["image"], open(payload["image"], "rb"))
}
data = {key: payload[key] for key in payload if key not in files}
response = requests.post(API_URL, headers=headers, files=files, data=data)
return response.json()

步骤二:请求并获得数据结果

请求方式如下,不过需要注意 flux 模型的提示词 (prompt) 需要是 英文

python
output = query({
"model": "flux-1-schnell",
"image": "liuyifei.png",
"size": "1024x1024",
"guidance_scale": 4,
"num_inference_steps": 4,
"id_weight": 1,
"id_timestep_start": 0,
"prompt": "Portrait painting, delicate sketch style, colored painting, ultra-high-definition, ultra-high pixel count"
})

上述代码中的提示词 Portrait painting, delicate sketch style, colored painting 要求生成一张 精致的彩色素描肖像化。 教程使用的id图像如下:

input

参数说明:

  • model:模型名,此处固定。
  • image:本地的图片路径,事实上在函数中可以看到是以二进制的形式传输。
  • size:生成图像的尺寸。
  • guidance_scale:提示词引导系数,越大则生成图片对提示词的遵从度越高。
  • num_inference_steps:生成图片的步数,该模型4步即可生成效果极佳的图片。
  • id_weight:id参考图对生成图片的影响度,越大则人脸生成的越像,可以适当调整。
  • id_timestep_start :开始在生图时嵌入人脸的步数,越小则在越早的步数中开始生成人脸,就越像。可适当调整。
  • prompt :生成图片的提示词,flux支持长文本复杂的提示词,越详细越好,可以放心大胆的写。

步骤三:解码并保存结果

得到的结果为 json,格式如下:

{
"data": [
{
"b64_json": "<b64_data>"
}
],
"created": "<id>"
}

数据结果为 Base64 编码的图像,因此需要解码后才能保存,解包、解码如下:

python
b64data = output['data'][0]['b64_json']
img = Image.open(BytesIO(base64.b64decode(b64data)))
img.save("/path/to/save/res.jpg")
img.show()

结果如下图,按照我们的要求,生成了特定人脸的彩色素描肖像化:

output

完整示例代码如下:

python
import requests
import base64
from PIL import Image
from io import BytesIO

API_URL = "https://ai.gitee.com/v1/images/face-migration"
headers = {
"Authorization": "Bearer <add your token>"
}

def query(payload):
files = {
"image": (payload["image"], open(payload["image"], "rb"))
}
data = {key: payload[key] for key in payload if key not in files}
response = requests.post(API_URL, headers=headers, files=files, data=data)
return response.json()

output = query({
"model": "flux-1-schnell",
"image": "liuyifei.png",
"size": "1024x1024",
"guidance_scale": 4,
"num_inference_steps": 4,
"id_weight": 1,
"id_timestep_start": 0,
"prompt": "a woman holding sign with glowing green text \"Gitee AI\"",
})

data = output["data"][0]["b64_json"]

stream = BytesIO(base64.b64decode(data))
img = Image.open(stream)
img.save("output.png")
img.show()