BEN API Documentation
The Background Erase Network (BEN) API provides a simple HTTP interface for removing backgrounds from images. Our API is designed to be language-agnostic and can be integrated with any programming language that supports HTTP requests.
Authentication
All API requests require an API token for authentication. You can obtain your token from your account dashboard. Include this token in the Authorization header of your requests.
API Endpoint
The main endpoint for background removal is:
POST https://api.backgrounderase.net/v2
Basic CURL Example
curl -X POST "https://api.backgrounderase.net/v2" \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"image\": \"YOUR_BASE64_ENCODED_IMAGE\"}"
Python Integration Guide
Our Python SDK provides a streamlined way to integrate background removal capabilities into your Python applications. This integration supports both synchronous and asynchronous operations, handles image preprocessing automatically, and includes built-in error handling. The complete source code is available in this GitHub repo.
Prerequisites
Before getting started, ensure you have:
- Python 3.7 or higher installed on your system
- pip package manager
- Basic familiarity with Python and command-line operations
Installation
You can install our Python SDK by cloning the repository and installing the required dependencies:
git clone https://github.com/PramaLLC/ben-api-python-integration
cd ben-api-python-integration
pip install -r requirements.txt
The installation process will automatically set up all necessary dependencies, including PIL for image processing and requests for API communication.
Authentication Setup
To use the API, you'll need to obtain an api token. This requires an active business subscription, which you can purchase through our pricing page.
Once you have an active subscription:
- Navigate to your account dashboard
- Scroll to the "API Access" section at the bottom
- Generate a new token
- Store this token securely - you'll need it for API requests
Basic Usage Example
Here's a simple example demonstrating how to remove the background from an image:
from PIL import Image
from main import predict_image
# Load your image
image = Image.open("image.jpg")
# Process the image
mask, foreground = predict_image(image, "your_ben_api_token")
# Save the results
mask.save("mask.png") # Saves the transparency mask
foreground.save("foreground.png") # Saves the image with background removed
The predict_image function returns two PIL Image objects:
- mask: A grayscale image where white represents the foreground and black represents the background
- foreground: The original image with the background removed, saved with transparency
Running the Example
To execute the example code, save it as example.py and run it from your terminal:
python example.py
Node.js Integration Guide
Our Node.js SDK provides a powerful way to integrate background removal capabilities into your JavaScript applications. This implementation supports both CommonJS and ES modules, includes comprehensive error handling, and is designed for server-side image processing. The complete source code is available in our GitHub repo.
Prerequisites
Before getting started, ensure you have:
- Node.js 14.x or higher installed
- npm or yarn package manager
- Basic understanding of async/await and Node.js file operations
Installation
Clone our repository and install the required dependencies:
git clone https://github.com/PramaLLC/ben-api-node-integration
cd ben-api-node-integration
npm install
Authentication Setup
To use the API, you'll need a business subscription and an API token. Visit our pricing page to subscribe, then generate your token from the account dashboard.
Basic Usage Example
Create a file named example.js with the following code:
const fs = require('fs');
const path = require('path');
const { predictImage } = require('./main');
async function main() {
try {
const apiKey = 'your_ben_api_token'; // Replace with your API token
const apiUrl = 'https://api.backgrounderase.net/v2';
// Load image file
const inputPath = path.join(__dirname, 'image.jpg');
const originalBuffer = fs.readFileSync(inputPath);
// Get prediction
const result = await predictImage(originalBuffer, apiKey, apiUrl);
if (!result) {
console.error('Failed to get a valid result from predictImage.');
return;
}
// Save results
const { mask, foreground } = result;
fs.writeFileSync(path.join(__dirname, 'result.png'), foreground);
fs.writeFileSync(path.join(__dirname, 'mask.png'), mask);
} catch (err) {
console.error('Error:', err);
}
}
main();
Running the Example
Execute the example code using Node.js:
node example.js
Response Format
The API returns two primary components:
- mask: A binary buffer containing the segmentation mask as a PNG image
- foreground: A buffer containing the processed image with the background removed
Error Handling
The SDK includes comprehensive error handling for common scenarios:
- Network connectivity issues
- Authentication failures
- Invalid image formats
- API rate limiting
Docker Integration Guide
Our Docker integration provides a Flask server implementation of the Background Removal API, allowing you to run the service in an isolated container environment. The complete source code is available in our GitHub repo.
Prerequisites
Before starting, ensure you have:
- Docker installed and running on your system
- Basic understanding of Docker and container operations
- Valid API token from Background Erase Network
Installation
Clone the repository and build the Docker container:
git clone https://github.com/PramaLLC/ben-api-python-docker-integration
cd ben-api-python-docker-integration
docker build -t ben-api .
docker run -p 8585:8585 ben-api
The server will be available at http://localhost:8585
Making Requests
Here's a Python example demonstrating how to interact with the Docker server:
import requests
import base64
from PIL import Image
import io
def test_flask_server():
# API endpoint
url = 'http://localhost:8585'
# Your API key
headers = {
'Content-Type': 'application/json',
'x-api-key': 'your_ben_api_token' # your ben api token here
}
# Read and encode image
with open('image.jpg', 'rb') as image_file: # your image file path
image_data = base64.b64encode(image_file.read()).decode('utf-8')
# Prepare the payload
payload = {
'image': image_data
}
try:
# Make POST request
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
# Save returned image
image_data = base64.b64decode(response.json()['image'])
image = Image.open(io.BytesIO(image_data))
image.save('response_image.png')
print("Response image saved as 'response_image.png'")
else:
print(f"Error: {response.text}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
test_flask_server()
Docker Configuration
The container exposes the following configurations:
- Port: 8585 (configurable via Docker run command)
- Environment Variables: BEN_API_TOKEN for authentication
- Volume Mounts: Optional for persistent storage
Health Checks
The server provides a health check endpoint at /health
. You can monitor the server's status with:
curl http://localhost:8585/health
Production Deployment
For production environments, consider:
- Using Docker Compose for orchestration
- Implementing proper logging and monitoring
- Setting up container restart policies
- Configuring appropriate resource limits
Frequently Asked Questions
What latency should I expect when using the BEN API?
For properly optimized images, the API typically responds within 600-700ms. Response times can vary based on image complexity and size. To achieve optimal performance:
- Resize images to 1024x1024 px before sending the request
- Use JPEG format with 85% quality before encoding into base64
- Ensure stable network connectivity
Enterprise customers with high-volume needs can access our edge network for latencies as low as 300ms. If you consistently experience latency above 1 second, contact our support team for optimization assistance.
Why does the BEN API return a grayscale mask?
Our API returns a grayscale mask in order to reduce network transfer latency. A grayscale mask returned from our servers is reconstructed on the client side which significantly reduces end user latency.
What image formats are supported?
The API supports JPEG, PNG, and WebP formats encoded into base64. For optimal performance, we recommend using JPEG format with 85% compression. Maximum file size is currently 10MB.
What is the maximum number of API calls I can make per minute?
The rate limit we've implemented is generous. Those on the business plan with access to the BEN API will not be rate limited up to 1 thousand requests per second. Enterprise customers have custom limits based on their needs if this should exceed the 1000 per second default value.
How does the API handle complex images with multiple subjects?
The API is trained to identify and remove backgrounds from images with multiple subjects. It uses our advanced machine learning model to detect foreground elements and generate accurate masks for all subjects in the image. For best results, ensure subjects are clearly visible and not heavily overlapping.
Can I specify which parts of the image to keep or remove?
Currently, the API automatically determines foreground and background elements. More precise control is currently limited to enterprise customers only. We plan to roll out this functionality to users under the business plan in the near future.
What happens if the API fails to process an image?
If the API encounters an error, it will return an error message which you can reference in the troubleshooting section below in order to solve the error. Common issues include invalid image format, file size exceeding limits, or corrupted image data.
Troubleshooting
Forbidden
There are three main situations where our users encounter this error:
- You have not waited long enough after generating your api key to start using it. The process generally takes about 60 seconds to fully initialize globally.
- You are not using a valid API key. Try to generate a new key or verify your existing subscription is still active.
- You are not using the valid URL for our API. The URL you should send requests to is:
https://api.backgrounderase.net/v2
Why am I getting 'Invalid Image Format'?
This error is occuring because either:
- You're image isn't properly base64 encoded. The image encoded into a base64 string should contain no prefixes like "data:image/jpeg;base64".
- You are not using a supported image type. The image types we accept are JPEG, WEBP, PNG, GIF, TIFF, and BMP.
Why is my request timing out?
This is occuring because either:
- Network connectivity issues on the client side
- Image file size exceeds 50MB limit. You should resize image to 1024 by 1024 px strictly before sending the request to our API
- High server load (rare)
Why is my response mask quality poor?
If this is occuring please check:
- Your image resolution (recommend 1024 by 1024 px)
- If possible ensure some detctable distinction between the subject and its background.
- Verify image isn't heavily compressed. We recommend JPEG quality of 85%.
Why is my latency higher than expected?
If this is occuring please check:
- the dimensions and format of your image before sending. We recommend 1024 by 1024 px and JPEG with 85% quality
- the stability of your network connection
- If you are outside of the United States you can expect additional latency due to our servers being located in the United States. If you are an enterprise outside of the US looking for services from us we are happy to set up a dedicated endpoint located closer to you to reduce network transmission latency.
I have a technical question about an issue/bug or I need integration help.
We provide support for any question or issue - including simple integration help. Please contact us at [email protected] with the relevant information and we'll help you as soon as possible.