NAV
shell python php javascript C#

Taustanpoistajan API:n avulla voit integroida tekoälypohjaisen taustan poiston sovelluksiisi. Poista kuvien ja videoiden taustoja ohjelmallisesti yksinkertaisilla REST API -kutsuilla.

Aloita rekisteröidymällä API-avaimeen osoitteessa Kehittäjäportaali

Authorization: <api_key>

API-parametrien viite

Seuraavat parametrit voidaan sisällyttää API-pyyntöihisi. Kaikki tiedostojen lataukset tukevat suuria tiedostoja ilman käytännön kokorajoitusta.

Kuvankäsittelyparametrit

ParametriTyyppiOletusKuvaus
convert_tostringvaadittuAseta kuvan taustanpoistajaksi
modelstringu2netTekoälymalli: u2net (yleiset esineet/ihmiset/esineet), u2net_human_seg (optimoitu ihmisille), u2netp (nopea/kevyt)
alpha_mattingbooleanfalseOta käyttöön alfa-matto, jotta hiusten reunat ja yksityiskohdat ovat terävämmät
alpha_fgint240Etualan kynnysarvo (0–255). Korkeampi = tarkempi etualan tunnistus
alpha_bgint10Taustakynnys (0–255). Alempi = tarkempi taustan tunnistus
alpha_erodeint10Reunan eroosion koko (1–25). Säätelee reunan terävyyttä.
alpha_base_sizeint1000Alfa-mattoprosessoinnin peruskoko. Korkeampi = parempi laatu, mutta hitaampi
only_maskbooleanfalsePalauta mustavalkoinen maski läpinäkyvän kuvan sijaan
bg_typestringtransparentTaustan tyyppi: läpinäkyvä, värillinen tai kuva
bg_color_valuestring#ffffffTaustaväri heksadesimaalimuodossa (kun bg_type=color)

Videonkäsittelyparametrit

ParametriTyyppiOletusKuvaus
convert_tostringvaadittuAseta video-taustanpoistajaksi
modelstringu2netTekoälymalli: u2net (yleinen), u2net_human_seg (ihmiset), u2netp (nopea)
video_formatstringmovTulostemuoto: mov (läpinäkyvä), mattekey (mp4 matte), gif (animoitu), video_over_image, video_over_video, gif_with_bg, mp4_with_color
alpha_mattingbooleanfalseOta käyttöön alfa-matto terävämpien reunojen saamiseksi
alpha_fgint240Etualan kynnysarvo (0–255)
alpha_bgint10Taustakynnys (0–255)
alpha_erodeint10Reunan eroosion koko (1–25)
alpha_base_sizeint1000Pohjakoko alfa-mattokäsittelyä varten
video_bg_color_enabledbooleanfalseOta käyttöön tasavärinen tausta (mp4_with_color-muodolle)
video_bg_colorstring#00ff00Taustaväri heksadesimaalimuodossa
framerateintautoMukautettu lähtöruudunpäivitysnopeus (1–60 FPS). Jätä tyhjäksi, jos haluat vastaavan syötevideon.
frame_limitintnoneRajoita käsittely ensimmäisiin N kehykseen. Hyödyllinen testaukseen tai leikkeiden luomiseen.

Poista kuvan tausta

Poista kuvan tausta

import requests
import time
import shutil
import json

headers = {'Authorization': 'YOUR_API_KEY'}
file_list = ['testfiles/image.jpeg']
params = {
    'lang': 'en',
    'convert_to': 'image-backgroundremover',
    'model': 'u2net',
    'alpha_matting': 'true',
    'alpha_fg': '240',
    'alpha_bg': '10',
    'alpha_erode': '10',
}
api_domain = "api.backgroundremoverai.com"
port = "https"
api_url = f"{port}://{api_domain}/v1/convert/"
results_url = f"{port}://{api_domain}/v1/results/"


def download_file(url, local_filename):
    with requests.get(f"{port}://{api_domain}{url}", stream=True) as r:
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)
    return local_filename


def convert_files(api_url, params, headers):
    files = [eval(f'("files", open("{file}", "rb"))') for file in file_list]
    r = requests.post(
        url=api_url,
        files=files,
        data=params,
        headers=headers
    )
    if r.status_code != 200:
        print(r.status_code)
        print(r.content)
        return

    return r.json()


