cutcout_api

Description

This API is used for cloud-based saliency detection requests, which can automatically identify salient target regions in images. It supports three types of saliency detection: portrait, product, and graphic. It can return detection result images or mask images, and supports advanced features such as edge detail optimization.

Version

1.0

Image Requirements

  • Image FormatJPG, PNG, HEIC
  • Image Pixel DimensionsMinimum 224×224 pixels, maximum 3000×3000 pixels
  • Image File SizeRecommended to be within 3MB

Call URL

Production Environment: https://openapi.meitu.com Task Submission Endpoint: https://openapi.meitu.com/api/v1/sdk/sync/push Task Name (task): /v1/photo_scissors/sod Task Type (task_type): mtlab

Request Method

POST

Content-Type: application/json

Permission

https://ai.meitu.com/doc?id=218&type=api&lang=zh&domain=OUT

Request Parameters

RequiredParameter NameTypeParameter Description
YesparamsstringAlgorithm parameters (JSON string)
Yesinit_imagesobject[]Multimedia file list
YestaskstringFixed value: /v1/photo_scissors/sod
Yestask_typestringmtlab
Nosync_timeoutintDefault 30, synchronous timeout in seconds
Norsp_media_typestringDefault "url", return result type; "jpg" means base64

init_images multimedia file parameters, structure description as follows:

RequiredParameter NameTypeParameter Description
YesurlstringURL address of the multimedia, or base64
YesprofileobjectAttribute information description

profile attribute information description

RequiredParameter NameTypeParameter Description
Yesmedia_profilesobjectMedia attribute information
YesversionstringVersion information, fixed value: v1

media_profiles media attribute information

RequiredParameter NameTypeParameter Description
Yesmedia_data_typestringMedia data type, "url": indicates URL, "jpg": indicates base64

params inference parameters are a JSON string, and their structure is described as follows:

RequiredFieldTypeDescription
YesparameterobjectCore algorithm parameter object

parameter algorithm parameter details

RequiredParameter NameTypeDescription
NonMaskboolWhether to return a mask image. True returns only the mask image, False returns the result image
Nomodel_typeintSelect the matting model to use
0: Portrait matting
1: Product matting
2: Graphic matting
If not provided, the model will automatically determine which model to use
NouserboxesstringFor graphic types, user interaction box parameters can be added. Coordinates should use relative coordinates, and be sure to pass in the coordinates of four points in clockwise order starting from the top-left corner (i.e., top-left, top-right, bottom-right, bottom-left). Example: [[[0.01, 0.814], [0.12, 0.814], [0.12, 0.96], [0.01, 0.96]]]
NoblackwhiteboolWhether to return a black-and-white image. True returns only a black-and-white mask image, False returns a four-channel mask image. Default is False
NonboxboolWhether to return the target position. True returns target position top_x, top_y, bottom_x, bottom_y. Default is False
Nopost_mattingboolOnly for the product category. Whether to use the edge post-processing algorithm. Default is False. If set to True, finer edge details will be obtained, but processing time will increase by 0.2s~1s
Nouse_fe_rgbaboolControls whether to use foreground estimation. Default is False. If there are white or black edges in the matting result, set to True to use foreground estimation

Input Example

