AI换装

描述

本接口用于在云端按照指定换装模板处理输入图像,生成 AI 换装图像。

版本

1.0

图片要求

图片格式:JPG、PNG。

调用 URL

    正式环境:https://openapi.meitu.com
    任务提交接口:https://openapi.meitu.com/api/v1/sdk/sync/push
    任务名称(task):/v1/AI_Change_Clothes/change_clothes_default/477312
    任务类型(task_type):formula

task 的最后一段是换装 ID。本文请求与 SDK 示例使用原文列出的“黄油月光”换装 ID 477312;使用其他换装模板时,应将最后一段替换为对应的换装 ID。

调用方法

POST

Content-Type: application/json

权限

开放平台接口签名

请求参数

是否必选参数名类型参数说明
必选paramsstring算法参数(JSON 字符串);原接口算法参数默认为空,统一封装后 parameter 传空对象
必选init_imagesobject[]图片文件列表
必选taskstring本文示例固定 /v1/AI_Change_Clothes/change_clothes_default/477312;最后一段为换装 ID
必选task_typestring固定 formula
可选sync_timeoutint默认 30-1 表示不等待;同步超时且 status 返回 9 时使用查询接口

init_images 多媒体文件参数,结构说明如下

是否必选参数名类型参数说明
必选urlstring图片 URL 或 base64
必选profileobject属性信息描述

profile 属性信息描述

是否必选参数名类型参数说明
必选media_profilesobject图片属性信息
必选versionstring固定 v1

media_profiles 媒体属性信息

是否必选参数名类型参数说明
必选media_data_typestringurl 表示图片 URL;jpg 表示经过 base64 编码的 JPG 图片

params 推理参数是 JSON 字符串,其结构说明如下

是否必选字段类型说明
可选rsp_media_typestring默认 urljpg 表示结果图像以 base64 返回,url 表示返回图像 URL
必选parameterobject算法核心参数对象;本接口传空对象 {}

parameter 算法参数详情

是否必选字段类型说明
原接口没有算法核心参数

换装模板素材 ID

名称换装 ID
黄油月光477312
墨染和服477307

更多换装素材请访问美图 AI 开放平台,通过页面右下角联系方式联系客服。

输入值示例

{
  "task": "/v1/AI_Change_Clothes/change_clothes_default/477312",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"rsp_media_type\":\"url\",\"parameter\":{}}",
  "sync_timeout": 30
}

返回值说明

注意,生成的结果,会定期清理,请及时下载保存
字段类型说明
request_idstring请求标识
trace_idstring链路追踪标识
codeint业务状态码,0 表示请求受理成功
error_codeint错误码,成功时为 0
messagestring业务信息
tipsany补充提示,可为 null
dataobject任务状态和算法结果

data 中单个元素的字段说明

字段类型说明
statusint状态码:-1 未找到任务;0 创建成功;1 执行中;2 失败;9 超时,使用查询接口查询;10 成功
resultobject算法结果;原始响应字段映射到此对象内
progressnumber任务进度,例如 0.10.851
predict_elapsedint预计耗时,毫秒
create_timeint64创建时间戳,毫秒
task_idstring任务 ID
custom_task_idstring客户自定义任务 ID
trace_idstringdata 内链路标识
client_infostring客户端信息
init_imagesobject[]/null输入媒体回显

result 中单个元素的字段说明

字段类型说明
idstring算法任务 ID
urlsstring[]生成图片地址
msgstring原接口返回的多媒体文件相关属性信息描述
error_codeint算法错误码;失败时可能为 20001
error_messagestring算法错误信息;20001 对应 PROCESS_ERROR(处理错误)

返回值示例

请求成功返回示例

Response Status:200

content-type 为 application/json; charset=utf-8

{
  "request_id": "req_50309bd5a827",
  "trace_id": "trace_50309bd5a827",
  "code": 0,
  "error_code": 0,
  "message": "",
  "tips": null,
  "data": {
    "status": 10,
    "result": {
      "id": "50309bd5-a827-4125-bc96-62039c93770b",
      "urls": [
        "https://obs.mtlab.meitu.com/mtopen/rF5GIhp5ReLKgLV91CKj5BO1q2FTLMmc/MTY5Mjg1MzIwMA==/1c39ef92-04f1-40b4-5b7e-8fcfca0c11ea.png"
      ],
      "msg": ""
    },
    "progress": 1,
    "predict_elapsed": 0,
    "create_time": 1692853200000,
    "task_id": "50309bd5-a827-4125-bc96-62039c93770b",
    "custom_task_id": "",
    "trace_id": "trace_50309bd5a827",
    "client_info": "",
    "init_images": null
  }
}

需要查询返回示例

使用 查询接口 接口查询

Response Status:200

content-type 为 application/json; charset=utf-8

{
  "request_id": "req_50309bd5a827",
  "trace_id": "trace_50309bd5a827",
  "code": 0,
  "error_code": 0,
  "message": "",
  "tips": null,
  "data": {
    "status": 9,
    "result": {},
    "progress": 0.85,
    "predict_elapsed": 1000,
    "create_time": 1692853200000,
    "task_id": "50309bd5-a827-4125-bc96-62039c93770b",
    "custom_task_id": "",
    "trace_id": "trace_50309bd5a827",
    "client_info": "",
    "init_images": null
  }
}