def get_results(params):
    if params.get('error'):
        return params.get('error')

    r = requests.post(
        url=results_url,
        data=params
    )
    data = r.json()
    finished = data.get('finished')

    while not finished:
        if int(data.get('queue_count')) > 0:
            print('queue: %s' % data.get('queue_count'))

        time.sleep(5)
        results = get_results(params)
        results = json.dumps(results)

        if results:
            break
    if finished:
        for f in data.get('files'):
            download_file("%s" % f.get('url'), "%s" % f.get('filename'))
        return {"finished": "files downloaded"}

    return r.json()


resp = convert_files(api_url, params, headers)
get_results(resp)
curl -F "lang=en" -F "convert_to=image-backgroundremover" -F "files=@image.jpeg" -H "Authorization: YOUR_API_KEY" https://api.backgroundremoverai.com/v1/convert/

{"uuid": "conversion_uuid"}

curl -F "uuid=conversion_uuid" https://api.backgroundremoverai.com/v1/results/

{"files": [{"url": "/path/to/file.png", "filename": "file.png"}], "failed": [], "finished": true, "queue_count": 0, "errors": []}





<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ERROR | E_PARSE);

$headers = array("Authorization: YOUR_API_KEY");
$file_list = ['/path/to/files/image.jpeg'];
$api_url = "https://api.backgroundremoverai.com/v1/convert/";
$results_url = "https://api.backgroundremoverai.com/v1/results/";

function download_file($url, $filename){
    $curl = curl_init();
    $url = "https://api.backgroundremoverai.com" . $url;
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSLVERSION, 3);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close ($curl);
    $destination_path = "/path/to/result/files/";
    $destination_file = fopen($destination_path . $filename, "w+");
    fwrite($destination_file, $data);
    fclose($destination_file);
}

function convert_files($file_list, $headers, $api_url) {
    $post_data['lang'] = 'en';
    $post_data['convert_to'] = 'image-backgroundremover';
    $post_data['model'] = 'u2net';
    $post_data['alpha_matting'] = 'true';

    foreach ($file_list as $index => $file) {
        $post_data['file[' . $index . ']'] = curl_file_create(
            realpath($file),
            mime_content_type($file),
            basename($file)
        );
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($curl);
    curl_close($curl);

    return json_decode($content);
}

function get_results($params, $results_url, $headers) {
    if ($params->error) {
        print_r($params->error);
        return;
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $results_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_decode(json_encode($params), true));
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $content = json_decode(curl_exec($curl));
    curl_close($curl);

    if ($content->finished == false) {
        if (intval($content->queue_count) > 0) {
            print_r("queue: $content->queue_count");
        }

        sleep(5);
        $results = get_results($params, $results_url, $headers);
        return;
    }

    foreach ($content->files as $f) {
        download_file($f->url, $f->filename);
    }
}

$resp = convert_files($file_list, $headers, $api_url);
get_results($resp, $results_url, $headers);
?>
const request = require('request');
const fs = require('fs');

let file_list = ['/testfiles/blah.jpeg']
const api_url = 'https://api.backgroundremoverai.com/v1/convert/'
const results_url = 'https://api.backgroundremoverai.com/v1/results/'

function convertFiles(file_list) {
    let formData = {
        'lang': 'en',
        'convert_to': 'image-backgroundremover',
        'model': 'u2net',
        'alpha_matting': 'true'
    };

    for (var i = 0; i < file_list.length; i ++) {
        formData['files'] = fs.createReadStream(file_list[i]);
    }

    request({
        url: api_url,
        method: 'post',
        formData: formData,
        headers: {
            "Authorization": "YOUR_API_KEY",
            "Content-Type": "multipart/form-data",
        }
    }, function(err, res, body) {
        if (err) {
            console.error(err);
            return err;
        }
        getResults(JSON.parse(body));
    });
}

function getResults(data) {
    if (data.error) {
        console.error(data);
        return data.error;
    }
    request({
        url: results_url,
        method: 'post',
        formData: data
    }, function(e, r, body) {
        response = JSON.parse(body);
        console.log(response);
        if (!response.finished) {
            setTimeout(
                function() {
                    getResults(data);
                }, 1000
            );
        }

        console.log(response);
    })
}

convertFiles(file_list);
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    static readonly HttpClient client = new HttpClient();

    static async Task Main()
    {
        client.DefaultRequestHeaders.Add("Authorization", "YOUR_API_KEY");
        var form = new MultipartFormDataContent();
        form.Add(new StringContent("en"), "lang");
        form.Add(new StringContent("image-backgroundremover"), "convert_to");
        form.Add(new StringContent("u2net"), "model");
        form.Add(new StringContent("true"), "alpha_matting");
        form.Add(new ByteArrayContent(File.ReadAllBytes("testfiles/image.jpeg")),
            "files", "image.jpeg");

        var response = await client.PostAsync(
            "https://api.backgroundremoverai.com/v1/convert/",
            form
        );
        var result = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject<dynamic>(result);

        while (!(bool)data.finished)
        {
            await Task.Delay(5000);
            var pollContent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("uuid", (string)data.uuid)
            });
            response = await client.PostAsync(
                "https://api.backgroundremoverai.com/v1/results/",
                pollContent
            );
            result = await response.Content.ReadAsStringAsync();
            data = JsonConvert.DeserializeObject<dynamic>(result);
        }

        foreach (var file in data.files)
        {
            Console.WriteLine(file.url);
        }
    }
}

