Background Removal v2
Description
Automatically detect the salient subject in an image and return a cutout or mask. Suitable for portraits, products, icons, and seals. If several objects are similarly prominent, the model may select a different subject than intended.
Version
1.8.1
Image Requirements
Submit one image per request. The input URL must be accessible to the service. Supported Base64 input formats are jpg, jpeg, png, bmp, webp, jfif, heic, and avif. When sending Base64 data, use the matching media type. The example below uses a URL.
Request URL
Production environment: https://openapi.meitu.com
Task submission endpoint: https://openapi.meitu.com/api/v1/sdk/sync/push
Task name (task): /v1/Background_Removal_V2/497073
Task type (task_type): formulaHTTP Method
POST
Content-Type: application/json
Authentication
Use AK/SK signing.
Request Parameters
| Required | Parameter | Type | Description |
|---|---|---|---|
| Yes | params | string | Algorithm parameters encoded as a JSON string. |
| Yes | init_images | object[] | Image list. Submit one item. |
| Yes | task | string | /v1/Background_Removal_V2/497073 |
| Yes | task_type | string | formula |
init_images
| Required | Parameter | Type | Description |
|---|---|---|---|
| Yes | url | string | Input image URL, or encoded image data for Base64 input. |
| — | profile | object | Specifies the media type in the example. |
profile
| Required | Parameter | Type | Description |
|---|---|---|---|
| — | media_profiles | object | Media properties. |
| — | version | string | Example value: v1. |
media_profiles
| Required | Parameter | Type | Description |
|---|---|---|---|
| — | media_data_type | string | Use url for an image URL, or the matching format for Base64 data. |
params
Pass the algorithm parameters as a JSON string. The decoded fields are listed below.
| Required | Parameter | Type | Description |
|---|---|---|---|
| Yes | parameter | object | Algorithm parameter object. |
parameter
| Required | Parameter | Type | Default | Description |
|---|---|---|---|---|
| No | nMask | boolean | false | true: return only the mask. false: return the cutout with an alpha channel. |
| No | blackwhite | boolean | false | Applies only when nMask=true. true returns a grayscale JPG mask; false returns a PNG mask with an alpha channel. |
| No | nbox | boolean | false | Enable to return the target bounding box in pixels: top_x, top_y, bottom_x, and bottom_y. |
| No | wbg | boolean | false | Enable to composite the cutout on a white background and output JPG. |
| No | inv_res | boolean | false | Invert the mask. Applies only when nMask=true. |
| No | use_fe_rgba | boolean | false | Enable to request an additional RGBA PNG foreground estimate for portraits and products. Icons and seals return a foreground estimate by default. |
| No | keep_resolution | boolean | true | For inputs with a long edge over 2496 pixels, true upsamples the result to the original resolution; false returns a scaled result with a 2496-pixel long edge. |
| No | userboxes | string | null | Supported only for icons. Pass a three-dimensional coordinate array encoded as a JSON string. Coordinates run from 0 to 1. Order the points top-left, top-right, bottom-right, bottom-left. |
| No | post_matting | boolean | true | Applies only to products. Edge post-processing improves edge detail and adds about 0.2–1 seconds of processing time. |
| No | model_type | integer | null | Select the model: 0 portrait, 1 product, 2 icon or seal. Omit to let the model choose automatically. |
Request Example
Return the main cutout with an alpha channel and request the object's bounding box.
{
"task": "/v1/Background_Removal_V2/497073",
"task_type": "formula",
"init_images": [
{
"url": "https://example.com/input.jpg",
"profile": {
"media_profiles": {
"media_data_type": "url"
},
"version": "v1"
}
}
],
"params": "{\"parameter\":{\"nMask\":false,\"nbox\":true}}"
}Response Fields
If the submission returns a status that requires polling, use the gateway's data.task_id with Task Query. Do not use the algorithm's msg_id for gateway polling.
Algorithm Result Fields
| Field | Description |
|---|---|
media_info_list[0].media_data | Main result. Contains an image URL or Base64 data, depending on the actual response media type. |
media_info_list[1].media_data | Additional foreground estimate. Present only when parameter.return_fe=true. |
parameter.exist_salient | Whether a salient object was detected. |
parameter.Kind | Detected category: 0 portrait, 1 product, 2 icon or seal. |
parameter.rsp_media_type | Actual response media type. |
parameter.return_fe | Whether the second image is a foreground estimate. |
parameter.use_fe_rgba | Whether RGBA foreground estimation was enabled for a portrait or product. |
parameter.top_x / top_y / bottom_x / bottom_y | Top-left and bottom-right pixel coordinates of the target bounding box. Values are populated only when nbox=true. |
parameter.seal_bbox | Seal bounding box coordinates. Empty for other categories. |
parameter.version / pull_time / process_time | Algorithm version, input image download time, and algorithm processing time. Timing values are in milliseconds. |
parameter.use_fe | Deprecated; retained for compatibility. |
Common Error Codes
See API Error Codes for gateway errors.
SDK Examples
Fill in your access and secret keys and the image URL before running the example.
Python
import requests
from sign_sdk import sign
url = "https://openapi.meitu.com/api/v1/sdk/sync/push"
body = r'''{
"task": "/v1/Background_Removal_V2/497073",
"task_type": "formula",
"init_images": [
{
"url": "https://example.com/input.jpg",
"profile": {
"media_profiles": {
"media_data_type": "url"
},
"version": "v1"
}
}
],
"params": "{\"parameter\":{\"nMask\":false,\"nbox\":true}}"
}'''
headers = {"Content-Type": "application/json", sign.HeaderHost: "openapi.meitu.com"}
signer = sign.Signer("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
request = signer.sign(url, "POST", headers, body)
with requests.Session() as session:
response = session.send(request, timeout=(10, 60), allow_redirects=False)
print(response.status_code, response.text)Go
package main
import (
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/mtlab/api/signer"
)
func main() {
url := "https://openapi.meitu.com/api/v1/sdk/sync/push"
body := `{
"task": "/v1/Background_Removal_V2/497073",
"task_type": "formula",
"init_images": [
{
"url": "https://example.com/input.jpg",
"profile": {
"media_profiles": {
"media_data_type": "url"
},
"version": "v1"
}
}
],
"params": "{\"parameter\":{\"nMask\":false,\"nbox\":true}}"
}`
headers := make(http.Header)
headers.Set(signer.HeaderHost, "openapi.meitu.com")
headers.Set("Content-Type", "application/json")
s := signer.NewSigner("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
req, err := s.Sign(url, http.MethodPost, headers, body)
if err != nil {
log.Fatal(err)
}
client := &http.Client{
Timeout: 60 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
result, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(res.StatusCode, string(result))
}PHP
<?php
require_once __DIR__ . '/signer.php';
$url = 'https://openapi.meitu.com/api/v1/sdk/sync/push';
$body = <<<'JSON'
{
"task": "/v1/Background_Removal_V2/497073",
"task_type": "formula",
"init_images": [
{
"url": "https://example.com/input.jpg",
"profile": {
"media_profiles": {
"media_data_type": "url"
},
"version": "v1"
}
}
],
"params": "{\"parameter\":{\"nMask\":false,\"nbox\":true}}"
}
JSON;
$headers = ['Host' => 'openapi.meitu.com', 'Content-Type' => 'application/json'];
$signer = new Signer('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');
$curl = $signer->sign($url, 'POST', $headers, $body);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60,
]);
$result = curl_exec($curl);
if ($result === false) {
$error = curl_error($curl);
curl_close($curl);
throw new RuntimeException($error);
}
echo curl_getinfo($curl, CURLINFO_HTTP_CODE), PHP_EOL, $result, PHP_EOL;
curl_close($curl);Java
package com.meitu.openai.common;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
String url = "https://openapi.meitu.com/api/v1/sdk/sync/push";
String body = "{\n" +
" \"task\": \"/v1/Background_Removal_V2/497073\",\n" +
" \"task_type\": \"formula\",\n" +
" \"init_images\": [\n" +
" {\n" +
" \"url\": \"https://example.com/input.jpg\",\n" +
" \"profile\": {\n" +
" \"media_profiles\": {\n" +
" \"media_data_type\": \"url\"\n" +
" },\n" +
" \"version\": \"v1\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"params\": \"{\\\"parameter\\\":{\\\"nMask\\\":false,\\\"nbox\\\":true}}\"\n" +
"}";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put(Signer.HeaderHost, "openapi.meitu.com");
Signer signer = new Signer("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY");
Map<String, String> signed = signer.sign(url, "POST", headers, body);
HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
try {
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setReadTimeout(60000);
connection.setInstanceFollowRedirects(false);
signed.forEach(connection::setRequestProperty);
connection.setDoOutput(true);
try (OutputStream out = connection.getOutputStream()) {
out.write(body.getBytes(StandardCharsets.UTF_8));
}
int status = connection.getResponseCode();
try (InputStream in = status >= 400 ? connection.getErrorStream() : connection.getInputStream()) {
String result = in == null ? "" : new String(in.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(status + " " + result);
}
} finally {
connection.disconnect();
}
}
}