{
  "task": "/v1/photo_scissors/sod",
  "task_type": "mtlab",
  "params": "{\"parameter\":{\"nMask\":false,\"model_type\":0}}",
  "init_images": [
    {
      "url": "https://example.com/image.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "sync_timeout": 30,
  "rsp_media_type": "url"
}

Return Value Description

Note: The generated results will be periodically cleared. Please download and save them in time.
FieldTypeDescription
request_idstringRequest ID
codeintBusiness status code
messagestringBusiness message
dataobjectResult data

Field description for a single element in data:

FieldTypeDescription
statusintTask status (status code: -1 task not found, 0 task created successfully, 1 task in progress, 2 task failed, 9 task timed out: use the query API to query, 10 task succeeded)
resultobjectResult data
task_idstringTask ID
trace_idstringTrace ID
create_timeintCreation time
progressintProgress percentage
predict_elapsedintEstimated elapsed time

Field description for a single element in result:

FieldTypeDescription
parameterobjectAlgorithm parameter information
media_info_listarrayMedia file list
msgstringStatus message
msg_idstringMessage ID
codeintAlgorithm status code
error_codeintError code
error_msgstringError message
dataobjectAlgorithm return data

Return Value Examples

Request Success Response Example

Response Status: 200

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

{
  "request_id": "req_123456789",
  "trace_id": "trace_987654321",
  "code": 0,
  "error_code": 0,
  "message": "success",
  "data": {
    "status": 9,
    "result": {
      "parameter": {
        "version": "1.0",
        "exist_salient": true,
        "Kind": 0
      },
      "media_info_list": [
        {
          "media_data": "https://example.com/result.jpg",
          "media_profiles": {
            "media_data_type": "url"
          }
        }
      ],
      "msg": "success",
      "msg_id": "msg_123456",
      "code": 0,
      "error_code": 0,
      "error_msg": ""
    },
    "progress": 100,
    "predict_elapsed": 5000,
    "create_time": 1640995200000,
    "task_id": "task_1234567890",
    "trace_id": "trace_987654321",
    "client_info": "",
    "init_images": null
  }
}

Query Required Response Example

Use the query API to query

Response Status: 200

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

{
  "request_id": "",
  "trace_id": "",
  "code": 0,
  "error_code": 0,
  "message": "success",
  "data": {
    "status": 9,
    "result": {
      "id": "t_mt1a3i5n7b3da6d589-46b5-4f66-a0bb-8dd22f2a172e"
    },
    "progress": 0,
    "predict_elapsed": 10000,
    "create_time": 1759202368761,
    "task_id": "t_mt1a3i5n7b3da6d589-46b5-4f66-a0bb-8dd22f2a172e",
    "custom_task_id": "",
    "trace_id": "9129a3a2-99c4-46ce-8731-0e100e2fbee7",
    "client_info": "",
    "init_images": null
  }
}

Request Failure Response Example

Response Status: 400

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

{
  "request_id": "req_error_123456",
  "trace_id": "trace_error_789012",
  "code": 20003,
  "error_code": 20003,
  "message": "ALGO_ERROR",
  "tips": null,
  "data": {
    "status": 2,
    "result": {
      "id": "t_mt1a3i5n7be8d575cc-2ffb-4e0c-85a8-1824110e31b8",
      "code": 20003,
      "data": {
        "duration": {
          "alg_process_time": 0,
          "created_timestamp": 1759201989,
          "pull_timestamp": 1759201989,
          "repost_time": 0,
          "upload_time": 0,
          "waiting_time": 0
        },
        "error_code": 20003,
        "error_msg": "DETECT_NOT_FACE",
        "extra": {},
        "media_info_list": [],
        "msg_id": "c1b09cb2-6e05-4d21-55ab-r007b1f21bec",
        "parameter": null
      },
      "msg": "DETECT_NOT_FACE",
      "msg_id": "c1b09cb2-6e05-4d21-55ab-r007b1f21bec"
    },
    "progress": 1,
    "predict_elapsed": 10000,
    "create_time": 1759201989444,
    "task_id": "t_mt1a3i5n7be8d575cc-2ffb-4e0c-85a8-1824110e31b8",
    "custom_task_id": "",
    "trace_id": "",
    "client_info": "",
    "init_images": null
  }
}

Common Error Codes and Messages

See https://ai.meitu.com/doc?id=36 for details.

Call Example (Python)

import requests
import json
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",
    }

    # Build request parameters
    payload_dict = {
        "params": json.dumps({
            "parameter": {
                "nMask": False,
                "model_type": 0
            }
        }),
        "task": "/v1/photo_scissors/sod",
        "task_type": "mtlab",
        "init_images": [{
            "url": "https://example.com/image.jpg",
            "profile": {
                "media_profiles": {"media_data_type":"url"},
                "version": "v1"
            }
        }],
        "sync_timeout": 30,
        "rsp_media_type": "url"
    }
    body = json.dumps(payload_dict)

    try:
        signer = sign.Signer(key, secret)
        signed_request = signer.sign(url, method, headers, body)

        session = requests.Session()
        response = session.send(signed_request, verify=False)

        print(f"Status: {response.status_code}")
        print(f"Response: {response.text}")

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    api_call_example()

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 := "POST"

  headers := make(http.Header)
  headers.Set(signer.HeaderHost, "openapi.meitu.com")
  headers.Set("Content-Type", "application/json")

  // Build request body, params must be an escaped JSON string
  body := `{
    "params": "{\"parameter\": { \"nMask\": false, \"model_type\": 0 }}",
    "task": "/v1/photo_scissors/sod",
    "task_type": "mtlab",
    "init_images": [{
      "url": "YOUR_IMAGE_URL",
      "profile": {
        "media_profiles": {"media_data_type":"url"},
        "version": "v1"
      }
    }],
    "rsp_media_type": "url"
  }`

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

  client := http.DefaultClient
  resp, err := client.Do(req)
  if err != nil {
    fmt.Println("Failed to send request:", err)
    return
  }
  defer resp.Body.Close()

  bodyBytes, err := io.ReadAll(resp.Body)
  if err != nil {
    fmt.Println("Read response failed:", err)
    return
  }
  fmt.Println("Response:", resp.StatusCode, string(bodyBytes))
}

Call Example (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'
];

// JSON encode inner parameters
$innerParams = json_encode([
  "parameter" => [
    "nMask" => false,
    "model_type" => 0
  ]
]);

// Encode outer request body
$body = json_encode([
  "params" => $innerParams,
  "task" => "/v1/photo_scissors/sod",
  "task_type" => "mtlab",
  "init_images" => [
    [
      "url" => "YOUR_IMAGE_URL",
      "profile" => [
        "media_profiles" => ["media_data_type" => "url"],
        "version" => "v1"
      ]
    ]
  ],
  "sync_timeout" => 30,
  "rsp_media_type" => "url"
]);

$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;
}
curl_close($curl);
?>

Call Example (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.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.meitu.openai.common.Signer;

public class Main {
    public static void main(String[] args) throws Exception {
        Signer signer = new Signer("your api_key","api_secret");

        String url = "http://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/photo_scissors/sod\",\n" +
                "  \"task_type\": \"mtlab\",\n" +
                "  \"params\": \"{\\\"parameter\\\":{\\\"nMask\\\":false,\\\"model_type\\\":0}}\",\n" +
                "  \"init_images\": [\n" +
                "    {\n" +
                "      \"url\": \"https://example.com/image.jpg\",\n" +
                "      \"profile\": {\n" +
                "        \"media_profiles\": {\n" +
                "          \"media_data_type\": \"url\"\n" +
                "        },\n" +
                "        \"version\": \"v1\"\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"sync_timeout\": 30,\n" +
                "  \"rsp_media_type\": \"url\"\n" +
                "}";
        Map<String,String> signedHeaders = signer.sign(url, method, headers, body);
        System.out.println("signedHeader: "+signedHeaders);
        try {
            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);
            if (body!=null){
                connection.getOutputStream().write(body.getBytes());
            }
            int status = connection.getResponseCode();
            System.out.println(status);

            InputStream inputStream;
            if (status >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println("======");
            System.out.println(response.toString());
            System.out.println("======");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}