Pixian 이미지 배경 제거 API

Pixian.AI는 완전한 기능을 갖춘 이미지 배경 제거 API를 제공합니다. API는 동급 최고의 충실도로 이미지 배경을 완전히 자동으로 제거합니다.

API 키 가져오기

빠른 시작

비트맵 이미지를 POST하고 이미지 제거된 결과를 얻습니다.

$ curl https://api.pixian.ai/api/v2/remove-background \
 -u xyz123:[secret] \
 -F image=@example.jpeg \
 -o pixian_result.png
// Requires: org.apache.httpcomponents.client5:httpclient5-fluent

Request request = Request.post("https://api.pixian.ai/api/v2/remove-background")
   .addHeader("Authorization", "Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd")
   .body(
      MultipartEntityBuilder.create()
         .addBinaryBody("image", new File("example.jpeg")) // TODO: Replace with your image
         // TODO: Add more upload parameters here
         .build()
      );
ClassicHttpResponse response = (ClassicHttpResponse) request.execute().returnResponse();

if (response.getCode() == 200) {
   // Write result to disk, TODO: or wherever you'd like
   try (FileOutputStream out = new FileOutputStream("pixian_result.png")) {
      response.getEntity().writeTo(out);
   }
} else {
   System.out.println("Request Failed: Status: " + response.getCode() + ", Reason: " + response.getReasonPhrase());
}
using (var client = new HttpClient())
using (var form = new MultipartFormDataContent())
{
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "INSERT_API_KEY_HERE");
   form.Add(new ByteArrayContent(File.ReadAllBytes("example.jpeg")), "image", "example.jpeg"); // TODO: Replace with your image
   // TODO: Add more upload parameters here

   var response = client.PostAsync("https://api.pixian.ai/api/v2/remove-background", form).Result;

   if (response.IsSuccessStatusCode)
   {
      // Write result to disk, TODO: or wherever you'd like
      FileStream outStream = new FileStream("pixian_result.png", FileMode.Create, FileAccess.Write, FileShare.None);
      response.Content.CopyToAsync(outStream).ContinueWith((copyTask) => { outStream.Close(); });
   }
   else
   {
       Console.WriteLine("Request Failed: Status: " + response.StatusCode + ", Reason: " + response.ReasonPhrase);
   }
}
// Requires "request" to be installed (see https://www.npmjs.com/package/request)
var request = require('request');
var fs = require('fs');