请求失败返回示例

Response Status:400

content-type 为 application/json; charset=utf-8

{
  "request_id": "req_50309bd5a827",
  "trace_id": "trace_50309bd5a827",
  "code": 0,
  "error_code": 0,
  "message": "",
  "tips": null,
  "data": {
    "status": 2,
    "result": {
      "error_code": 20001,
      "error_message": "PROCESS_ERROR"
    },
    "progress": 0,
    "predict_elapsed": 0,
    "create_time": 1692853200000,
    "task_id": "50309bd5-a827-4125-bc96-62039c93770b",
    "custom_task_id": "",
    "trace_id": "trace_50309bd5a827",
    "client_info": "",
    "init_images": null
  }
}

通用的错误代码与信息

详见 API 错误码

当前 API 特有的错误代码与信息:

ErrorCode 状态代码错误信息说明
20001PROCESS_ERROR处理错误

SDK 调用示例

Python

import json

import requests
from sign_sdk import sign

def api_call_example():
    key = "your_api_key"
    secret = "your_api_secret"
    url = "https://openapi.meitu.com/api/v1/sdk/sync/push"
    method = "POST"

    headers = {
        "Content-Type": "application/json",
        sign.HeaderHost: "openapi.meitu.com",
    }
    inner_params = {
        "rsp_media_type": "url",
        "parameter": {},
    }
    payload = {
        "task": "/v1/AI_Change_Clothes/change_clothes_default/477312",
        "task_type": "formula",
        "init_images": [
            {
                "url": "https://example.com/input.jpg",
                "profile": {
                    "media_profiles": {"media_data_type": "url"},
                    "version": "v1",
                },
            }
        ],
        "params": json.dumps(inner_params, ensure_ascii=False),
        "sync_timeout": 30,
    }
    body = json.dumps(payload, ensure_ascii=False)

    signer = sign.Signer(key, secret)
    signed_request = signer.sign(url, method, headers, body)
    response = requests.Session().send(signed_request)
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")

if __name__ == "__main__":
    api_call_example()

Go

package main

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

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

func main() {
	key := "your_api_key"
	secret := "your_api_secret"
	signObj := signer.NewSigner(key, secret)

	url := "https://openapi.meitu.com/api/v1/sdk/sync/push"
	method := http.MethodPost
	headers := make(http.Header)
	headers.Set(signer.HeaderHost, "openapi.meitu.com")
	headers.Set("Content-Type", "application/json")

	body := `{
  "task": "/v1/AI_Change_Clothes/change_clothes_default/477312",
  "task_type": "formula",
  "init_images": [{
    "url": "https://example.com/input.jpg",
    "profile": {
      "media_profiles": {"media_data_type": "url"},
      "version": "v1"
    }
  }],
  "params": "{\"rsp_media_type\":\"url\",\"parameter\":{}}",
  "sync_timeout": 30
}`

	req, err := signObj.Sign(url, method, headers, body)
	if err != nil {
		fmt.Println("Failed to sign request:", err)
		return
	}

	resp, err := http.DefaultClient.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("Read response failed:", err)
		return
	}
	fmt.Println("Response:", resp.StatusCode, string(responseBody))
}

PHP

<?php
require 'signer.php';

$key = 'your_api_key';
$secret = 'your_api_secret';
$signer = new Signer($key, $secret);

$url = 'https://openapi.meitu.com/api/v1/sdk/sync/push';
$method = 'POST';
$headers = ['Content-Type' => 'application/json'];

$innerParams = json_encode([
    'rsp_media_type' => 'url',
    'parameter' => (object) [],
]);

$body = json_encode([
    'task' => '/v1/AI_Change_Clothes/change_clothes_default/477312',
    'task_type' => 'formula',
    'init_images' => [
        [
            'url' => 'https://example.com/input.jpg',
            'profile' => [
                'media_profiles' => ['media_data_type' => 'url'],
                'version' => 'v1',
            ],
        ],
    ],
    'params' => $innerParams,
    'sync_timeout' => 30,
]);

$curl = $signer->sign($url, $method, $headers, $body);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status === 0) {
    echo 'Error: ' . curl_error($curl);
} else {
    echo "Status: {$status}\n";
    echo "Response: {$response}\n";
}
curl_close($curl);
?>

Java

package com.meitu.openai.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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_api_key", "your_api_secret");
        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/AI_Change_Clothes/change_clothes_default/477312\",\n" +
                "  \"task_type\": \"formula\",\n" +
                "  \"init_images\": [{\n" +
                "    \"url\": \"https://example.com/input.jpg\",\n" +
                "    \"profile\": {\n" +
                "      \"media_profiles\": {\"media_data_type\": \"url\"},\n" +
                "      \"version\": \"v1\"\n" +
                "    }\n" +
                "  }],\n" +
                "  \"params\": \"{\\\"rsp_media_type\\\":\\\"url\\\",\\\"parameter\\\":{}}\",\n" +
                "  \"sync_timeout\": 30\n" +
                "}";

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

        int status = connection.getResponseCode();
        InputStream stream = status >= 400
                ? connection.getErrorStream()
                : connection.getInputStream();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            System.out.println("Response: " + status + " " + response);
        }
    }
}