人像背景融合

描述

将用户提供的人像与参考背景进行融合,生成新的人像图片。调用时传入一张人像图片和一张背景图片,并通过 media_type 标记各图片的用途。

图片样例

人像图片背景图片输出图片
人像图片背景图片输出图片

图片要求

支持 JPG、PNG 格式。通过 init_images 传入两张图片:

  • 背景图片:将 profile.media_profiles.media_type 设为 media_data_bg
  • 人像图片:将 profile.media_profiles.media_type 设为 media_data_fg

通过 URL 传入图片时,media_data_type 设为 url;通过 Base64 编码传入图片时,设为 jpg。示例按背景图片、人像图片的顺序传入,两张图片均需填写对应的用途标记。

调用 URL

  • 请求地址:https://openapi.meitu.com/api/v1/sdk/sync/push
  • 任务名称(task):/v1/bg_portrait_replace/bg_portrait/446025
  • 任务类型(task_type):formula

调用方法

POST

Content-Type: application/json

权限

使用 Access Key(AK)和 Secret Key(SK)进行请求签名,详见开放平台接口签名

请求参数

是否必选参数名类型参数说明
必选taskstring固定为 /v1/bg_portrait_replace/bg_portrait/446025
必选task_typestring固定为 formula
必选init_imagesobject[]两张输入图片,分别为背景图片和人像图片,使用 media_type 标记用途。
必选paramsstring本接口无需额外算法参数,传入字符串 "{}",不是 JSON 对象 {}
可选sync_timeoutint同步等待时间,单位为秒,默认 30-1 表示不等待。返回 data.status = 9 时,调用任务查询接口获取结果。
可选rsp_media_typestring结果返回方式,默认 url:返回图片 URL;jpg:返回 Base64 编码数据。该字段位于请求体顶层。本文示例使用默认的 URL 返回方式。

init_images 元素

是否必选参数名类型参数说明
必选urlstring图片 URL 或 Base64 编码数据,与 media_data_type 对应。
必选profileobject图片传输信息及用途标记。

profile

是否必选参数名类型参数说明
必选media_profilesobject图片传输方式及用途。
必选versionstring固定为 v1

media_profiles

是否必选参数名类型参数说明
必选media_data_typestringurl:图片 URL;jpg:Base64 编码的图片数据。
必选media_typestringmedia_data_bg:参考背景;media_data_fg:用户人像。

输入值示例

以下示例通过 URL 传入背景图片和人像图片。请将示例中的图片地址替换为实际可访问的地址。

{
  "task": "/v1/bg_portrait_replace/bg_portrait/446025",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/background.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url",
          "media_type": "media_data_bg"
        },
        "version": "v1"
      }
    },
    {
      "url": "https://example.com/portrait.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url",
          "media_type": "media_data_fg"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{}",
  "sync_timeout": 30
}

返回值说明

以下说明及示例使用默认的 URL 返回方式。结果图片在生成 24 小时后会被定期清理,请及时下载保存。

字段类型说明
codeint请求处理状态码,0 表示请求处理正常;非 0 表示请求失败。任务是否完成需同时检查 data.status
messagestring响应消息或错误信息。
dataobject/null任务信息;请求失败时可能为 null

data

字段类型说明
statusint任务状态:-1 未找到任务;0 已创建;1 执行中;2 失败;9 需要查询结果;10 成功。
msgstring多媒体文件的属性描述信息,按实际响应返回。
resultobject任务 ID 和处理结果。
progressnumber任务进度,例如 0.10.851

result

字段类型说明
idstring任务 ID;查询结果时作为 task_id 参数传入。
urlsstring[]任务成功后的结果图片 URL 列表。

data.status9 时,使用 data.result.id 调用任务查询接口。查询接口使用 GET https://openapi.meitu.com/api/v1/sdk/status?task_id=<任务ID>,同样需要签名。

任务查询返回 01 时表示任务尚未完成;返回 10 时获取 data.result.urls;返回 2 时表示任务失败。任务在 24 小时后过期,不支持历史任务查询。