API palauttaa polun käsiteltyyn tiedostoon.

/path/to/local/file_processed.png

Useiden tiedostojen käsittelyyn kannattaa sisällyttää useita tiedostoja yhteen pyyntöön. Jokainen tiedosto käsitellään ja palautetaan erikseen.

Poista videon tausta

Poista videon tausta

import requests
import time
import shutil
import json

headers = {'Authorization': 'YOUR_API_KEY'}
file_list = ['testfiles/video.mp4']
params = {
    'lang': 'en',
    'convert_to': 'video-backgroundremover',
    'model': 'u2net',
    'video_format': 'mov',
    'alpha_matting': 'true',
}
api_domain = "api.backgroundremoverai.com"
port = "https"
api_url = f"{port}://{api_domain}/v1/convert/"
results_url = f"{port}://{api_domain}/v1/results/"


def download_file(url, local_filename):
    with requests.get(f"{port}://{api_domain}{url}", stream=True) as r:
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)
    return local_filename


def convert_files(api_url, params, headers):
    files = [eval(f'("files", open("{file}", "rb"))') for file in file_list]
    r = requests.post(
        url=api_url,
        files=files,
        data=params,
        headers=headers
    )
    if r.status_code != 200:
        print(r.status_code)
        print(r.content)
        return

    return r.json()


def get_results(params):
    if params.get('error'):
        return params.get('error')

    r = requests.post(
        url=results_url,
        data=params
    )
    data = r.json()
    finished = data.get('finished')

    while not finished:
        if int(data.get('queue_count')) > 0:
            print('queue: %s' % data.get('queue_count'))

        time.sleep(5)
        results = get_results(params)
        results = json.dumps(results)

        if results:
            break
    if finished:
        for f in data.get('files'):
            download_file("%s" % f.get('url'), "%s" % f.get('filename'))
        return {"finished": "files downloaded"}

    return r.json()


resp = convert_files(api_url, params, headers)
get_results(resp)
curl -F "lang=en" -F "convert_to=video-backgroundremover" \
     -F "files=@video.mp4" \
     -H "Authorization: YOUR_API_KEY" https://api.backgroundremoverai.com/v1/convert/

{"uuid": "conversion_uuid"}

curl -F "uuid=conversion_uuid" https://api.backgroundremoverai.com/v1/results/

{"files": [{"url": "/path/to/file.mov", "filename": "file.mov"}], "failed": [], "finished": true, "queue_count": 0, "errors": []}





<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ERROR | E_PARSE);

$headers = array("Authorization: api_key");
$file_list = ['/path/to/files/blah.mp4'];
$api_url = "https://api.backgroundremoverai.com/v1/convert/";
$results_url = "https://api.backgroundremoverai.com/v1/results/";