request.post({
  url: 'https://api.pixian.ai/api/v2/remove-background',
  formData: {
    image: fs.createReadStream('example.jpeg'), // TODO: Replace with your image
    // TODO: Add more upload options here
  },
  auth: {user: 'xyz123', pass: '[secret]'},
  followAllRedirects: true,
  encoding: null
}, function(error, response, body) {
  if (error) {
    console.error('Request failed:', error);
  } else if (!response || response.statusCode != 200) {
    console.error('Error:', response && response.statusCode, body.toString('utf8'));
  } else {
    // Save result
    fs.writeFileSync("pixian_result.png", body);
  }
});
$ch = curl_init('https://api.pixian.ai/api/v2/remove-background');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array('Authorization: Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd'));
curl_setopt($ch, CURLOPT_POSTFIELDS,
    array(
      'image' => curl_file_create('example.jpeg'),
      // TODO: Add more upload options here
    ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
  // Save result
  file_put_contents("pixian_result.png", $data);
} else {
  echo "Error: " . $data;
}
curl_close($ch);
# Requires "requests" to be installed (see https://pypi.org/project/requests/)
import requests

response = requests.post(
    'https://api.pixian.ai/api/v2/remove-background',
    files={'image': open('example.jpeg', 'rb')},
    data={
        # TODO: Add more upload options here
    },
    auth=('xyz123', '[secret]')
)
if response.status_code == requests.codes.ok:
    # Save result
    with open('pixian_result.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)
# Requires: gem install httpclient
require 'httpclient'

client = HTTPClient.new default_header: {
  "Authorization" => "Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd"
}

response = client.post("https://api.pixian.ai/api/v2/remove-background", {
  "image" => File.open("example.jpeg", "rb"), # TODO: Replace with your image
  # TODO: Add more upload parameters here
})

if response.status == 200 then
  # Write result to disk, TODO: or wherever you'd like
  File.open("pixian_result.png", 'w') { |file| file.write(response.body) }
else
  puts "Error: Code: " + response.status.to_s + ", Reason: " + response.reason
end
$ curl https://api.pixian.ai/api/v2/remove-background \
 -u xyz123:[secret] \
 -F 'image.url=https://example.com/example.jpeg' \
 -o pixian_result.png
// Requires: org.apache.httpcomponents.client5:httpclient5-fluent

Request request = Request.post("https://api.pixian.ai/api/v2/remove-background")
   .addHeader("Authorization", "Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd")
   .body(
      MultipartEntityBuilder.create()
         .addTextBody("image.url", "https://example.com/example.jpeg") // TODO: Replace with your image URL
         // TODO: Add more upload parameters here
         .build()
      );
ClassicHttpResponse response = (ClassicHttpResponse) request.execute().returnResponse();

if (response.getCode() == 200) {
   // Write result to disk, TODO: or wherever you'd like
   try (FileOutputStream out = new FileOutputStream("pixian_result.png")) {
      response.getEntity().writeTo(out);
   }
} else {
   System.out.println("Request Failed: Status: " + response.getCode() + ", Reason: " + response.getReasonPhrase());
}
using (var client = new HttpClient())
using (var form = new MultipartFormDataContent())
{
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "INSERT_API_KEY_HERE");
   form.Add(new StringContent("https://example.com/example.jpeg"), "image.url"); // TODO: Replace with your image URL
   // TODO: Add more upload parameters here

   var response = client.PostAsync("https://api.pixian.ai/api/v2/remove-background", form).Result;

   if (response.IsSuccessStatusCode)
   {
      // Write result to disk, TODO: or wherever you'd like
      FileStream outStream = new FileStream("pixian_result.png", FileMode.Create, FileAccess.Write, FileShare.None);
      response.Content.CopyToAsync(outStream).ContinueWith((copyTask) => { outStream.Close(); });
   }
   else
   {
       Console.WriteLine("Request Failed: Status: " + response.StatusCode + ", Reason: " + response.ReasonPhrase);
   }
}
// Requires "request" to be installed (see https://www.npmjs.com/package/request)
var request = require('request');
var fs = require('fs');

request.post({
  url: 'https://api.pixian.ai/api/v2/remove-background',
  formData: {
    'image.url': 'https://example.com/example.jpeg', // TODO: Replace with your image
    // TODO: Add more upload options here
  },
  auth: {user: 'xyz123', pass: '[secret]'},
  followAllRedirects: true,
  encoding: null
}, function(error, response, body) {
  if (error) {
    console.error('Request failed:', error);
  } else if (!response || response.statusCode != 200) {
    console.error('Error:', response && response.statusCode, body.toString('utf8'));
  } else {
    // Save result
    fs.writeFileSync("pixian_result.png", body);
  }
});
$ch = curl_init('https://api.pixian.ai/api/v2/remove-background');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array('Authorization: Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd'));
curl_setopt($ch, CURLOPT_POSTFIELDS,
    array(
      'image.url' => 'https://example.com/example.jpeg',
      // TODO: Add more upload options here
    ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
  // Save result
  file_put_contents("pixian_result.png", $data);
} else {
  echo "Error: " . $data;
}
curl_close($ch);
# Requires "requests" to be installed (see https://pypi.org/project/requests/)
import requests

response = requests.post(
    'https://api.pixian.ai/api/v2/remove-background',
    data={
        'image.url': 'https://example.com/example.jpeg',
        # TODO: Add more upload options here
    },
    auth=('xyz123', '[secret]')
)
if response.status_code == requests.codes.ok:
    # Save result
    with open('pixian_result.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)
# Requires: gem install httpclient
require 'httpclient'

client = HTTPClient.new default_header: {
  "Authorization" => "Basic cHh4YmJ6Yjk2bjJ3OGFtOltzZWNyZXRd"
}

response = client.post("https://api.pixian.ai/api/v2/remove-background", {
  "image.url" => "https://example.com/example.jpeg", # TODO: Replace with your image URL
  # TODO: Add more upload parameters here
})

if response.status == 200 then
  # Write result to disk, TODO: or wherever you'd like
  File.open("pixian_result.png", 'w') { |file| file.write(response.body) }
else
  puts "Error: Code: " + response.status.to_s + ", Reason: " + response.reason
end

다른 제공업체에서 이전 중 이십니까? Check out our migration guide

가격

API와 무료로 통합하고 테스트할 수 있으며 구매가 필요 없습니다.

개발에는 test=true를 사용하십시오. 첫 페이지의 대화형 웹 앱을 사용하여 결과 품질을 평가할 수 있습니다.

제작 결과에는 크레딧 팩 구매가 필요합니다. 가격 페이지를 참조하십시오.

인증 및 보안

API는 표준 HTTP 기본 액세스 인증을 이용합니다. API에 대한 모든 요청은 HTTPS를 통해 이루어져야 하며 API 자격 증명을 포함해야 하며 API ID는 사용자로, API 암호는 비밀번호로 지정해야 합니다.

성공적인 요구를 하려면 귀하의 HTTP 클라이언트 라이브러리는 서버 이름 표시 (SNI)를 지원하여야 합니다. 이상한 핸드셰이크 에러를 받으면, 대부분이 이러한 이유입니다.

비율 제한

API의 사용은 관대 한 허용량으로 속도가 제한되며 상한선이 없습니다.

정상적 최종 사용자 중심 작동중에는 비율 제한을 거의 받지 않을것입니다, 그 이유는 사용이 줄어용자 중심 작동중에는 비율 제한을 거의 받지 않을것입니다, 그 이유는 사용이 줄어드는 경향이 있으며 서비스가 적절히 처리되는 방향으로 흘러갑니다.

하지만, 최대 5개의 스레드로 시작하고, 원하는 레벨의 평행에 도달할 때 까지, 매5분마다 1개의 스레드를 추가하기를 추천합니다. 100개 이상의 동시 스레드가 필요하면 시작하기 전에 알려주십시오.

너무 많은 요구를 제출하면 429 Too Many Requests를 받기 시작합니다. 이러한 일이 발생하며, 선형적으로 물러나십시오: 처음 이러한 반응을 받으면, 다음 요구를 제출하기 전에 5초를 기다리십시오. 2번째의 연속적 429 반응을 받으면, 다음 요구를 제출하기 이전에 2*5=10 초를 기다리십시오. 3번째 반응을 받으면, 3*5=15 초, 등을 기다리십시오.

요구가 성공적이면, 물러나기를 재설정하시고 매 스레드에 기존하여 물러나십시오 (예, 스레드가 서로 독립적으로 작동하여야 합니다).

타임아웃

API 요청은 일반적으로 몇 초 내에 완료되지만 일시적인 로드 급증 중에는 처리 시간이 더 길어질 수 있습니다.

클라이언트 라이브러리가 API 요청을 조기에 종료하지 않도록 하려면 최소한 180 초의 유휴 시간 제한으로 구성해야 합니다.

오류 JSON 개체

우리는 API 요청의 성공 또는 실패를 알려주기 위하여 기본 HTTP 상태를 이용하며 또한 반환된 오류 JSON 매체에 중요한 에러 정보를 포함합니다.

문제가 있는 요구에는 언제나 오류 JSON 개체를 반환하려고 합니다. 하지만, 내부 서버 실패가 비-JSON 오류 메시지로 나타나는 것은 항상 이론적으로 가능합니다.

특성

status디버깅에 도움이 되도록 응답의 HTTP 상태가 여기 다시 되풀이됩니다.
codePixian.AI 내부 에러 코드.
message디버깅에 유용한 사람이 읽을 수 있는 오류 메시지.

귀하 요구의 HTTP 상태가 200 이면, 오류 JSON 개체가 반환되지 않으며, 요구가 널리 전달되었다고 생각하여도 안전합니다.

일부 HTTP 클라이언트 라이브러리는 400 에서 599 범위로 HTTP 상태 예외를 알려줍니다. 이러한 예외를 감지하고 적절히 처리하여야 합니다.

HTTP Status의미
200-299

성공

400-499

요구에서 제공된 정보에 문제가 있습니다 (예, 매개변수가 없음) 오류 메시지를 검토하고 어떻게 수정할 것인지 알아보십시오.

500-599

Pixian.AI 내부 에러 코드가 있었습니다. 잠시 기다리신 다음 다시 시도하십시오, 그리고 문제가 계속되면 이메일을 저희한테 보내주십시오.

오류 응답 예

{
  "error" : {
    "status" : 400,
    "code" : 1006,
    "message" : "Failed to read the supplied image. "
  }
}

Delta PNG 포맷 낮은 대기 시간 및 대역폭

Pixian.AI는 Delta PNG 출력 형식을 제공하는 최초의 배경 제거 서비스임을 자랑스럽게 생각합니다. Delta PNG는 일반 PNG보다 인코딩 속도가 빠르고 크기도 훨씬 작습니다. 따라서 모바일 앱과 같이 대기 시간 및 대역폭에 민감한 애플리케이션에 매우 적합합니다.

더욱 상세히 알기 오른쪽 화살표

배경 제거 POST
https://api.pixian.ai/api/v2/remove-background

이미지에서 배경을 제거하려면, 표준 HTTP POST 파일 업로드를 합니다. 이진수 파일을 업로드할 때 콘텐츠-유형multipart/form-data가 되어야 함을 주의하십시오.

추적 변수

입력 이미지는 다음의 한 종류이어야 합니다:


이진수

이진수 파일


문자열

Base64로 인코딩된 문자열 문자열의 최대 사이즈는 1 메가바이크 입니다.


문자열

가져와서 처리할 URL입니다.

.bmp, .gif, .jpeg, .png 또는 .tiff 파일이어야 합니다.

최대 이미지 업로드 크기(= 폭 × 높이)는 32,000,000 픽셀이며 max_pixels로 축소됩니다.


부울, 기본값: false

이것이 시험 이미지임을 표시하기 위하여 true를 패스하십시오.

완제품 이미지를 위하여 false를 생략 또는 전달하십시오.

테스트 이미지들은 무료로 사용할 수 있으나, 그 결과에는 워터마크가 있습니다.


정수, 100 에서o 25000000로, 기본값: 25000000

최대 이미지 업로드 크기(= 폭 × 높이). 이보다 큰 이미지는 처리 전에 이 크기로 축소됩니다.


형식: '#RRGGBB', 예 #0055FF

결과에 적용할 배경 색 투명한 배경을 남기려면 생략하십시오.

'#'를 잊지 말고 포함하십시오.


부울, 기본값: false

결과를 전경 물체로 자를지 여부.

result.marginresult.target_size와 함께 사용하면 매번 적절한 크기와 중앙에 정렬된 결과를 얻을 수 있어 매우 유용합니다.


형식: '(x.y%|px){1,4}', 예: 10px 20% 5px 15%, 기본값: 0px

결과에 추가할 여백.

결과가 전경에서 잘리는지 여부에 관계없이 추가됩니다.

result.target_size가 지정되면 여백이 삽입됩니다. 즉, 유효 목표 크기가 확장되지 않습니다.

지원되는 단위는 %px입니다. CSS 의미 체계를 따르므로 다음 중 하나를 사용할 수 있습니다:

  • [all]
  • [top/bottom] [left/right]
  • [top] [left/right] [bottom]
  • [top] [right] [bottom] [left]


형식: 'w h', 예 1920 1080

특정 결과 크기를 픽셀 단위로 적용합니다. 결과는 지정된 크기에 맞게 조정됩니다. 초과 공간이 있는 경우 result.vertical_alignment가 수직 처리를 제어하여 항상 수평 중앙에 배치됩니다.


열거형, 기본값: middle

result.target_size 사용 시 초과 수직 공간을 할당하는 방법을 지정합니다.


열거형, 기본값: auto

출력 형식 auto는 투명한 결과의 경우 png로 해석되고, 불투명한 결과의 경우 jpeg로 해석됩니다. 즉, background.color이 지정되었습니다.

delta_png는 모바일 앱과 같이 지연 시간이 짧고 대역폭이 제한된 상황에 특히 유용한 빠르고 컴팩트한 고급 형식입니다. 배경은 투명한 검정색 0x00000000으로 인코딩되고 전경은 투명한 흰색 0x00FFFFFF으로 인코딩됩니다. 부분적으로 투명한 픽셀에는 실제 색상 값이 있습니다. 입력 이미지와 함께 이를 사용하여 전체 결과를 재구성할 수 있습니다. Learn more about the Delta PNG format

delta_png를 사용할 때 background.color, result.crop_to_foreground, result.margin, result.target_sizeresult.vertical_alignment는 무시됩니다. 결과는 입력 이미지와 크기가 동일해야 합니다. 그렇지 않으면 디코딩이 실패하므로 max_pixels로 인해 입력이 축소되어서는 안 됩니다.


정수, 1 에서o 100로, 기본값: 75

JPEG 결과를 인코딩할 때 사용할 품질입니다.

결과 헤더

X-Credits-Charged 실제 청구된 크레딧.
X-Credits-Calculated 생산 요청인 경우 청구되었을 계산된 크레딧. 테스트 요청에 대해서만 반환됩니다.
X-Input-Orientation 입력 이미지에서 읽고 적용한 EXIF 방향 태그. 1부터 8까지의 정수 값입니다. 이는 이미지 로딩 라이브러리가 EXIF 방향을 지원하지 않는 경우 유용합니다. Read more about EXIF orientation here
X-Input-Size 크기 제한이 적용되기 전의 입력 이미지(픽셀 단위)의 [width] [height]입니다.
X-Result-Size 픽셀로 표시된 결과 이미지의 [width] [height].
X-Input-Foreground [top] [left] [width] [height] 입력 이미지 좌표에서 전경의 경계 상자.
X-Result-Foreground [top] [left] [width] [height] 결과 이미지 좌표에서 전경의 경계 상자.

API 변경 로그

날짜변경
2024. 3. 4. 타임아웃에 대한 섹션이 추가되었습니다.
2024. 1. 16. 오류 JSON 개체를 문서화했습니다.
2024. 1. 11. 이제 실제로 X-Credits-Charged 헤더를 반환하고 테스트 요청을 위해 X-Credits-Calculated 헤더를 추가했습니다.
2023. 6. 13. 가독성을 높이기 위해 API를 버전 2로 업데이트하고 매개변수를 camelCase에서 snake_case로 업데이트했습니다. 이전 버전의 API는 더 이상 지원되지 않지만 계속 사용할 수 있습니다.
2023. 5. 3. 크게 확장된 API 매개변수.
2023. 4. 28. API 엔드포인트를 업데이트했습니다.
2023. 3. 21. 초판.
API 키 가져오기