返回值示例

请求成功返回示例

任务已完成,data.status = 10

{
  "code": 0,
  "message": "",
  "data": {
    "status": 10,
    "result": {
      "id": "50309bd5-a827-4125-bc96-62039c93770b",
      "urls": [
        "https://example.com/result.png"
      ]
    },
    "progress": 1
  }
}

需要查询返回示例

任务尚需查询结果,使用 data.result.id 作为查询接口的 task_id

{
  "code": 0,
  "message": "",
  "data": {
    "status": 9,
    "result": {
      "id": "50309bd5-a827-4125-bc96-62039c93770b"
    },
    "progress": 0
  }
}

请求失败返回示例

{
  "code": 20008,
  "message": "UNSUITABLE_IMAGE",
  "data": null
}

错误代码与信息

错误代码错误信息说明
20008UNSUITABLE_IMAGE图片不符合接口要求。

其他错误码详见 API 错误码

SDK 调用示例

以下示例使用相同的请求参数提交人像背景融合任务。调用前替换 AK、SK、背景图片 URL 和人像图片 URL。

示例打印接口响应。请求成功后,检查 data.status;状态为 9 时,按上述说明查询任务结果。

Python

先按 Python 签名 SDK 接入文档引入 SDK。

import json

import requests
from sign_sdk import sign

def api_call_example():
    key = "your_access_key"
    secret = "your_secret_key"
    url = "https://openapi.meitu.com/api/v1/sdk/sync/push"
    headers = {
        "Content-Type": "application/json",
        sign.HeaderHost: "openapi.meitu.com",
    }
    payload = {
        "task": "/v1/bg_portrait_replace/bg_portrait/446025",
        "task_type": "formula",
        "init_images": [
            {
                "url": "https://example.com/background.jpg",
                "profile": {
                    "media_profiles": {
                        "media_data_type": "url",
                        "media_type": "media_data_bg"
                    },
                    "version": "v1"
                }
            },
            {
                "url": "https://example.com/portrait.jpg",
                "profile": {
                    "media_profiles": {
                        "media_data_type": "url",
                        "media_type": "media_data_fg"
                    },
                    "version": "v1"
                }
            }
        ],
        "params": "{}",
        "sync_timeout": 30
    }
    body = json.dumps(payload, ensure_ascii=False)

    signer = sign.Signer(key, secret)
    signed_request = signer.sign(url, "POST", headers, body)
    with requests.Session() as session:
        response = session.send(signed_request, timeout=60)
        print("Status:", response.status_code)
        print("Response:", response.text)

if __name__ == "__main__":
    api_call_example()

Go

先按 Go 签名 SDK 接入文档引入 SDK。

package main

import (
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/mtlab/api/signer"
)

func main() {
	key := "your_access_key"
	secret := "your_secret_key"
	signObj := signer.NewSigner(key, secret)
	url := "https://openapi.meitu.com/api/v1/sdk/sync/push"
	headers := make(http.Header)
	headers.Set(signer.HeaderHost, "openapi.meitu.com")
	headers.Set("Content-Type", "application/json")

	body := `{
  "task": "/v1/bg_portrait_replace/bg_portrait/446025",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/background.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url",
          "media_type": "media_data_bg"
        },
        "version": "v1"
      }
    },
    {
      "url": "https://example.com/portrait.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url",
          "media_type": "media_data_fg"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{}",
  "sync_timeout": 30
}`
	req, err := signObj.Sign(url, http.MethodPost, headers, body)
	if err != nil {
		fmt.Println("Failed to sign request:", err)
		return
	}
	client := &http.Client{Timeout: 60 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Failed to read response:", err)
		return
	}
	fmt.Println("Status:", resp.StatusCode)
	fmt.Println("Response:", string(responseBody))
}

PHP

先按 PHP 签名 SDK 接入文档引入 SDK。

<?php
require_once __DIR__ . '/signer.php';