function download_file($url, $filename){
    $curl = curl_init();
    $url = "https://api.backgroundremoverai.com" . $url;
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSLVERSION, 3);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close ($curl);
    $destination_path = "/path/to/result/files/";
    $destination_file = fopen($destination_path . $filename, "w+");
    fwrite($destination_file, $data);
    fclose($destination_file);
}

function convert_files($file_list, $headers, $api_url) {
    $post_data['lang'] = 'en';
    $post_data['convert_to'] = 'video-backgroundremover';

    foreach ($file_list as $index => $file) {
        $post_data['file[' . $index . ']'] = curl_file_create(
            realpath($file),
            mime_content_type($file),
            basename($file)
        );
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($curl);
    curl_close($curl);

    return json_decode($content);
}

function get_results($params, $results_url, $headers) {
    if ($params->error) {
        print_r($params->error);
        return;
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $results_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_decode(json_encode($params), true));
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $content = json_decode(curl_exec($curl));
    curl_close($curl);

    if ($content->finished == false) {
        if (intval($content->queue_count) > 0) {
            print_r("queue: $content->queue_count");
        }

        sleep(5);
        $results = get_results($params, $results_url, $headers);
        return;
    }

    foreach ($content->files as $f) {
        download_file($f->url, $f->filename);
    }
}

$resp = convert_files($file_list, $headers, $api_url);
get_results($resp, $results_url, $headers);
?>
const request = require('request');
const fs = require('fs');

let file_list = ['/testfiles/blah.mp4']
const api_url = 'https://api.backgroundremoverai.com/v1/convert/'
const results_url = 'https://api.backgroundremoverai.com/v1/results/'

function convertFiles(file_list) {
    let formData = {
        'lang': 'en',
        'convert_to': 'video-backgroundremover'
    };

    for (var i = 0; i < file_list.length; i ++) {
        formData['files'] = fs.createReadStream(file_list[i]);
    }

    request({
        url: api_url,
        method: 'post',
        formData: formData,
        headers: {
            "Authorization": "YOUR_API_KEY",
            "Content-Type": "multipart/form-data",
        }
    }, function(err, res, body) {
        if (err) {
            console.error(err);
            return err;
        }
        getResults(JSON.parse(body));
    });
}

function getResults(data) {
    if (data.error) {
        console.error(data);
        return data.error;
    }
    request({
        url: results_url,
        method: 'post',
        formData: data
    }, function(e, r, body) {
        response = JSON.parse(body);
        console.log(response);
        if (!response.finished) {
            setTimeout(
                function() {
                    getResults(data);
                }, 1000
            );
        }

        console.log(response);
    })
}

convertFiles(file_list);
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    static readonly HttpClient client = new HttpClient();

    static async Task Main()
    {
        client.DefaultRequestHeaders.Add("Authorization", "YOUR_API_KEY");
        var form = new MultipartFormDataContent();
        form.Add(new StringContent("en"), "lang");
        form.Add(new StringContent("video-backgroundremover"), "convert_to");
        form.Add(new StringContent("u2net"), "model");
        form.Add(new StringContent("mov"), "video_format");
        form.Add(new StringContent("true"), "alpha_matting");
        form.Add(new ByteArrayContent(File.ReadAllBytes("testfiles/video.mp4")),
            "files", "video.mp4");

        var response = await client.PostAsync(
            "https://api.backgroundremoverai.com/v1/convert/",
            form
        );
        var result = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject<dynamic>(result);

        while (!(bool)data.finished)
        {
            await Task.Delay(5000);
            var pollContent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("uuid", (string)data.uuid)
            });
            response = await client.PostAsync(
                "https://api.backgroundremoverai.com/v1/results/",
                pollContent
            );
            result = await response.Content.ReadAsStringAsync();
            data = JsonConvert.DeserializeObject<dynamic>(result);
        }

        foreach (var file in data.files)
        {
            Console.WriteLine(file.url);
        }
    }
}

API palauttaa polun käsiteltyyn tiedostoon.

/path/to/local/file_processed.mov
/path/to/local/file_processed.gif

Useiden tiedostojen käsittelyyn kannattaa sisällyttää useita tiedostoja yhteen pyyntöön. Jokainen tiedosto käsitellään ja palautetaan erikseen.