$key = 'your_access_key';
$secret = 'your_secret_key';
$url = 'https://openapi.meitu.com/api/v1/sdk/sync/push';
$headers = [
    'Content-Type' => 'application/json',
    'Host' => 'openapi.meitu.com',
];
$body = json_encode([
    'task' => '/v1/bg_portrait_replace/bg_portrait/446025',
    'task_type' => 'formula',
    'init_images' => [
        [
            'url' => 'https://example.com/background.jpg',
            'profile' => [
                'media_profiles' => [
                    'media_data_type' => 'url',
                    'media_type' => 'media_data_bg',
                ],
                'version' => 'v1',
            ],
        ],
        [
            'url' => 'https://example.com/portrait.jpg',
            'profile' => [
                'media_profiles' => [
                    'media_data_type' => 'url',
                    'media_type' => 'media_data_fg',
                ],
                'version' => 'v1',
            ],
        ],
    ],
    'params' => '{}',
    'sync_timeout' => 30,
], JSON_UNESCAPED_SLASHES);

$signer = new Signer($key, $secret);
$curl = $signer->sign($url, 'POST', $headers, $body);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
$response = curl_exec($curl);

if ($response === false) {
    echo 'Error: ' . curl_error($curl) . PHP_EOL;
} else {
    echo 'Status: ' . curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL;
    echo 'Response: ' . $response . PHP_EOL;
}
curl_close($curl);

Java

先按 Java 签名 SDK 接入文档引入 SDK。

import com.meitu.openai.common.Signer;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        Signer signer = new Signer("your_access_key", "your_secret_key");
        String url = "https://openapi.meitu.com/api/v1/sdk/sync/push";
        String method = "POST";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put(Signer.HeaderHost, "openapi.meitu.com");

        String body = "{\n"
                + "  \"task\": \"/v1/bg_portrait_replace/bg_portrait/446025\",\n"
                + "  \"task_type\": \"formula\",\n"
                + "  \"init_images\": [\n"
                + "    {\n"
                + "      \"url\": \"https://example.com/background.jpg\",\n"
                + "      \"profile\": {\n"
                + "        \"media_profiles\": {\n"
                + "          \"media_data_type\": \"url\",\n"
                + "          \"media_type\": \"media_data_bg\"\n"
                + "        },\n"
                + "        \"version\": \"v1\"\n"
                + "      }\n"
                + "    },\n"
                + "    {\n"
                + "      \"url\": \"https://example.com/portrait.jpg\",\n"
                + "      \"profile\": {\n"
                + "        \"media_profiles\": {\n"
                + "          \"media_data_type\": \"url\",\n"
                + "          \"media_type\": \"media_data_fg\"\n"
                + "        },\n"
                + "        \"version\": \"v1\"\n"
                + "      }\n"
                + "    }\n"
                + "  ],\n"
                + "  \"params\": \"{}\",\n"
                + "  \"sync_timeout\": 30\n"
                + "}";

        Map<String, String> signedHeaders = signer.sign(url, method, headers, body);
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        try {
            connection.setRequestMethod(method);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.setInstanceFollowRedirects(false);
            for (Map.Entry<String, String> entry : signedHeaders.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setDoOutput(true);
            try (OutputStream output = connection.getOutputStream()) {
                output.write(body.getBytes(StandardCharsets.UTF_8));
            }

            int status = connection.getResponseCode();
            System.out.println("Status: " + status);
            InputStream stream = status >= 400
                    ? connection.getErrorStream()
                    : connection.getInputStream();
            if (stream != null) {
                try (InputStream input = stream;
                     ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                    byte[] buffer = new byte[4096];
                    int length;
                    while ((length = input.read(buffer)) != -1) {
                        output.write(buffer, 0, length);
                    }
                    System.out.println("Response: "
                            + new String(output.toByteArray(), StandardCharsets.UTF_8));
                }
            }
        } finally {
            connection.disconnect();
        }
    }
}